mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(ec2): publish security-group TCP ingress ports on the host (#1680)
* feat(ec2): publish security-group TCP ingress ports on the host For each TCP port opened to a CIDR source by an instance's security groups, start an alpine/socat sidecar that binds an allocated host port (default 30000-30999) and forwards to the instance container's IP, so the app is reachable from localhost. Forwards reconcile at launch, on authorize/revoke-security-group-ingress, and on ModifyInstanceAttribute group reassignment (previously ignored). Mappings persist and are restored across restarts. SSH is never re-forwarded; wide rules and per-instance totals are capped; disable with publish-security-group-ports=false. * fix(ec2): drop stale port mapping when sidecar recreation fails On restore, a failed socat recreation released the host port but left the appPort->hostPort entry in publishedPorts, so later reconciles saw the port as already published and never re-published it, and a later unpublish could double-release the host port. Remove the entry and persist on failure. Also null-guard portForwardManager.restore() for consistency with the setPersister guard. Adds a regression test. * fix(ec2): skip port-forward reconcile on non-running instances A reconcile queued by authorize-security-group-ingress could run after a concurrent stop/terminate had already cleared publishedPorts and removed the container; it then republished via the stale bridge IP, leaking an orphaned socat sidecar and a host port that nothing would release. Stop/terminate flip the instance state before their async unpublishAll, so guarding reconcileNow on the running state under the instance lock closes every window. Adds regression tests.
This commit is contained in:
1 parent
3fe7a60a58
commit
a27971c7d5
14 files changed
+883
-8
No files matched your search
@@ -1227,6 +1227,34 @@ public interface EmulatorConfig {
|
||||
@WithDefault("2299")
|
||||
int sshPortRangeEnd();
|
||||
|
||||
/**
|
||||
* When true, TCP ports opened by an instance's security-group ingress rules are
|
||||
* published on the host via a socat sidecar container, both at launch and on later
|
||||
* authorize-security-group-ingress. Set false to keep security groups as metadata only.
|
||||
*/
|
||||
@WithDefault("true")
|
||||
boolean publishSecurityGroupPorts();
|
||||
|
||||
/** Lowest host port in the range allocated for published security-group app ports. */
|
||||
@WithDefault("30000")
|
||||
int appPortRangeStart();
|
||||
|
||||
/** Highest host port in the range allocated for published security-group app ports. */
|
||||
@WithDefault("30999")
|
||||
int appPortRangeEnd();
|
||||
|
||||
/**
|
||||
* Upper bound on app ports published per instance. Also bounds any single ingress
|
||||
* rule's port span: wider ranges (e.g. an allow-all 0-65535 rule) are skipped so a
|
||||
* single rule cannot spawn thousands of socat sidecars or exhaust the host-port range.
|
||||
*/
|
||||
@WithDefault("20")
|
||||
int maxPublishedPortsPerInstance();
|
||||
|
||||
/** Image used for the socat sidecar that forwards published security-group ports. */
|
||||
@WithDefault("alpine/socat")
|
||||
String socatImage();
|
||||
|
||||
/** When true, instances go straight to RUNNING without launching Docker containers. */
|
||||
@WithDefault("false")
|
||||
boolean mock();
|
||||
|
||||
@@ -43,6 +43,15 @@ public class PortAllocator {
|
||||
throw new RuntimeException("No free port available in range " + basePort + "-" + maxPort);
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks a port as reserved without probing whether it is free. Used on restart to
|
||||
* re-reserve host ports already held by surviving containers (e.g. persisted EC2
|
||||
* port forwards) so the allocator does not hand them out again.
|
||||
*/
|
||||
public synchronized void markReserved(int port) {
|
||||
reserved.add(port);
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases a previously allocated port back to the pool.
|
||||
* Should be called when the Docker container that was using the port is removed.
|
||||
|
||||
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
|
||||
import io.github.hectorvent.floci.core.common.docker.PortAllocator;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
|
||||
import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.exception.NotFoundException;
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
@@ -32,6 +33,7 @@ import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
@@ -62,6 +64,7 @@ public class Ec2ContainerManager {
|
||||
private final PortAllocator portAllocator;
|
||||
private final EmulatorConfig config;
|
||||
private final Ec2MetadataServer metadataServer;
|
||||
private final Ec2PortForwardManager portForwardManager;
|
||||
|
||||
private final ExecutorService executor = Executors.newCachedThreadPool(r -> {
|
||||
Thread t = new Thread(r, "ec2-container-launcher");
|
||||
@@ -78,7 +81,8 @@ public class Ec2ContainerManager {
|
||||
DockerClient dockerClient,
|
||||
PortAllocator portAllocator,
|
||||
EmulatorConfig config,
|
||||
Ec2MetadataServer metadataServer) {
|
||||
Ec2MetadataServer metadataServer,
|
||||
Ec2PortForwardManager portForwardManager) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.logStreamer = logStreamer;
|
||||
@@ -88,6 +92,7 @@ public class Ec2ContainerManager {
|
||||
this.portAllocator = portAllocator;
|
||||
this.config = config;
|
||||
this.metadataServer = metadataServer;
|
||||
this.portForwardManager = portForwardManager;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -101,10 +106,18 @@ public class Ec2ContainerManager {
|
||||
* @param region AWS region (for CloudWatch log group naming)
|
||||
*/
|
||||
public void launch(Instance instance, String dockerImage, String publicKey, String region) {
|
||||
launch(instance, ResolvedAmiImage.minimal(dockerImage), publicKey, region);
|
||||
launch(instance, ResolvedAmiImage.minimal(dockerImage), publicKey, region, Set.of());
|
||||
}
|
||||
|
||||
public void launch(Instance instance, ResolvedAmiImage image, String publicKey, String region) {
|
||||
launch(instance, image, publicKey, region, Set.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param appPorts TCP ports opened by the instance's security groups to publish on the host
|
||||
* via socat sidecars once the container is running (empty for none)
|
||||
*/
|
||||
public void launch(Instance instance, ResolvedAmiImage image, String publicKey, String region, Set<Integer> appPorts) {
|
||||
instance.setState(InstanceState.pending());
|
||||
|
||||
executor.submit(() -> {
|
||||
@@ -198,6 +211,11 @@ public class Ec2ContainerManager {
|
||||
LOG.infov("EC2 instance {0} running in container {1} (SSH host port {2})",
|
||||
instanceId, containerId, String.valueOf(sshHostPort));
|
||||
|
||||
// Publish security-group TCP ingress ports on the host via socat sidecars.
|
||||
if (appPorts != null && !appPorts.isEmpty()) {
|
||||
portForwardManager.reconcile(instance, appPorts);
|
||||
}
|
||||
|
||||
// Inject SSH public key
|
||||
if (publicKey != null && !publicKey.isBlank()) {
|
||||
injectSshKey(containerId, publicKey);
|
||||
@@ -232,6 +250,9 @@ public class Ec2ContainerManager {
|
||||
}
|
||||
instance.setState(InstanceState.stopping());
|
||||
executor.submit(() -> {
|
||||
// Sidecars forward to the container's current IP, which Docker reassigns on the
|
||||
// next start; tear them down so no forward is left pointing at a stale address.
|
||||
portForwardManager.unpublishAll(instance);
|
||||
try {
|
||||
dockerClient.stopContainerCmd(containerId).withTimeout(30).exec();
|
||||
} catch (NotFoundException e) {
|
||||
@@ -340,6 +361,7 @@ public class Ec2ContainerManager {
|
||||
int sshHostPort = instance.getSshHostPort();
|
||||
instance.setState(InstanceState.shuttingDown());
|
||||
executor.submit(() -> {
|
||||
portForwardManager.unpublishAll(instance);
|
||||
if (containerId != null) {
|
||||
try {
|
||||
dockerClient.removeContainerCmd(containerId).withForce(true).exec();
|
||||
|
||||
@@ -612,6 +612,18 @@ public class Ec2QueryHandler {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Security group reassignment: --groups maps to GroupId.1, GroupId.2, ...
|
||||
List<String> groupIds = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String groupId = p.getFirst("GroupId." + i);
|
||||
if (groupId == null) {
|
||||
break;
|
||||
}
|
||||
groupIds.add(groupId);
|
||||
}
|
||||
if (!groupIds.isEmpty()) {
|
||||
service.modifyInstanceGroups(region, instanceId, groupIds);
|
||||
}
|
||||
return booleanResponse("ModifyInstanceAttribute");
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Address;
|
||||
import io.github.hectorvent.floci.services.ec2.model.GroupIdentifier;
|
||||
import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Image;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.ec2.model.InstanceNetworkInterface;
|
||||
@@ -81,6 +82,7 @@ public class Ec2Service {
|
||||
private final String accountId;
|
||||
private final EmulatorConfig config;
|
||||
private final Ec2ContainerManager containerManager;
|
||||
private final Ec2PortForwardManager portForwardManager;
|
||||
private final AmiImageResolver amiImageResolver;
|
||||
private final Ec2ImageCatalog imageCatalog;
|
||||
private final Ec2InstanceTypeCatalog instanceTypeCatalog;
|
||||
@@ -111,9 +113,10 @@ public class Ec2Service {
|
||||
|
||||
@Inject
|
||||
public Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,
|
||||
Ec2PortForwardManager portForwardManager,
|
||||
AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog,
|
||||
Ec2InstanceTypeCatalog instanceTypeCatalog, StorageFactory storageFactory) {
|
||||
this(config, containerManager, amiImageResolver, imageCatalog, instanceTypeCatalog,
|
||||
this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog, instanceTypeCatalog,
|
||||
storageFactory.create("ec2", "ec2-vpcs.json", new TypeReference<Map<String, Vpc>>() {}),
|
||||
storageFactory.create("ec2", "ec2-subnets.json", new TypeReference<Map<String, Subnet>>() {}),
|
||||
storageFactory.create("ec2", "ec2-security-groups.json", new TypeReference<Map<String, SecurityGroup>>() {}),
|
||||
@@ -134,6 +137,7 @@ public class Ec2Service {
|
||||
|
||||
// Package-private for hermetic tests (pass in-memory or temp-dir-backed StorageBackends directly).
|
||||
Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,
|
||||
Ec2PortForwardManager portForwardManager,
|
||||
AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog,
|
||||
Ec2InstanceTypeCatalog instanceTypeCatalog,
|
||||
StorageBackend<String, Vpc> vpcs,
|
||||
@@ -155,6 +159,7 @@ public class Ec2Service {
|
||||
this.accountId = config.defaultAccountId();
|
||||
this.config = config;
|
||||
this.containerManager = containerManager;
|
||||
this.portForwardManager = portForwardManager;
|
||||
this.amiImageResolver = amiImageResolver;
|
||||
this.imageCatalog = imageCatalog;
|
||||
this.instanceTypeCatalog = instanceTypeCatalog;
|
||||
@@ -178,6 +183,13 @@ public class Ec2Service {
|
||||
|
||||
@PostConstruct
|
||||
void restoreMetadataRegistrations() {
|
||||
if (portForwardManager != null) {
|
||||
portForwardManager.setPersister(inst -> {
|
||||
if (inst != null && inst.getRegion() != null && inst.getInstanceId() != null) {
|
||||
instances.put(key(inst.getRegion(), inst.getInstanceId()), inst);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (config.services().ec2().mock()) {
|
||||
return;
|
||||
}
|
||||
@@ -191,6 +203,10 @@ public class Ec2Service {
|
||||
if (containerManager.restoreMetadataRegistration(instance)) {
|
||||
instances.put(key, instance);
|
||||
restored++;
|
||||
// Container is running: re-reserve host ports and recreate any missing socat sidecars.
|
||||
if (portForwardManager != null) {
|
||||
portForwardManager.restore(instance);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (restored > 0) {
|
||||
@@ -631,13 +647,59 @@ public class Ec2Service {
|
||||
publicKey = kp.getPublicKey();
|
||||
}
|
||||
}
|
||||
containerManager.launch(inst, dockerImage, publicKey, region);
|
||||
containerManager.launch(inst, dockerImage, publicKey, region, desiredPublishedPorts(region, inst));
|
||||
}
|
||||
}
|
||||
|
||||
return reservation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the TCP ingress ports Floci should publish on the host for an instance, aggregated
|
||||
* across its attached security groups. Empty when publishing is disabled or nothing is opened.
|
||||
*/
|
||||
private Set<Integer> desiredPublishedPorts(String region, Instance inst) {
|
||||
if (!config.services().ec2().publishSecurityGroupPorts()) {
|
||||
return Set.of();
|
||||
}
|
||||
List<SecurityGroup> sgs = new ArrayList<>();
|
||||
if (inst.getSecurityGroups() != null) {
|
||||
for (GroupIdentifier gi : inst.getSecurityGroups()) {
|
||||
securityGroups.get(key(region, gi.getGroupId())).ifPresent(sgs::add);
|
||||
}
|
||||
}
|
||||
return Ec2PortForwardManager.extractPublishablePorts(
|
||||
sgs, config.services().ec2().maxPublishedPortsPerInstance());
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-publishes host forwards for every running instance attached to the given security group,
|
||||
* so ports opened or closed via authorize/revoke ingress take effect on already-running
|
||||
* instances. No-op in mock mode or when publishing is disabled.
|
||||
*/
|
||||
private void reconcilePublishedPortsForGroup(String region, String groupId) {
|
||||
if (!config.services().ec2().publishSecurityGroupPorts() || config.services().ec2().mock()) {
|
||||
return;
|
||||
}
|
||||
String prefix = region + "::";
|
||||
for (Instance inst : instances.scan(k -> k.startsWith(prefix))) {
|
||||
if (inst.getSecurityGroups() == null || inst.getDockerContainerId() == null) {
|
||||
continue;
|
||||
}
|
||||
boolean attached = inst.getSecurityGroups().stream()
|
||||
.anyMatch(g -> groupId.equals(g.getGroupId()));
|
||||
if (!attached) {
|
||||
continue;
|
||||
}
|
||||
String state = inst.getState() != null ? inst.getState().getName() : null;
|
||||
if (!"running".equals(state)) {
|
||||
continue;
|
||||
}
|
||||
portForwardManager.reconcile(inst, desiredPublishedPorts(region, inst));
|
||||
instances.put(key(region, inst.getInstanceId()), inst);
|
||||
}
|
||||
}
|
||||
|
||||
public Subnet requireSubnet(String region, String subnetId) {
|
||||
ensureDefaultResources(region);
|
||||
Subnet subnet = subnets.get(key(region, subnetId)).orElse(null);
|
||||
@@ -848,6 +910,34 @@ public class Ec2Service {
|
||||
instances.put(key(region, instanceId), inst);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the security groups attached to an instance (ModifyInstanceAttribute with
|
||||
* {@code GroupId.N}). Validates each group, updates the instance and its network interfaces,
|
||||
* and re-publishes host forwards so ports opened by the newly attached groups take effect.
|
||||
*/
|
||||
public void modifyInstanceGroups(String region, String instanceId, List<String> groupIds) {
|
||||
ensureDefaultResources(region);
|
||||
Instance inst = getRequiredInstance(region, instanceId);
|
||||
|
||||
List<GroupIdentifier> identifiers = new ArrayList<>();
|
||||
for (String groupId : groupIds) {
|
||||
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
|
||||
identifiers.add(new GroupIdentifier(sg.getGroupId(), sg.getGroupName()));
|
||||
}
|
||||
|
||||
inst.setSecurityGroups(new ArrayList<>(identifiers));
|
||||
if (inst.getNetworkInterfaces() != null) {
|
||||
inst.getNetworkInterfaces().forEach(eni -> eni.setGroups(new ArrayList<>(identifiers)));
|
||||
}
|
||||
instances.put(key(region, instanceId), inst);
|
||||
|
||||
if (config.services().ec2().publishSecurityGroupPorts() && !config.services().ec2().mock()
|
||||
&& inst.getDockerContainerId() != null
|
||||
&& inst.getState() != null && "running".equals(inst.getState().getName())) {
|
||||
portForwardManager.reconcile(inst, desiredPublishedPorts(region, inst));
|
||||
}
|
||||
}
|
||||
|
||||
private Instance getRequiredInstance(String region, String instanceId) {
|
||||
Instance inst = instances.get(key(region, instanceId)).orElse(null);
|
||||
if (inst == null)
|
||||
@@ -1151,6 +1241,7 @@ public class Ec2Service {
|
||||
rules.addAll(createRules(region, groupId, perm, false));
|
||||
}
|
||||
securityGroups.put(key(region, groupId), sg);
|
||||
reconcilePublishedPortsForGroup(region, groupId);
|
||||
return rules;
|
||||
}
|
||||
|
||||
@@ -1206,6 +1297,7 @@ public class Ec2Service {
|
||||
|
||||
sg.getIpPermissions().removeIf(p -> matchesAnyPermission(p, permissions));
|
||||
securityGroups.put(key(region, groupId), sg);
|
||||
reconcilePublishedPortsForGroup(region, groupId);
|
||||
}
|
||||
|
||||
public void revokeSecurityGroupEgress(String region, String groupId, List<IpPermission> permissions) {
|
||||
|
||||
@@ -5,7 +5,9 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@@ -59,6 +61,10 @@ public class Instance {
|
||||
private int sshHostPort;
|
||||
private long terminatedAt;
|
||||
|
||||
// Security-group ingress ports published on the host via socat sidecars:
|
||||
// container app port -> allocated host port. Not part of the AWS wire format.
|
||||
private Map<Integer, Integer> publishedPorts = new LinkedHashMap<>();
|
||||
|
||||
public Instance() {}
|
||||
|
||||
public String getInstanceId() { return instanceId; }
|
||||
@@ -172,6 +178,14 @@ public class Instance {
|
||||
public String getContainerBridgeIp() { return containerBridgeIp; }
|
||||
public void setContainerBridgeIp(String containerBridgeIp) { this.containerBridgeIp = containerBridgeIp; }
|
||||
|
||||
public Map<Integer, Integer> getPublishedPorts() {
|
||||
if (publishedPorts == null) {
|
||||
publishedPorts = new LinkedHashMap<>();
|
||||
}
|
||||
return publishedPorts;
|
||||
}
|
||||
public void setPublishedPorts(Map<Integer, Integer> publishedPorts) { this.publishedPorts = publishedPorts; }
|
||||
|
||||
public String getRootVolumeId() { return rootVolumeId; }
|
||||
public void setRootVolumeId(String rootVolumeId) { this.rootVolumeId = rootVolumeId; }
|
||||
|
||||
|
||||
+367
@@ -0,0 +1,367 @@
|
||||
package io.github.hectorvent.floci.services.ec2.portforward;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
|
||||
import io.github.hectorvent.floci.core.common.docker.PortAllocator;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.ec2.model.IpPermission;
|
||||
import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.InspectContainerResponse;
|
||||
import com.github.dockerjava.api.model.ContainerNetwork;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Publishes EC2 instance application ports on the host, driven by the TCP ingress
|
||||
* rules of the instance's security groups.
|
||||
*
|
||||
* <p>For each opened TCP port a small {@code alpine/socat} sidecar container is started
|
||||
* as a host sibling (created through the mounted Docker socket, exactly like the instance
|
||||
* container and its SSH binding). The sidecar publishes an allocated host port and forwards
|
||||
* it to the instance container's IP, so {@code curl localhost:<hostPort>} reaches the app.
|
||||
*
|
||||
* <p>Because each forward is a fresh container, ports opened <em>after</em> launch via
|
||||
* {@code authorize-security-group-ingress} are handled the same way as ports present at
|
||||
* launch. The instance container itself is never modified.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class Ec2PortForwardManager {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(Ec2PortForwardManager.class);
|
||||
|
||||
/** SSH is already published on its own host port by the container manager; never re-forward it. */
|
||||
static final int SSH_PORT = 22;
|
||||
|
||||
private final DockerClient dockerClient;
|
||||
private final ContainerBuilder containerBuilder;
|
||||
private final ContainerLifecycleManager lifecycleManager;
|
||||
private final PortAllocator portAllocator;
|
||||
private final EmulatorConfig config;
|
||||
|
||||
private final ExecutorService executor = Executors.newCachedThreadPool(r -> {
|
||||
Thread t = new Thread(r, "ec2-port-forward");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
|
||||
// Persists an instance after its publishedPorts change, so the mapping survives a
|
||||
// hard restart (not just the periodic/shutdown flush). Set by the owning service.
|
||||
private volatile Consumer<Instance> persister;
|
||||
|
||||
@Inject
|
||||
public Ec2PortForwardManager(DockerClient dockerClient,
|
||||
ContainerBuilder containerBuilder,
|
||||
ContainerLifecycleManager lifecycleManager,
|
||||
PortAllocator portAllocator,
|
||||
EmulatorConfig config) {
|
||||
this.dockerClient = dockerClient;
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.portAllocator = portAllocator;
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconciles the instance's live forwards against the desired port set: publishes ports
|
||||
* that are newly opened and unpublishes ports that no longer have an ingress rule. Runs
|
||||
* asynchronously so it does not block the calling API thread.
|
||||
*/
|
||||
public void reconcile(Instance instance, Set<Integer> desiredPorts) {
|
||||
if (!enabled() || instance == null || instance.getDockerContainerId() == null) {
|
||||
return;
|
||||
}
|
||||
executor.submit(() -> reconcileNow(instance, desiredPorts));
|
||||
}
|
||||
|
||||
void reconcileNow(Instance instance, Set<Integer> desiredPorts) {
|
||||
synchronized (instance) {
|
||||
// A reconcile queued before a stop/terminate must not republish against the
|
||||
// removed container: stop/terminate flip the state before their async
|
||||
// unpublishAll, so a non-running state here means the forwards are (being)
|
||||
// torn down and new sidecars would leak.
|
||||
String state = instance.getState() != null ? instance.getState().getName() : null;
|
||||
if (!"running".equals(state)) {
|
||||
return;
|
||||
}
|
||||
for (int port : desiredPorts) {
|
||||
if (!instance.getPublishedPorts().containsKey(port)) {
|
||||
publish(instance, port);
|
||||
}
|
||||
}
|
||||
for (Integer port : new ArrayList<>(instance.getPublishedPorts().keySet())) {
|
||||
if (!desiredPorts.contains(port)) {
|
||||
unpublish(instance, port);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes every forward for the instance and releases its host ports. Called on
|
||||
* terminate and stop. Runs on the caller's thread (both callers are already async).
|
||||
*/
|
||||
public void unpublishAll(Instance instance) {
|
||||
if (instance == null) {
|
||||
return;
|
||||
}
|
||||
synchronized (instance) {
|
||||
for (Integer port : new ArrayList<>(instance.getPublishedPorts().keySet())) {
|
||||
unpublish(instance, port);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
boolean enabled() {
|
||||
return config.services().ec2().publishSecurityGroupPorts() && !config.services().ec2().mock();
|
||||
}
|
||||
|
||||
/** Sets the callback used to persist an instance after its forwards change. */
|
||||
public void setPersister(Consumer<Instance> persister) {
|
||||
this.persister = persister;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-establishes an instance's persisted forwards after a restart: re-reserves each host
|
||||
* port so the allocator will not reuse it, and recreates any socat sidecar that did not
|
||||
* survive. Sidecars are independent containers, so a surviving one keeps working untouched.
|
||||
*/
|
||||
public void restore(Instance instance) {
|
||||
if (!enabled() || instance == null || instance.getDockerContainerId() == null
|
||||
|| instance.getPublishedPorts().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (Map.Entry<Integer, Integer> entry : new LinkedHashMap<>(instance.getPublishedPorts()).entrySet()) {
|
||||
int appPort = entry.getKey();
|
||||
int hostPort = entry.getValue();
|
||||
portAllocator.markReserved(hostPort);
|
||||
String name = forwardContainerName(instance.getInstanceId(), appPort);
|
||||
if (lifecycleManager.findByName(name).isEmpty()) {
|
||||
LOG.infov("Recreating missing port-forward sidecar for EC2 instance {0} app port {1}",
|
||||
instance.getInstanceId(), appPort);
|
||||
if (!publishOn(instance, appPort, hostPort)) {
|
||||
portAllocator.release(hostPort);
|
||||
// Drop the stale mapping so a later reconcile can re-publish the port
|
||||
// instead of seeing it as already published.
|
||||
instance.getPublishedPorts().remove(appPort);
|
||||
persist(instance);
|
||||
}
|
||||
} else {
|
||||
LOG.infov("Restored port-forward for EC2 instance {0}: app port {1} -> host port {2}",
|
||||
instance.getInstanceId(), appPort, hostPort);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void publish(Instance instance, int appPort) {
|
||||
int hostPort = portAllocator.allocate(
|
||||
config.services().ec2().appPortRangeStart(),
|
||||
config.services().ec2().appPortRangeEnd());
|
||||
if (!publishOn(instance, appPort, hostPort)) {
|
||||
portAllocator.release(hostPort);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean publishOn(Instance instance, int appPort, int hostPort) {
|
||||
String instanceId = instance.getInstanceId();
|
||||
try {
|
||||
NetworkTarget target = resolveInstanceTarget(instance);
|
||||
if (target == null) {
|
||||
LOG.warnv("Could not resolve container IP for EC2 instance {0}; not publishing port {1}",
|
||||
instanceId, appPort);
|
||||
return false;
|
||||
}
|
||||
|
||||
String name = forwardContainerName(instanceId, appPort);
|
||||
lifecycleManager.removeIfExists(name);
|
||||
|
||||
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(config.services().ec2().socatImage())
|
||||
.withName(name)
|
||||
.withEntrypoint(List.of("socat"))
|
||||
.withCmd(List.of(
|
||||
"TCP-LISTEN:" + appPort + ",fork,reuseaddr",
|
||||
"TCP:" + target.ip() + ":" + appPort))
|
||||
.withPortBinding(appPort, hostPort)
|
||||
.withLogRotation();
|
||||
if (target.network() != null) {
|
||||
specBuilder.withNetworkMode(target.network());
|
||||
}
|
||||
ContainerSpec spec = specBuilder.build();
|
||||
|
||||
String containerId = lifecycleManager.create(spec);
|
||||
lifecycleManager.startCreated(containerId, spec);
|
||||
|
||||
instance.getPublishedPorts().put(appPort, hostPort);
|
||||
persist(instance);
|
||||
LOG.infov("Published EC2 instance {0} app port {1} on host port {2} (socat -> {3}:{1})",
|
||||
instanceId, appPort, hostPort, target.ip());
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to publish EC2 instance {0} app port {1}: {2}", instanceId, appPort, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void unpublish(Instance instance, int appPort) {
|
||||
String name = forwardContainerName(instance.getInstanceId(), appPort);
|
||||
lifecycleManager.removeIfExists(name);
|
||||
Integer hostPort = instance.getPublishedPorts().remove(appPort);
|
||||
if (hostPort != null) {
|
||||
portAllocator.release(hostPort);
|
||||
persist(instance);
|
||||
LOG.infov("Unpublished EC2 instance {0} app port {1} (released host port {2})",
|
||||
instance.getInstanceId(), appPort, hostPort);
|
||||
}
|
||||
}
|
||||
|
||||
private void persist(Instance instance) {
|
||||
Consumer<Instance> p = persister;
|
||||
if (p != null) {
|
||||
try {
|
||||
p.accept(instance);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Could not persist EC2 instance {0} after forward change: {1}",
|
||||
instance.getInstanceId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static String forwardContainerName(String instanceId, int appPort) {
|
||||
return "floci-ec2-fwd-" + instanceId + "-" + appPort;
|
||||
}
|
||||
|
||||
private NetworkTarget resolveInstanceTarget(Instance instance) {
|
||||
String containerId = instance.getDockerContainerId();
|
||||
if (containerId != null) {
|
||||
try {
|
||||
InspectContainerResponse inspect = dockerClient.inspectContainerCmd(containerId).exec();
|
||||
if (inspect.getNetworkSettings() != null) {
|
||||
Map<String, ContainerNetwork> networks = inspect.getNetworkSettings().getNetworks();
|
||||
NetworkTarget target = pickTarget(networks);
|
||||
if (target != null) {
|
||||
return target;
|
||||
}
|
||||
String ip = inspect.getNetworkSettings().getIpAddress();
|
||||
if (ip != null && !ip.isBlank()) {
|
||||
return new NetworkTarget(null, ip);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Could not inspect EC2 instance {0} container for forward target: {1}",
|
||||
instance.getInstanceId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
String stored = instance.getContainerBridgeIp();
|
||||
if (stored != null && !stored.isBlank()) {
|
||||
return new NetworkTarget(null, stored);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefers a user-defined network (so the sidecar can join it and reach the instance by IP);
|
||||
* falls back to the default bridge with a null network name (the sidecar stays on the bridge
|
||||
* the instance is already on).
|
||||
*/
|
||||
static NetworkTarget pickTarget(Map<String, ContainerNetwork> networks) {
|
||||
if (networks == null || networks.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
for (Map.Entry<String, ContainerNetwork> entry : networks.entrySet()) {
|
||||
String ip = entry.getValue() != null ? entry.getValue().getIpAddress() : null;
|
||||
if (!"bridge".equals(entry.getKey()) && ip != null && !ip.isBlank()) {
|
||||
return new NetworkTarget(entry.getKey(), ip);
|
||||
}
|
||||
}
|
||||
ContainerNetwork bridge = networks.get("bridge");
|
||||
if (bridge != null && bridge.getIpAddress() != null && !bridge.getIpAddress().isBlank()) {
|
||||
return new NetworkTarget(null, bridge.getIpAddress());
|
||||
}
|
||||
for (ContainerNetwork network : networks.values()) {
|
||||
if (network != null && network.getIpAddress() != null && !network.getIpAddress().isBlank()) {
|
||||
return new NetworkTarget(null, network.getIpAddress());
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the set of TCP ports to publish for an instance from its security groups.
|
||||
*
|
||||
* <p>Only CIDR-sourced TCP rules are published: AWS makes a port opened to a referenced
|
||||
* security group reachable from that group's private IPs, not from the host, so rules
|
||||
* sourced only by a security-group reference are skipped. Ports are aggregated (deduped)
|
||||
* across all of the instance's groups, SSH (22) is never forwarded, and any single rule
|
||||
* whose port span exceeds {@code maxPerInstance} is skipped so an allow-all range cannot
|
||||
* spawn thousands of sidecars. The total is capped at {@code maxPerInstance}.
|
||||
*/
|
||||
public static Set<Integer> extractPublishablePorts(List<SecurityGroup> securityGroups, int maxPerInstance) {
|
||||
Set<Integer> ports = new LinkedHashSet<>();
|
||||
for (SecurityGroup sg : securityGroups) {
|
||||
if (sg == null || sg.getIpPermissions() == null) {
|
||||
continue;
|
||||
}
|
||||
for (IpPermission perm : sg.getIpPermissions()) {
|
||||
if (!isTcp(perm.getIpProtocol()) || !hasCidrSource(perm)) {
|
||||
continue;
|
||||
}
|
||||
Integer from = perm.getFromPort();
|
||||
Integer to = perm.getToPort();
|
||||
if (from == null || to == null || from < 0 || to < 0) {
|
||||
continue;
|
||||
}
|
||||
int lo = Math.min(from, to);
|
||||
int hi = Math.max(from, to);
|
||||
long span = (long) hi - lo + 1;
|
||||
if (span > maxPerInstance) {
|
||||
LOG.warnv("Skipping wide security-group ingress range {0}-{1} on {2} (span {3} exceeds max {4})",
|
||||
lo, hi, sg.getGroupId(), span, maxPerInstance);
|
||||
continue;
|
||||
}
|
||||
for (int p = lo; p <= hi; p++) {
|
||||
if (p != SSH_PORT) {
|
||||
ports.add(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ports.size() > maxPerInstance) {
|
||||
LOG.warnv("Capping published ports from {0} to {1} per instance", ports.size(), maxPerInstance);
|
||||
Set<Integer> capped = new LinkedHashSet<>();
|
||||
for (Integer port : ports) {
|
||||
if (capped.size() >= maxPerInstance) {
|
||||
break;
|
||||
}
|
||||
capped.add(port);
|
||||
}
|
||||
return capped;
|
||||
}
|
||||
return ports;
|
||||
}
|
||||
|
||||
static boolean isTcp(String ipProtocol) {
|
||||
return "tcp".equalsIgnoreCase(ipProtocol) || "6".equals(ipProtocol);
|
||||
}
|
||||
|
||||
static boolean hasCidrSource(IpPermission perm) {
|
||||
return (perm.getIpRanges() != null && !perm.getIpRanges().isEmpty())
|
||||
|| (perm.getIpv6Ranges() != null && !perm.getIpv6Ranges().isEmpty());
|
||||
}
|
||||
|
||||
/** A resolved forward destination: the instance IP and the network to reach it on (null = default bridge). */
|
||||
record NetworkTarget(String network, String ip) {
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user