mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(ecs): register EC2 tasks in instance target groups as AWS does (#8724)
* fix(ecs): register EC2 tasks in instance target groups as AWS does * fix(ecs): hold instance host ports until the task stops * test(ecs): share one EcsService builder across ECS service tests
This commit is contained in:
1 parent
a221e18838
commit
be34135e5b
17 files changed
+756
-272
No files matched your search
@@ -0,0 +1,60 @@
|
||||
package io.floci.aws.services.ec2;
|
||||
|
||||
import io.floci.aws.core.common.Resettable;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* The host ports of an EC2 instance that something other than the instance's own container
|
||||
* serves. An ECS task in {@code bridge} or {@code host} network mode is placed on a container
|
||||
* instance and is addressed, as on AWS, by that instance's id and the host port it publishes,
|
||||
* but its containers run beside the instance rather than inside it. ECS records here where such a
|
||||
* port is actually reachable, so an ELBv2 {@code instance} target {@code i-...:port} reaches the
|
||||
* task the way AWS forwards it to the instance's primary address on that port.
|
||||
*
|
||||
* <p>Memory only: the tasks that publish these ports do not survive a restart either.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class Ec2InstancePorts implements Resettable {
|
||||
|
||||
/** Where a published instance port is reachable from the Floci process. */
|
||||
public record Endpoint(String host, int port) {}
|
||||
|
||||
private record Key(String accountId, String instanceId, int port) {}
|
||||
|
||||
private final Map<Key, Endpoint> endpoints = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* Records that {@code instanceId}'s {@code port} is served at {@code endpoint}.
|
||||
*
|
||||
* @return false, recording nothing, when another endpoint already holds that port
|
||||
*/
|
||||
public boolean bind(String accountId, String instanceId, int port, Endpoint endpoint) {
|
||||
Endpoint existing = endpoints.putIfAbsent(new Key(accountId, instanceId, port), endpoint);
|
||||
return existing == null || existing.equals(endpoint);
|
||||
}
|
||||
|
||||
/** Releases {@code instanceId}'s {@code port} if {@code endpoint} still holds it. */
|
||||
public void release(String accountId, String instanceId, int port, Endpoint endpoint) {
|
||||
endpoints.remove(new Key(accountId, instanceId, port), endpoint);
|
||||
}
|
||||
|
||||
public boolean isBound(String accountId, String instanceId, int port) {
|
||||
return endpoints.containsKey(new Key(accountId, instanceId, port));
|
||||
}
|
||||
|
||||
public Optional<Endpoint> find(String accountId, String instanceId, int port) {
|
||||
if (accountId == null || instanceId == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.ofNullable(endpoints.get(new Key(accountId, instanceId, port)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
endpoints.clear();
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
package io.floci.aws.services.ecs;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.ec2.Ec2InstancePorts;
|
||||
import io.floci.aws.services.ecs.container.EcsContainerManager;
|
||||
import io.floci.aws.services.ecs.model.Container;
|
||||
import io.floci.aws.services.ecs.model.EcsLoadBalancer;
|
||||
@@ -14,6 +16,7 @@ import io.floci.aws.services.ecs.model.EcsTaskAddress;
|
||||
import io.floci.aws.services.ecs.model.NetworkBinding;
|
||||
import io.floci.aws.services.elbv2.ElbV2Service;
|
||||
import io.floci.aws.services.elbv2.model.TargetDescription;
|
||||
import io.floci.aws.services.elbv2.model.TargetGroup;
|
||||
import io.floci.aws.services.elbv2.model.TargetHealth;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -28,7 +31,8 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
/**
|
||||
* Bridges ECS services to ELBv2: when an ECS service declares a {@code loadBalancers}
|
||||
@@ -42,17 +46,27 @@ import java.util.function.BiConsumer;
|
||||
public class EcsLoadBalancerRegistrar {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EcsLoadBalancerRegistrar.class);
|
||||
// The ECS agent's default range for dynamic host ports on Amazon Linux.
|
||||
private static final int EPHEMERAL_PORT_MIN = 32768;
|
||||
private static final int EPHEMERAL_PORT_MAX = 60999;
|
||||
|
||||
private final ElbV2Service elbV2Service;
|
||||
private final EcsContainerManager containerManager;
|
||||
// taskArn → the targets registered for it, persisted so they can be released after a restart
|
||||
private final AccountAwareStorageBackend<EcsRegisteredTargets> ledger;
|
||||
private final Ec2InstancePorts instancePorts;
|
||||
// taskArn → the container instance host ports the task holds until it stops, memory-only like the
|
||||
// task itself. Each list is immutable and replaced through compute(), which is atomic per task.
|
||||
private final Map<String, List<InstancePort>> heldInstancePorts = new ConcurrentHashMap<>();
|
||||
|
||||
private record InstancePort(String accountId, String instanceId, int port, Ec2InstancePorts.Endpoint endpoint) {}
|
||||
|
||||
@Inject
|
||||
public EcsLoadBalancerRegistrar(ElbV2Service elbV2Service, EcsContainerManager containerManager,
|
||||
StorageFactory storageFactory) {
|
||||
StorageFactory storageFactory, Ec2InstancePorts instancePorts) {
|
||||
this.elbV2Service = elbV2Service;
|
||||
this.containerManager = containerManager;
|
||||
this.instancePorts = instancePorts;
|
||||
this.ledger = storageFactory.create("ecs", "ecs-registered-targets.json",
|
||||
new TypeReference<Map<String, EcsRegisteredTargets>>() {});
|
||||
}
|
||||
@@ -66,9 +80,22 @@ public class EcsLoadBalancerRegistrar {
|
||||
* deregisters a stopping task's target whoever registered it.
|
||||
*/
|
||||
public void registerTask(EcsTask task, EcsServiceModel svc, String region) {
|
||||
registerTask(task, svc, null, region);
|
||||
}
|
||||
|
||||
/**
|
||||
* As {@link #registerTask(EcsTask, EcsServiceModel, String)}, for a task placed on the container
|
||||
* instance backed by EC2 instance {@code ec2InstanceId}. A target group of target type
|
||||
* {@code instance} then gets the target ECS registers on AWS: the instance's id on the host port
|
||||
* the container publishes, which {@link Ec2InstancePorts} maps back to the container.
|
||||
*/
|
||||
public void registerTask(EcsTask task, EcsServiceModel svc, String ec2InstanceId, String region) {
|
||||
List<EcsRegisteredTargets.Target> planned = new ArrayList<>();
|
||||
forEachTarget(task, svc, (tgArn, td) ->
|
||||
planned.add(new EcsRegisteredTargets.Target(tgArn, td.getId(), td.getPort())));
|
||||
forEachTarget(task, svc, (tgArn, td, container, binding) -> {
|
||||
TargetDescription target = instanceTarget(task, region, tgArn, ec2InstanceId, td, container, binding)
|
||||
.orElse(td);
|
||||
planned.add(new EcsRegisteredTargets.Target(tgArn, target.getId(), target.getPort()));
|
||||
});
|
||||
if (planned.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
@@ -107,7 +134,7 @@ public class EcsLoadBalancerRegistrar {
|
||||
public Duration deregisterTask(EcsTask task, EcsServiceModel svc, String region) {
|
||||
List<Duration> drains = new ArrayList<>();
|
||||
if (task.getTaskArn() == null) {
|
||||
forEachTarget(task, svc, (tgArn, td) -> drains.add(deregister(region, tgArn, td)));
|
||||
forEachTarget(task, svc, (tgArn, td, container, binding) -> drains.add(deregister(region, tgArn, td)));
|
||||
} else {
|
||||
Optional<EcsRegisteredTargets> recorded = ledger.get(task.getTaskArn());
|
||||
if (recorded.isPresent()) {
|
||||
@@ -243,8 +270,107 @@ public class EcsLoadBalancerRegistrar {
|
||||
}
|
||||
}
|
||||
|
||||
private void forEachTarget(EcsTask task, EcsServiceModel svc,
|
||||
BiConsumer<String, TargetDescription> action) {
|
||||
/**
|
||||
* The {@code instance} target for a container reached at {@code containerTarget}, when the target
|
||||
* group is of that type and the task runs on a container instance. Its port is the host port the
|
||||
* container publishes on the instance, or, when another task on the instance already holds that
|
||||
* one, as when Docker published nothing and the containers share a container port, a port from
|
||||
* the ephemeral range the ECS agent assigns dynamic host ports from.
|
||||
*
|
||||
* <p>The container's other published host ports are taken on the instance too, where free, as a
|
||||
* bridge-mode task occupies every host port it maps: a target group whose health checks name one
|
||||
* of them then reaches the container. The task holds all of them until it stops, see
|
||||
* {@link #releaseInstancePorts}.
|
||||
*/
|
||||
private Optional<TargetDescription> instanceTarget(EcsTask task, String region, String tgArn,
|
||||
String ec2InstanceId, TargetDescription containerTarget,
|
||||
Container container, NetworkBinding binding) {
|
||||
if (ec2InstanceId == null || ec2InstanceId.isBlank() || task.getTaskArn() == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
TargetGroup group = elbV2Service.getTargetGroup(region, tgArn);
|
||||
if (group == null || !"instance".equals(group.getTargetType())) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String accountId = AwsArnUtils.parse(tgArn).accountId();
|
||||
Ec2InstancePorts.Endpoint endpoint = new Ec2InstancePorts.Endpoint(containerTarget.getId(),
|
||||
containerTarget.getPort());
|
||||
AtomicReference<Integer> trafficPort = new AtomicReference<>();
|
||||
heldInstancePorts.compute(task.getTaskArn(), (taskArn, held) -> {
|
||||
List<InstancePort> ports = held == null ? new ArrayList<>() : new ArrayList<>(held);
|
||||
Integer port = heldPort(ports, ec2InstanceId, endpoint)
|
||||
.orElseGet(() -> bindInstancePort(accountId, ec2InstanceId, binding.hostPort(), endpoint));
|
||||
if (port != null && heldPort(ports, ec2InstanceId, endpoint).isEmpty()) {
|
||||
ports.add(new InstancePort(accountId, ec2InstanceId, port, endpoint));
|
||||
}
|
||||
for (NetworkBinding other : container.getNetworkBindings()) {
|
||||
Ec2InstancePorts.Endpoint otherEndpoint = new Ec2InstancePorts.Endpoint(containerTarget.getId(),
|
||||
EcsTaskAddress.isLoopback(containerTarget.getId()) ? other.hostPort() : other.containerPort());
|
||||
if (other.hostPort() > 0 && heldPort(ports, ec2InstanceId, otherEndpoint).isEmpty()
|
||||
&& instancePorts.bind(accountId, ec2InstanceId, other.hostPort(), otherEndpoint)) {
|
||||
ports.add(new InstancePort(accountId, ec2InstanceId, other.hostPort(), otherEndpoint));
|
||||
}
|
||||
}
|
||||
trafficPort.set(port);
|
||||
return List.copyOf(ports);
|
||||
});
|
||||
if (trafficPort.get() == null) {
|
||||
LOG.warnv("No free host port on {0} for ECS task {1}; registering its container address instead",
|
||||
ec2InstanceId, task.getTaskArn());
|
||||
return Optional.empty();
|
||||
}
|
||||
TargetDescription target = new TargetDescription();
|
||||
target.setId(ec2InstanceId);
|
||||
target.setPort(trafficPort.get());
|
||||
return Optional.of(target);
|
||||
}
|
||||
|
||||
private static Optional<Integer> heldPort(List<InstancePort> held, String instanceId,
|
||||
Ec2InstancePorts.Endpoint endpoint) {
|
||||
return held.stream()
|
||||
.filter(p -> p.instanceId().equals(instanceId) && p.endpoint().equals(endpoint))
|
||||
.map(InstancePort::port)
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
private Integer bindInstancePort(String accountId, String instanceId, int preferred,
|
||||
Ec2InstancePorts.Endpoint endpoint) {
|
||||
if (preferred > 0 && instancePorts.bind(accountId, instanceId, preferred, endpoint)) {
|
||||
return preferred;
|
||||
}
|
||||
for (int port = EPHEMERAL_PORT_MIN; port <= EPHEMERAL_PORT_MAX; port++) {
|
||||
if (instancePorts.bind(accountId, instanceId, port, endpoint)) {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the container instance host ports {@link #registerTask} took for the task. Called once the
|
||||
* task is STOPPED rather than when it leaves its target groups: a draining task's containers still
|
||||
* run, so on AWS they still occupy those ports and a replacement on the same instance gets others.
|
||||
*/
|
||||
public void releaseInstancePorts(String taskArn) {
|
||||
if (taskArn == null) {
|
||||
return;
|
||||
}
|
||||
List<InstancePort> held = heldInstancePorts.remove(taskArn);
|
||||
if (held == null) {
|
||||
return;
|
||||
}
|
||||
for (InstancePort port : held) {
|
||||
instancePorts.release(port.accountId(), port.instanceId(), port.port(), port.endpoint());
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface TargetAction {
|
||||
void accept(String targetGroupArn, TargetDescription containerTarget, Container container,
|
||||
NetworkBinding binding);
|
||||
}
|
||||
|
||||
private void forEachTarget(EcsTask task, EcsServiceModel svc, TargetAction action) {
|
||||
if (svc == null || svc.getLoadBalancers() == null || svc.getLoadBalancers().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
@@ -274,7 +400,7 @@ public class EcsLoadBalancerRegistrar {
|
||||
TargetDescription td = new TargetDescription();
|
||||
td.setId(containerManager.resolveContainerHost(container));
|
||||
td.setPort(EcsTaskAddress.isLoopback(td.getId()) ? binding.hostPort() : binding.containerPort());
|
||||
action.accept(lb.getTargetGroupArn(), td);
|
||||
action.accept(lb.getTargetGroupArn(), td, container, binding);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package io.floci.aws.services.ecs;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
@@ -128,6 +130,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
StoredResourceArns {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EcsService.class);
|
||||
private static final ObjectMapper IDENTITY_DOCUMENT_JSON = new ObjectMapper();
|
||||
private static final String DEFAULT_CLUSTER = "default";
|
||||
|
||||
private final RegionResolver regionResolver;
|
||||
@@ -1972,6 +1975,46 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
return task;
|
||||
}
|
||||
|
||||
/**
|
||||
* The container instance an EC2 replica task runs on: the ACTIVE instance of the cluster running
|
||||
* the fewest tasks, among those registered for the placement's capacity provider when any are,
|
||||
* otherwise among those registered for none. Null for a Fargate placement, and when the cluster
|
||||
* has no instance to offer, which leaves the task running without one as before container
|
||||
* instances were considered.
|
||||
*/
|
||||
private String containerInstanceFor(EcsCluster cluster, Placement placement) {
|
||||
if (placement.launchType() != LaunchType.EC2) {
|
||||
return null;
|
||||
}
|
||||
String prefix = containerInstanceKey(cluster.getClusterArn(), "");
|
||||
List<ContainerInstance> active = containerInstances.entrySet().stream()
|
||||
.filter(e -> e.getKey().startsWith(prefix))
|
||||
.map(Map.Entry::getValue)
|
||||
.filter(ci -> "ACTIVE".equals(ci.getStatus()))
|
||||
.toList();
|
||||
String provider = placement.capacityProviderName();
|
||||
List<ContainerInstance> candidates = active;
|
||||
if (provider != null) {
|
||||
List<ContainerInstance> ofProvider = active.stream()
|
||||
.filter(ci -> provider.equals(ci.getCapacityProviderName()))
|
||||
.toList();
|
||||
candidates = !ofProvider.isEmpty() ? ofProvider : active.stream()
|
||||
.filter(ci -> ci.getCapacityProviderName() == null || ci.getCapacityProviderName().isBlank())
|
||||
.toList();
|
||||
}
|
||||
if (candidates.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
Map<String, Long> load = tasks.values().stream()
|
||||
.filter(t -> t.getContainerInstanceArn() != null)
|
||||
.filter(t -> !TaskStatus.STOPPED.name().equals(t.getLastStatus()))
|
||||
.collect(Collectors.groupingBy(EcsTask::getContainerInstanceArn, Collectors.counting()));
|
||||
return candidates.stream()
|
||||
.min(Comparator.comparingLong(ci -> load.getOrDefault(ci.getContainerInstanceArn(), 0L)))
|
||||
.map(ContainerInstance::getContainerInstanceArn)
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/** Where a task runs: a launch type, or the capacity provider that chose one for it. */
|
||||
private record Placement(LaunchType launchType, String capacityProviderName) {}
|
||||
|
||||
@@ -2428,6 +2471,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
task.setExecutionStoppedAt(Instant.now());
|
||||
task.bumpVersion();
|
||||
containerManager.releaseTaskNetwork(task, region);
|
||||
lbRegistrar.releaseInstancePorts(task.getTaskArn());
|
||||
if (task.getContainers() != null) {
|
||||
task.getContainers().forEach(c -> {
|
||||
c.setLastStatus("STOPPED");
|
||||
@@ -2457,7 +2501,9 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
private void registerTaskWithLoadBalancers(EcsTask task, EcsCluster cluster, String region) {
|
||||
EcsServiceModel svc = owningService(task, cluster);
|
||||
if (svc != null && !svc.getLoadBalancers().isEmpty()) {
|
||||
lbRegistrar.registerTask(task, svc, region);
|
||||
ContainerInstance instance = task.getContainerInstanceArn() == null ? null
|
||||
: resolveContainerInstance(cluster.getClusterArn(), task.getContainerInstanceArn());
|
||||
lbRegistrar.registerTask(task, svc, instance != null ? instance.getEc2InstanceId() : null, region);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4049,8 +4095,9 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
*/
|
||||
public ContainerInstance registerContainerInstance(RegisterContainerInstanceRequest request,
|
||||
String region) {
|
||||
String instanceId = identityDocumentInstanceId(request.getInstanceIdentityDocument())
|
||||
.orElseGet(() -> "i-floci-" + UUID.randomUUID().toString().substring(0, 8));
|
||||
EcsCluster cluster = resolveClusterOrDefault(request.getCluster(), region);
|
||||
String instanceId = "i-floci-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String instanceArn = request.getContainerInstanceArn() != null
|
||||
? request.getContainerInstanceArn()
|
||||
: regionResolver.buildArn("ecs", region,
|
||||
@@ -4081,6 +4128,30 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* The {@code instanceId} of the EC2 instance identity document the ECS agent registers with, which
|
||||
* is the EC2 instance AWS records the container instance as. Empty when the caller sent no
|
||||
* document. A document that is not JSON, or names no instance, is rejected rather than replaced
|
||||
* by a generated id, so a registration never silently stands for some other instance.
|
||||
*/
|
||||
static Optional<String> identityDocumentInstanceId(String identityDocument) {
|
||||
if (identityDocument == null || identityDocument.isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String instanceId;
|
||||
try {
|
||||
instanceId = IDENTITY_DOCUMENT_JSON.readTree(identityDocument).path("instanceId").asText("");
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"instanceIdentityDocument is not a valid instance identity document.", 400);
|
||||
}
|
||||
if (instanceId.isBlank()) {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"instanceIdentityDocument does not name an instanceId.", 400);
|
||||
}
|
||||
return Optional.of(instanceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deregisters an instance, leaving it in the cluster as {@code INACTIVE} rather than dropping
|
||||
* it: AWS keeps answering DescribeContainerInstances for a deregistered instance, and only
|
||||
@@ -5682,6 +5753,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
LOG.infov("ECS task {0} reconciled to STOPPED (all containers exited)", taskArn);
|
||||
String region = taskRegion(task);
|
||||
containerManager.releaseTaskNetwork(task, region);
|
||||
lbRegistrar.releaseInstancePorts(taskArn);
|
||||
if (eventPublisher != null) {
|
||||
eventPublisher.emitTaskLadder(task, TaskStatus.RUNNING, TaskStatus.STOPPED, region);
|
||||
}
|
||||
@@ -6198,7 +6270,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
.toList();
|
||||
for (Placement placement : serviceTaskPlacements(svc, currentTasks, toStart)) {
|
||||
try {
|
||||
EcsTask launched = launchServiceTask(cluster, svc, placement, null, region);
|
||||
EcsTask launched = launchServiceTask(cluster, svc, placement,
|
||||
containerInstanceFor(cluster, placement), region);
|
||||
recordLaunchFailure(svc, null, null);
|
||||
LOG.infov("Service reconciler started task {0} for service {1}",
|
||||
launched.getTaskArn(), svc.getServiceName());
|
||||
|
||||
@@ -12,6 +12,7 @@ import io.floci.aws.core.common.RequestHost;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.common.WebSocketUpgrades;
|
||||
import io.floci.aws.core.common.tls.ReloadingKeyManager;
|
||||
import io.floci.aws.services.ec2.Ec2InstancePorts;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.elbv2.model.Action;
|
||||
import io.floci.aws.services.elbv2.model.Listener;
|
||||
@@ -136,6 +137,9 @@ public class ElbV2DataPlane {
|
||||
@Inject
|
||||
Ec2Service ec2Service;
|
||||
|
||||
@Inject
|
||||
Ec2InstancePorts instancePorts;
|
||||
|
||||
@Inject
|
||||
CertificateReferenceResolver certificateResolver;
|
||||
|
||||
@@ -718,8 +722,10 @@ public class ElbV2DataPlane {
|
||||
return;
|
||||
}
|
||||
TargetDescription target = pickRoundRobin(tgArn, candidates);
|
||||
int port = ElbV2HealthChecker.effectivePort(target, tg);
|
||||
String host = ElbV2TargetResolver.resolveHost(ec2Service, tg, target);
|
||||
Ec2InstancePorts.Endpoint endpoint = ElbV2TargetResolver.resolve(ec2Service, instancePorts, tg,
|
||||
target.getId(), ElbV2HealthChecker.effectivePort(target, tg));
|
||||
int port = endpoint.port();
|
||||
String host = endpoint.host();
|
||||
AtomicBoolean disconnected = new AtomicBoolean();
|
||||
socket.closeHandler(ignored -> disconnected.set(true));
|
||||
vertx.executeBlocking(() -> ElbV2TargetResolver.resolveCheckedAddress(host))
|
||||
@@ -1161,8 +1167,10 @@ public class ElbV2DataPlane {
|
||||
target = pickRoundRobin(tgArn, candidates);
|
||||
}
|
||||
List<String> cookies = duration > 0 ? stickyCookie.headers(scope, tg, target) : List.of();
|
||||
int targetPort = ElbV2HealthChecker.effectivePort(target, tg);
|
||||
String host = ElbV2TargetResolver.resolveHost(ec2Service, tg, target);
|
||||
Ec2InstancePorts.Endpoint endpoint = ElbV2TargetResolver.resolve(ec2Service, instancePorts, tg,
|
||||
target.getId(), ElbV2HealthChecker.effectivePort(target, tg));
|
||||
int targetPort = endpoint.port();
|
||||
String host = endpoint.host();
|
||||
boolean secure = "HTTPS".equals(tg.getProtocol());
|
||||
if (isWebSocketUpgrade(req)) {
|
||||
proxyUpgrade(req, host, targetPort, secure, hostHeader, forwarded,
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.floci.aws.services.elbv2;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.Resettable;
|
||||
import io.floci.aws.core.common.concurrent.SocketDeadline;
|
||||
import io.floci.aws.services.ec2.Ec2InstancePorts;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.elbv2.model.TargetDescription;
|
||||
import io.floci.aws.services.elbv2.model.TargetGroup;
|
||||
@@ -40,6 +41,7 @@ public class ElbV2HealthChecker implements Resettable {
|
||||
private final WorkerExecutor probeWorkers;
|
||||
private final EmulatorConfig config;
|
||||
private final Ec2Service ec2Service;
|
||||
private final Ec2InstancePorts instancePorts;
|
||||
private final SSLSocketFactory backendTls = backendTls();
|
||||
|
||||
// tgArn → (targetKey → TargetState)
|
||||
@@ -48,11 +50,17 @@ public class ElbV2HealthChecker implements Resettable {
|
||||
private final Map<String, Long> timers = new ConcurrentHashMap<>();
|
||||
private final Semaphore probeSlots = new Semaphore(MAX_CONCURRENT_PROBES);
|
||||
|
||||
ElbV2HealthChecker(Vertx vertx, EmulatorConfig config, Ec2Service ec2Service) {
|
||||
this(vertx, config, ec2Service, new Ec2InstancePorts());
|
||||
}
|
||||
|
||||
@Inject
|
||||
public ElbV2HealthChecker(Vertx vertx, EmulatorConfig config, Ec2Service ec2Service) {
|
||||
public ElbV2HealthChecker(Vertx vertx, EmulatorConfig config, Ec2Service ec2Service,
|
||||
Ec2InstancePorts instancePorts) {
|
||||
this.vertx = vertx;
|
||||
this.config = config;
|
||||
this.ec2Service = ec2Service;
|
||||
this.instancePorts = instancePorts;
|
||||
this.probeWorkers = vertx.createSharedWorkerExecutor("floci-elbv2-health-probes", MAX_CONCURRENT_PROBES);
|
||||
}
|
||||
|
||||
@@ -200,8 +208,9 @@ public class ElbV2HealthChecker implements Resettable {
|
||||
state.workerRunning = true;
|
||||
}
|
||||
return SocketDeadline.call(timeout, () -> {
|
||||
String host = ElbV2TargetResolver.resolveHost(ec2Service, tg, targetId);
|
||||
return probeOnce(host, probePort, path, timeout, protocol);
|
||||
Ec2InstancePorts.Endpoint endpoint = ElbV2TargetResolver.resolve(ec2Service,
|
||||
instancePorts, tg, targetId, probePort);
|
||||
return probeOnce(endpoint.host(), endpoint.port(), path, timeout, protocol);
|
||||
}, () -> {
|
||||
synchronized (state) {
|
||||
state.workerRunning = false;
|
||||
|
||||
@@ -2,38 +2,51 @@ package io.floci.aws.services.elbv2;
|
||||
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.SsrfProtection;
|
||||
import io.floci.aws.services.ec2.Ec2InstancePorts;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.elbv2.model.TargetDescription;
|
||||
import io.floci.aws.services.elbv2.model.TargetGroup;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.util.Optional;
|
||||
|
||||
final class ElbV2TargetResolver {
|
||||
|
||||
private ElbV2TargetResolver() {}
|
||||
|
||||
static String resolveHost(Ec2Service ec2Service, TargetGroup targetGroup, TargetDescription target) {
|
||||
return resolveHost(ec2Service, targetGroup, target != null ? target.getId() : null);
|
||||
/**
|
||||
* Where a target is reached: an {@code ip} target at its own address, an {@code instance} target at
|
||||
* whatever serves that instance port. A port an ECS task on the instance publishes is reached at the
|
||||
* task's container; any other port at the instance's own container, as AWS forwards to the instance's
|
||||
* primary address. An instance Floci cannot place keeps its id, which the caller then fails to reach.
|
||||
*/
|
||||
static Ec2InstancePorts.Endpoint resolve(Ec2Service ec2Service, Ec2InstancePorts instancePorts,
|
||||
TargetGroup targetGroup, String targetId, int port) {
|
||||
if (targetId == null || targetId.isBlank() || targetGroup == null
|
||||
|| !"instance".equals(targetGroup.getTargetType())) {
|
||||
return new Ec2InstancePorts.Endpoint(targetId, port);
|
||||
}
|
||||
String accountId = extractAccountId(targetGroup.getTargetGroupArn());
|
||||
if (instancePorts != null) {
|
||||
Optional<Ec2InstancePorts.Endpoint> published = instancePorts.find(accountId, targetId, port);
|
||||
if (published.isPresent()) {
|
||||
return published.get();
|
||||
}
|
||||
}
|
||||
return new Ec2InstancePorts.Endpoint(resolveHost(ec2Service, targetId, accountId), port);
|
||||
}
|
||||
|
||||
static String resolveHost(Ec2Service ec2Service, TargetGroup targetGroup, String targetId) {
|
||||
if (targetId == null || targetId.isBlank()) {
|
||||
private static String resolveHost(Ec2Service ec2Service, String targetId, String accountId) {
|
||||
if (ec2Service == null) {
|
||||
return targetId;
|
||||
}
|
||||
if (targetGroup == null || !"instance".equals(targetGroup.getTargetType()) || ec2Service == null) {
|
||||
return targetId;
|
||||
}
|
||||
|
||||
String accountId = extractAccountId(targetGroup.getTargetGroupArn());
|
||||
Instance instance = accountId != null
|
||||
? ec2Service.findInstanceById(accountId, targetId)
|
||||
: ec2Service.findInstanceById(targetId);
|
||||
if (instance == null) {
|
||||
return targetId;
|
||||
}
|
||||
|
||||
String containerBridgeIp = instance.getContainerBridgeIp();
|
||||
if (containerBridgeIp != null && !containerBridgeIp.isBlank()) {
|
||||
return containerBridgeIp;
|
||||
|
||||
Reference in new issue
Block a user