mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(eks): give Services of the EKS Auto Mode NLB class a Network Load Balancer (#9316)
While a cluster has Auto Mode's load balancing capability on, a LoadBalancer Service whose loadBalancerClass is eks.amazonaws.com/nlb gets a Network Load Balancer in the cluster's subnets: a TCP target group per TCP port on its NodePort, with a TCP health check and the cluster's node registered by instance ID, and a listener on the Service port. Once the node is registered, the DNS name is written to the Service's status, in a patch that names its UID. A reconciler reads the Services with kubectl every 10 seconds; each pass makes whatever a Service's ports lack and removes what dropped ports had. The load balancers carry eks:eks-cluster-name and service.eks.amazonaws.com/stack, the only keys AmazonEKSLoadBalancingPolicy lets Auto Mode set, and go with the Service, with the cluster and when its load balancing is turned off. ElasticLoadBalancing.loadBalancingOn replaces two copies of the on check. Part of #8914.
This commit is contained in:
1 parent
fed52ed57a
commit
de6aaa4e0a
8 files changed
+977
-3
No files matched your search
@@ -0,0 +1,362 @@
|
||||
package io.floci.aws.services.eks;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.docker.ContainerExec;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.eks.model.Cluster;
|
||||
import io.floci.aws.services.eks.model.ClusterStatus;
|
||||
import io.floci.aws.services.eks.model.ElasticLoadBalancing;
|
||||
import io.floci.aws.services.eks.model.KubernetesNetworkConfig;
|
||||
import io.floci.aws.services.eks.model.ResourcesVpcConfig;
|
||||
import io.floci.aws.services.elbv2.ElbV2Service;
|
||||
import io.floci.aws.services.elbv2.model.Action;
|
||||
import io.floci.aws.services.elbv2.model.Listener;
|
||||
import io.floci.aws.services.elbv2.model.LoadBalancer;
|
||||
import io.floci.aws.services.elbv2.model.TargetDescription;
|
||||
import io.floci.aws.services.elbv2.model.TargetGroup;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class EksAutoModeLoadBalancersTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String SERVICES = """
|
||||
{"items": [
|
||||
{"metadata": {"namespace": "shop", "name": "web", "uid": "uid-web",
|
||||
"annotations": {"service.beta.kubernetes.io/aws-load-balancer-scheme": "internet-facing"}},
|
||||
"spec": {"type": "LoadBalancer", "loadBalancerClass": "eks.amazonaws.com/nlb",
|
||||
"ports": [{"protocol": "TCP", "port": 80, "nodePort": 31080},
|
||||
{"protocol": "UDP", "port": 53, "nodePort": 31053}]}},
|
||||
{"metadata": {"namespace": "shop", "name": "klipper"},
|
||||
"spec": {"type": "LoadBalancer", "ports": [{"protocol": "TCP", "port": 80, "nodePort": 32080}]}},
|
||||
{"metadata": {"namespace": "shop", "name": "internal"},
|
||||
"spec": {"type": "ClusterIP", "loadBalancerClass": "eks.amazonaws.com/nlb",
|
||||
"ports": [{"protocol": "TCP", "port": 80}]}},
|
||||
{"metadata": {"namespace": "shop", "name": "dns"},
|
||||
"spec": {"type": "LoadBalancer", "loadBalancerClass": "eks.amazonaws.com/nlb",
|
||||
"ports": [{"protocol": "UDP", "port": 53, "nodePort": 31054}]}},
|
||||
{"metadata": {"namespace": "shop", "name": "unallocated"},
|
||||
"spec": {"type": "LoadBalancer", "loadBalancerClass": "eks.amazonaws.com/nlb",
|
||||
"allocateLoadBalancerNodePorts": false, "ports": [{"protocol": "TCP", "port": 80}]}}
|
||||
]}""";
|
||||
|
||||
private final EksService eksService = mock(EksService.class);
|
||||
private final EksClusterManager clusterManager = mock(EksClusterManager.class);
|
||||
private final ElbV2Service elb = mock(ElbV2Service.class);
|
||||
private final EksAutoModeLoadBalancers loadBalancers = new EksAutoModeLoadBalancers(eksService, clusterManager, elb,
|
||||
mock(EmulatorConfig.class, RETURNS_DEEP_STUBS));
|
||||
/** What the mocked ELBv2 holds, by ARN. */
|
||||
private final List<LoadBalancer> lbs = new ArrayList<>();
|
||||
private final List<TargetGroup> groups = new ArrayList<>();
|
||||
private final Map<String, Map<String, String>> tags = new HashMap<>();
|
||||
|
||||
@Test
|
||||
void onlyLoadBalancerServicesOfTheAutoModeClassWithATcpNodePortGetOne() throws Exception {
|
||||
List<EksAutoModeLoadBalancers.NlbService> services =
|
||||
EksAutoModeLoadBalancers.nlbServices(new ObjectMapper().readTree(SERVICES));
|
||||
|
||||
// UDP gets no listener, as Floci's load balancers serve TCP and HTTP only; a Service with no TCP NodePort
|
||||
// (only UDP, or allocateLoadBalancerNodePorts false) gets no load balancer.
|
||||
assertEquals(List.of(new EksAutoModeLoadBalancers.NlbService("shop", "web", "uid-web", "internet-facing",
|
||||
List.of(new EksAutoModeLoadBalancers.ServicePort("TCP", 80, 31080)))), services);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServiceWithoutASchemeAnnotationGetsAnInternalLoadBalancer() throws Exception {
|
||||
List<EksAutoModeLoadBalancers.NlbService> services = EksAutoModeLoadBalancers.nlbServices(new ObjectMapper()
|
||||
.readTree(SERVICES.replace(EksAutoModeLoadBalancers.SCHEME_ANNOTATION, "example.com/other")));
|
||||
|
||||
assertEquals("internal", services.getFirst().scheme());
|
||||
}
|
||||
|
||||
@Test
|
||||
void namesFitElbV2KeepTheirPortAndDifferBetweenClustersAndPorts() {
|
||||
String stack = "a-very-long-namespace/a-very-long-service-name";
|
||||
|
||||
String name = EksAutoModeLoadBalancers.resourceName(cluster("prod"), stack, "");
|
||||
String port = EksAutoModeLoadBalancers.resourceName(cluster("prod"), stack, "-65535");
|
||||
String other = EksAutoModeLoadBalancers.resourceName(cluster("dev"), stack, "");
|
||||
|
||||
for (String each : List.of(name, port, other)) {
|
||||
assertTrue(each.length() <= 32 && each.matches("[A-Za-z0-9-]+") && !each.endsWith("-"), each);
|
||||
}
|
||||
assertTrue(port.matches(".*-65535-[0-9a-f]{10}"), port);
|
||||
assertNotEquals(name, port);
|
||||
assertNotEquals(name, other);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNewServiceGetsALoadBalancerATcpTargetGroupWithItsNodeAListenerAndItsDnsName() {
|
||||
Cluster cluster = cluster("prod");
|
||||
servicesAre(cluster, SERVICES);
|
||||
nodeIs(cluster, "i-0node");
|
||||
holdElb();
|
||||
|
||||
loadBalancers.reconcile(cluster, REGION);
|
||||
|
||||
Map<String, String> serviceTags = Map.of(EksAutoModeLoadBalancers.CLUSTER_TAG, "prod",
|
||||
EksAutoModeLoadBalancers.STACK_TAG, "shop/web");
|
||||
verify(elb).createLoadBalancer(eq(REGION), eq(EksAutoModeLoadBalancers.resourceName(cluster, "shop/web", "")),
|
||||
eq("internet-facing"), eq("network"), eq("ipv4"), eq(List.of("subnet-a", "subnet-b")), eq(List.of()),
|
||||
eq(serviceTags));
|
||||
// A TCP health check: ELBv2's default would probe the NodePort with HTTP.
|
||||
verify(elb).createTargetGroup(eq(REGION), eq(EksAutoModeLoadBalancers.resourceName(cluster, "shop/web", "-80")),
|
||||
eq("TCP"), isNull(), eq(31080), eq("vpc-1"), eq("instance"), eq("TCP"), isNull(), isNull(), isNull(),
|
||||
isNull(), isNull(), isNull(), isNull(), isNull(), eq("ipv4"), eq(serviceTags));
|
||||
verify(elb).registerTargets(eq(REGION), eq(groups.getFirst().getTargetGroupArn()),
|
||||
argThat(targets -> targets.size() == 1 && "i-0node".equals(targets.getFirst().getId())));
|
||||
ArgumentCaptor<List<Action>> forward = ArgumentCaptor.forClass(List.class);
|
||||
verify(elb).createListener(eq(REGION), eq("arn:lb-1"), eq("TCP"), eq(80), isNull(), isNull(),
|
||||
forward.capture(), isNull(), eq(serviceTags));
|
||||
assertEquals(groups.getFirst().getTargetGroupArn(), forward.getValue().getFirst().getTargetGroupArn());
|
||||
verify(elb, never()).createListener(any(), any(), eq("UDP"), anyInt(), any(), any(), any(), any(), any());
|
||||
verifyStatus(cluster, "{\"metadata\":{\"uid\":\"uid-web\"},"
|
||||
+ "\"status\":{\"loadBalancer\":{\"ingress\":[{\"hostname\":\"lb-1.elb.test\"}]}}}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPassThatStoppedAfterTheLoadBalancerIsFinishedByTheNext() {
|
||||
Cluster cluster = cluster("prod");
|
||||
servicesAre(cluster, SERVICES);
|
||||
nodeIs(cluster, "i-0node");
|
||||
holdElb();
|
||||
LoadBalancer lb = ownLoadBalancer(cluster, "shop/web");
|
||||
|
||||
loadBalancers.reconcile(cluster, REGION);
|
||||
|
||||
verify(elb, never()).createLoadBalancer(any(), any(), any(), any(), any(), any(), any(), any());
|
||||
verify(elb).createTargetGroup(eq(REGION), anyString(), eq("TCP"), isNull(), eq(31080), any(), any(), any(),
|
||||
any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
verify(elb).createListener(eq(REGION), eq(lb.getLoadBalancerArn()), eq("TCP"), eq(80), any(), any(), anyList(),
|
||||
any(), any());
|
||||
verifyStatus(cluster, "{\"metadata\":{\"uid\":\"uid-web\"},"
|
||||
+ "\"status\":{\"loadBalancer\":{\"ingress\":[{\"hostname\":\"" + lb.getDnsName() + "\"}]}}}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServiceGetsNoAddressUntilTheNodeIsRegisteredAndTheNodeIsRegisteredOnceItIs() {
|
||||
Cluster cluster = cluster("prod");
|
||||
servicesAre(cluster, SERVICES);
|
||||
holdElb();
|
||||
|
||||
loadBalancers.reconcile(cluster, REGION);
|
||||
|
||||
verify(elb, never()).registerTargets(any(), any(), any());
|
||||
verify(clusterManager, never()).execInContainerForResult(any(), argThat(cmd -> "patch".equals(cmd[1])), anyInt());
|
||||
|
||||
nodeIs(cluster, "i-0node");
|
||||
loadBalancers.reconcile(cluster, REGION);
|
||||
|
||||
verify(elb).registerTargets(eq(REGION), eq(groups.getFirst().getTargetGroupArn()),
|
||||
argThat(targets -> "i-0node".equals(targets.getFirst().getId())));
|
||||
verify(elb).createLoadBalancer(any(), any(), any(), any(), any(), any(), any(), any());
|
||||
verifyStatus(cluster, "{\"metadata\":{\"uid\":\"uid-web\"},"
|
||||
+ "\"status\":{\"loadBalancer\":{\"ingress\":[{\"hostname\":\"lb-1.elb.test\"}]}}}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGoneServicesLoadBalancerGoesWithItsListenersAndEveryTargetGroupMadeForItAttachedOrNot() {
|
||||
Cluster cluster = cluster("prod");
|
||||
servicesAre(cluster, "{\"items\": []}");
|
||||
holdElb();
|
||||
LoadBalancer lb = ownLoadBalancer(cluster, "shop/gone");
|
||||
Listener listener = new Listener();
|
||||
listener.setListenerArn("arn:listener");
|
||||
when(elb.describeListeners(REGION, lb.getLoadBalancerArn(), null)).thenReturn(List.of(listener));
|
||||
// A target group whose listener was never made has no load balancer to be found through.
|
||||
TargetGroup orphan = ownTargetGroup(cluster, "shop/gone", 8080);
|
||||
|
||||
loadBalancers.reconcile(cluster, REGION);
|
||||
|
||||
verify(elb).deleteListener(REGION, "arn:listener");
|
||||
verify(elb).deleteLoadBalancer(REGION, lb.getLoadBalancerArn());
|
||||
verify(elb).deleteTargetGroup(REGION, orphan.getTargetGroupArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLoadBalancerWithTheTagsButNotTheNameThisGivesIsLeftAlone() {
|
||||
Cluster cluster = cluster("prod");
|
||||
servicesAre(cluster, "{\"items\": []}");
|
||||
holdElb();
|
||||
LoadBalancer someoneElses = loadBalancer("arn:theirs", "theirs", "network", "prod", "shop/web");
|
||||
TargetGroup theirGroup = targetGroup("arn:their-tg", "k8s-shop-web-80-0123456789", 31080, "prod", "shop/web");
|
||||
|
||||
loadBalancers.reconcile(cluster, REGION);
|
||||
|
||||
verify(elb, never()).deleteLoadBalancer(REGION, someoneElses.getLoadBalancerArn());
|
||||
verify(elb, never()).deleteTargetGroup(REGION, theirGroup.getTargetGroupArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherClustersLoadBalancerIsLeftAlone() {
|
||||
Cluster cluster = cluster("prod");
|
||||
servicesAre(cluster, "{\"items\": []}");
|
||||
holdElb();
|
||||
ownLoadBalancer(cluster("dev"), "shop/web");
|
||||
|
||||
loadBalancers.reconcile(cluster, REGION);
|
||||
|
||||
verify(elb, never()).deleteLoadBalancer(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterWhoseLoadBalancingIsOffLosesItsLoadBalancers() {
|
||||
Cluster cluster = cluster("prod");
|
||||
cluster.getKubernetesNetworkConfig().setElasticLoadBalancing(new ElasticLoadBalancing(false));
|
||||
when(eksService.runningClusters()).thenReturn(List.of(new AccountAwareStorageBackend.AccountEntry<>(
|
||||
"000000000000", "prod", cluster)));
|
||||
when(eksService.clusterRegion(cluster)).thenReturn(REGION);
|
||||
holdElb();
|
||||
LoadBalancer lb = ownLoadBalancer(cluster, "shop/web");
|
||||
|
||||
loadBalancers.reconcileAll();
|
||||
|
||||
verify(elb).deleteLoadBalancer(REGION, lb.getLoadBalancerArn());
|
||||
verify(clusterManager, never()).execInContainerForResult(any(), any(), anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTargetGroupWhoseNodePortChangedIsMadeAgainWithItsListener() {
|
||||
Cluster cluster = cluster("prod");
|
||||
servicesAre(cluster, SERVICES);
|
||||
nodeIs(cluster, "i-0node");
|
||||
holdElb();
|
||||
LoadBalancer lb = ownLoadBalancer(cluster, "shop/web");
|
||||
TargetGroup stale = ownTargetGroup(cluster, "shop/web", 80);
|
||||
stale.setPort(30999);
|
||||
Listener listener = new Listener();
|
||||
listener.setListenerArn("arn:listener-80");
|
||||
listener.setPort(80);
|
||||
when(elb.describeListeners(REGION, lb.getLoadBalancerArn(), null)).thenReturn(List.of(listener));
|
||||
|
||||
loadBalancers.reconcile(cluster, REGION);
|
||||
|
||||
verify(elb).deleteListener(REGION, "arn:listener-80");
|
||||
verify(elb).deleteTargetGroup(REGION, stale.getTargetGroupArn());
|
||||
verify(elb).createTargetGroup(eq(REGION), anyString(), eq("TCP"), isNull(), eq(31080), any(), any(), any(),
|
||||
any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
verify(elb).createListener(eq(REGION), eq(lb.getLoadBalancerArn()), eq("TCP"), eq(80), any(), any(), anyList(),
|
||||
any(), any());
|
||||
}
|
||||
|
||||
/** The mocked ELBv2 lists and tags what the test and the reconciler put in it. */
|
||||
private void holdElb() {
|
||||
when(elb.describeLoadBalancers(REGION, null, null, null, null)).thenAnswer(inv -> List.copyOf(lbs));
|
||||
when(elb.describeTargetGroups(REGION, null, null, null)).thenAnswer(inv -> List.copyOf(groups));
|
||||
when(elb.describeTags(anyList())).thenAnswer(inv -> {
|
||||
Map<String, Map<String, String>> found = new HashMap<>();
|
||||
for (String arn : inv.<List<String>>getArgument(0)) {
|
||||
found.put(arn, tags.getOrDefault(arn, Map.of()));
|
||||
}
|
||||
return found;
|
||||
});
|
||||
when(elb.createLoadBalancer(anyString(), anyString(), anyString(), anyString(), anyString(), anyList(),
|
||||
anyList(), any())).thenAnswer(inv -> {
|
||||
Map<String, String> made = inv.getArgument(7);
|
||||
return loadBalancer("arn:lb-" + (lbs.size() + 1), inv.getArgument(1), "network",
|
||||
made.get(EksAutoModeLoadBalancers.CLUSTER_TAG), made.get(EksAutoModeLoadBalancers.STACK_TAG));
|
||||
});
|
||||
when(elb.createTargetGroup(anyString(), anyString(), anyString(), any(), anyInt(), any(), anyString(), any(),
|
||||
any(), any(), any(), any(), any(), any(), any(), any(), any(), any())).thenAnswer(inv -> {
|
||||
Map<String, String> made = inv.getArgument(17);
|
||||
return targetGroup("arn:tg-" + (groups.size() + 1), inv.getArgument(1), inv.getArgument(4),
|
||||
made.get(EksAutoModeLoadBalancers.CLUSTER_TAG), made.get(EksAutoModeLoadBalancers.STACK_TAG));
|
||||
});
|
||||
}
|
||||
|
||||
private LoadBalancer ownLoadBalancer(Cluster cluster, String stack) {
|
||||
return loadBalancer("arn:own-" + stack, EksAutoModeLoadBalancers.resourceName(cluster, stack, ""), "network",
|
||||
cluster.getName(), stack);
|
||||
}
|
||||
|
||||
private TargetGroup ownTargetGroup(Cluster cluster, String stack, int servicePort) {
|
||||
return targetGroup("arn:own-tg-" + stack + "-" + servicePort,
|
||||
EksAutoModeLoadBalancers.resourceName(cluster, stack, "-" + servicePort), 31080, cluster.getName(), stack);
|
||||
}
|
||||
|
||||
private LoadBalancer loadBalancer(String arn, String name, String type, String clusterName, String stack) {
|
||||
LoadBalancer lb = new LoadBalancer();
|
||||
lb.setLoadBalancerArn(arn);
|
||||
lb.setLoadBalancerName(name);
|
||||
lb.setType(type);
|
||||
lb.setDnsName(arn.substring(arn.indexOf(':') + 1) + ".elb.test");
|
||||
lbs.add(lb);
|
||||
if (clusterName != null) {
|
||||
tags.put(arn, Map.of(EksAutoModeLoadBalancers.CLUSTER_TAG, clusterName, EksAutoModeLoadBalancers.STACK_TAG,
|
||||
stack));
|
||||
}
|
||||
return lb;
|
||||
}
|
||||
|
||||
private TargetGroup targetGroup(String arn, String name, int port, String clusterName, String stack) {
|
||||
TargetGroup group = new TargetGroup();
|
||||
group.setTargetGroupArn(arn);
|
||||
group.setTargetGroupName(name);
|
||||
group.setPort(port);
|
||||
group.setTargets(new ArrayList<TargetDescription>());
|
||||
groups.add(group);
|
||||
tags.put(arn, Map.of(EksAutoModeLoadBalancers.CLUSTER_TAG, clusterName, EksAutoModeLoadBalancers.STACK_TAG,
|
||||
stack));
|
||||
return group;
|
||||
}
|
||||
|
||||
private void nodeIs(Cluster cluster, String instanceId) {
|
||||
Instance node = new Instance();
|
||||
node.setInstanceId(instanceId);
|
||||
when(clusterManager.getRegisteredClusterNodeInstance(cluster)).thenReturn(node);
|
||||
}
|
||||
|
||||
private void verifyStatus(Cluster cluster, String patch) {
|
||||
verify(clusterManager).execInContainerForResult(eq(cluster.getContainerId()), argThat(cmd -> List.of(cmd).equals(
|
||||
List.of("kubectl", "patch", "service", "web", "-n", "shop", "--subresource=status", "--type=merge", "-p",
|
||||
patch))), anyInt());
|
||||
}
|
||||
|
||||
private void servicesAre(Cluster cluster, String json) {
|
||||
when(clusterManager.execInContainerForResult(eq(cluster.getContainerId()),
|
||||
argThat(cmd -> cmd.length > 2 && "get".equals(cmd[1])), anyInt()))
|
||||
.thenReturn(new ContainerExec.Result(0, json, "", false));
|
||||
when(clusterManager.execInContainerForResult(eq(cluster.getContainerId()),
|
||||
argThat(cmd -> cmd.length > 2 && "patch".equals(cmd[1])), anyInt()))
|
||||
.thenReturn(new ContainerExec.Result(0, "patched", "", false));
|
||||
}
|
||||
|
||||
private static Cluster cluster(String name) {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName(name);
|
||||
cluster.setArn("arn:aws:eks:us-east-1:000000000000:cluster/" + name);
|
||||
cluster.setContainerId("k3s-" + name);
|
||||
cluster.setStatus(ClusterStatus.ACTIVE);
|
||||
ResourcesVpcConfig vpc = new ResourcesVpcConfig();
|
||||
vpc.setSubnetIds(List.of("subnet-a", "subnet-b"));
|
||||
vpc.setVpcId("vpc-1");
|
||||
cluster.setResourcesVpcConfig(vpc);
|
||||
KubernetesNetworkConfig network = new KubernetesNetworkConfig();
|
||||
network.setElasticLoadBalancing(new ElasticLoadBalancing(true));
|
||||
cluster.setKubernetesNetworkConfig(network);
|
||||
return cluster;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package io.floci.aws.services.eks;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.eks.model.Cluster;
|
||||
import io.floci.aws.services.eks.model.ResourcesVpcConfig;
|
||||
import io.floci.aws.services.elbv2.ElbV2Service;
|
||||
import io.floci.aws.services.elbv2.model.LoadBalancer;
|
||||
import io.floci.aws.services.elbv2.model.TargetGroup;
|
||||
import io.floci.aws.testing.DockerAvailability;
|
||||
import io.floci.aws.testing.EksTestNode;
|
||||
import io.floci.aws.testing.RdsMockProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
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.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/**
|
||||
* EKS Auto Mode load balancing on a real k3s node: a LoadBalancer Service of the {@code eks.amazonaws.com/nlb}
|
||||
* class gets a Network Load Balancer with a target group on its NodePort, its DNS name is written to the
|
||||
* Service's status, and the load balancer goes with the Service. The reconciler is called directly: EKS is mocked
|
||||
* in {@link RdsMockProfile}, which the other classes that run a real cluster use, so its interval doesn't run.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(RdsMockProfile.class)
|
||||
class EksAutoModeNlbDockerIntegrationTest {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EksAutoModeNlbDockerIntegrationTest.class);
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@Inject
|
||||
DockerClient dockerClient;
|
||||
|
||||
@Inject
|
||||
EksClusterManager eksClusterManager;
|
||||
|
||||
@Inject
|
||||
EksAutoModeLoadBalancers loadBalancers;
|
||||
|
||||
@Inject
|
||||
ElbV2Service elb;
|
||||
|
||||
@Inject
|
||||
Ec2Service ec2;
|
||||
|
||||
private Cluster cluster;
|
||||
|
||||
@BeforeEach
|
||||
void requireDocker() {
|
||||
boolean dockerAvailable = DockerAvailability.answers(dockerClient);
|
||||
if (!dockerAvailable) {
|
||||
LOG.warn("Docker daemon is not available; skipping EksAutoModeNlbDockerIntegrationTest");
|
||||
}
|
||||
Assumptions.assumeTrue(dockerAvailable, "Docker daemon must be available for the Auto Mode NLB test");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
if (cluster != null) {
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> loadBalancersOf(cluster.getName())
|
||||
.forEach(lb -> elb.deleteLoadBalancer(REGION, lb.getLoadBalancerArn())));
|
||||
try {
|
||||
eksClusterManager.stopCluster(cluster);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to stop test cluster: {0}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServiceOfTheNlbClassGetsALoadBalancerOnItsNodePortWhichGoesWithIt() {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
cluster = EksTestNode.cluster(ACCOUNT, "nlb-" + suffix);
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> {
|
||||
String vpc = ec2.createVpc(REGION, "10.61.0.0/16", false).getVpcId();
|
||||
String subnet = ec2.createSubnet(REGION, vpc, "10.61.1.0/24", "us-east-1a").getSubnetId();
|
||||
ResourcesVpcConfig network = new ResourcesVpcConfig();
|
||||
network.setVpcId(vpc);
|
||||
network.setSubnetIds(List.of(subnet));
|
||||
cluster.setResourcesVpcConfig(network);
|
||||
});
|
||||
EksTestNode node = EksTestNode.start(dockerClient, eksClusterManager, cluster, Duration.ofSeconds(90));
|
||||
node.apply("""
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: web
|
||||
namespace: default
|
||||
annotations:
|
||||
service.beta.kubernetes.io/aws-load-balancer-scheme: internet-facing
|
||||
spec:
|
||||
type: LoadBalancer
|
||||
loadBalancerClass: eks.amazonaws.com/nlb
|
||||
selector:
|
||||
app: web
|
||||
ports:
|
||||
- port: 18080
|
||||
targetPort: 80
|
||||
protocol: TCP""");
|
||||
int nodePort = Integer.parseInt(node.kubectlOutput("get", "service", "web", "-n", "default",
|
||||
"-o", "jsonpath={.spec.ports[0].nodePort}"));
|
||||
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> loadBalancers.reconcile(cluster, REGION));
|
||||
|
||||
List<LoadBalancer> created = RequestScopes.callAs(ACCOUNT, REGION, () -> loadBalancersOf(cluster.getName()));
|
||||
assertEquals(1, created.size());
|
||||
LoadBalancer lb = created.getFirst();
|
||||
assertEquals("network", lb.getType());
|
||||
assertEquals("internet-facing", lb.getScheme());
|
||||
List<TargetGroup> groups = RequestScopes.callAs(ACCOUNT, REGION,
|
||||
() -> elb.describeTargetGroups(REGION, lb.getLoadBalancerArn(), null, null));
|
||||
assertEquals(1, groups.size());
|
||||
assertEquals(nodePort, groups.getFirst().getPort());
|
||||
assertEquals("instance", groups.getFirst().getTargetType());
|
||||
assertEquals(lb.getDnsName(), node.kubectlOutput("get", "service", "web", "-n", "default",
|
||||
"-o", "jsonpath={.status.loadBalancer.ingress[0].hostname}"));
|
||||
|
||||
node.kubectl("delete", "service", "web", "-n", "default");
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> loadBalancers.reconcile(cluster, REGION));
|
||||
|
||||
await("load balancer deleted").atMost(Duration.ofSeconds(10))
|
||||
.until(() -> RequestScopes.callAs(ACCOUNT, REGION, () -> loadBalancersOf(cluster.getName())).isEmpty());
|
||||
AwsException gone = assertThrows(AwsException.class, () -> RequestScopes.callAs(ACCOUNT, REGION,
|
||||
() -> elb.describeTargetGroups(REGION, null, List.of(groups.getFirst().getTargetGroupArn()), null)));
|
||||
assertEquals("TargetGroupNotFound", gone.getErrorCode());
|
||||
}
|
||||
|
||||
private List<LoadBalancer> loadBalancersOf(String clusterName) {
|
||||
List<LoadBalancer> all = elb.describeLoadBalancers(REGION, null, null, null, null);
|
||||
if (all.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
Map<String, Map<String, String>> tags = elb.describeTags(all.stream().map(LoadBalancer::getLoadBalancerArn).toList());
|
||||
return all.stream().filter(lb -> clusterName.equals(
|
||||
tags.getOrDefault(lb.getLoadBalancerArn(), Map.of()).get(EksAutoModeLoadBalancers.CLUSTER_TAG))).toList();
|
||||
}
|
||||
}
|
||||
@@ -632,6 +632,18 @@ class EksServiceTest {
|
||||
verify(clusterManager, never()).detachCluster(any(Cluster.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDeletedClustersAutoModeLoadBalancersGoWithIt() {
|
||||
Cluster cluster = activeCluster();
|
||||
EksService service = serviceWithCluster(cluster, mock(EksClusterManager.class), false);
|
||||
EksAutoModeLoadBalancers loadBalancers = mock(EksAutoModeLoadBalancers.class);
|
||||
service.autoModeLoadBalancers = loadBalancers;
|
||||
|
||||
service.deleteCluster("running-cluster");
|
||||
|
||||
verify(loadBalancers).deleteLoadBalancers(cluster, service.clusterRegion(cluster));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDeleteOverlappingOneStillInProgressIsRejectedAndCannotReviveTheCluster() {
|
||||
Cluster cluster = activeCluster();
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package io.floci.aws.services.eks.model;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class ElasticLoadBalancingTest {
|
||||
|
||||
@Test
|
||||
void loadBalancingIsOnOnlyWhenEnabledIsTrue() {
|
||||
assertTrue(ElasticLoadBalancing.loadBalancingOn(new ElasticLoadBalancing(true)));
|
||||
assertFalse(ElasticLoadBalancing.loadBalancingOn(new ElasticLoadBalancing(false)));
|
||||
assertFalse(ElasticLoadBalancing.loadBalancingOn(new ElasticLoadBalancing(null)));
|
||||
assertFalse(ElasticLoadBalancing.loadBalancingOn(null));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user