diff --git a/docs/services/elb-classic.md b/docs/services/elb-classic.md
new file mode 100644
index 0000000000..9e39e0e945
--- /dev/null
+++ b/docs/services/elb-classic.md
@@ -0,0 +1,109 @@
+# Elastic Load Balancing (Classic, v1)
+
+**Protocol:** Query (XML) — `POST http://localhost:4566/` with `Action=` and `Version=2012-06-01`
+
+Classic Elastic Load Balancing is the 2012-06-01 API behind `aws elb` and Terraform's `aws_elb`
+resource. It is a **different API** from [ELB v2](elb.md) (ALB/NLB, 2015-12-01), even though both
+are served from the same endpoint host and signed with the same `elasticloadbalancing` credential
+scope.
+
+## How Floci tells the two apart
+
+Every Query-protocol request carries the API version it is speaking as the `Version` form
+parameter, and that is what Floci routes on:
+
+| `Version` | Answered by |
+|---|---|
+| `2012-06-01` | Classic (this page) |
+| `2015-12-01` | [ELB v2](elb.md) |
+
+Responses are emitted in the matching namespace —
+`http://elasticloadbalancing.amazonaws.com/doc/2012-06-01/` for Classic. A Classic
+`CreateLoadBalancer` returns `DNSName` and nothing else; Classic load balancers have no ARN and
+are addressed by `LoadBalancerName` for their whole life.
+
+If a hand-rolled client omits `Version`, Floci falls back to the request shape: an action unique
+to one API decides, and for the action names both APIs define (`CreateLoadBalancer`,
+`DescribeLoadBalancers`, `AddTags`, …) the presence of `LoadBalancerName` or `LoadBalancerNames`
+selects Classic. With neither present the request goes to ELB v2.
+
+## Supported Actions
+
+| Action | Description |
+|--------|-------------|
+| CreateLoadBalancer | Creates a Classic load balancer with listeners, subnets or AZs, security groups, scheme, and tags. Returns `DNSName`. |
+| DescribeLoadBalancers | Returns `LoadBalancerDescription` records, optionally filtered by `LoadBalancerNames`. |
+| DeleteLoadBalancer | Deletes a load balancer; deleting one that does not exist succeeds. |
+| CreateLoadBalancerListeners | Adds listeners. A conflicting listener on a port already in use is rejected with `DuplicateListener`. |
+| DeleteLoadBalancerListeners | Removes listeners by `LoadBalancerPorts`. |
+| ConfigureHealthCheck | Replaces the health check and re-arms Floci's checker. |
+| RegisterInstancesWithLoadBalancer | Registers EC2 instances and returns the full registered set. |
+| DeregisterInstancesFromLoadBalancer | Removes instances and returns the remaining set. |
+| DescribeInstanceHealth | Returns `InstanceStates` for the named instances, or for every registered instance. |
+| ModifyLoadBalancerAttributes | Updates cross-zone, access log, connection draining, connection settings, and additional attributes. Unsent members keep their current value. |
+| DescribeLoadBalancerAttributes | Returns the full attribute structure. |
+| ApplySecurityGroupsToLoadBalancer | Replaces the security groups. |
+| AttachLoadBalancerToSubnets / DetachLoadBalancerFromSubnets | Adds or removes subnets and recomputes the availability zones and VPC. |
+| EnableAvailabilityZonesForLoadBalancer / DisableAvailabilityZonesForLoadBalancer | Adds or removes availability zones. |
+| AddTags / RemoveTags / DescribeTags | Tagging, keyed by `LoadBalancerNames`. |
+| DescribeAccountLimits | Returns standard default Classic limits. |
+
+## Not implemented
+
+These Classic operations return `UnsupportedOperation` in the 2012-06-01 namespace rather than a
+fabricated result:
+
+`CreateAppCookieStickinessPolicy`, `CreateLBCookieStickinessPolicy`, `CreateLoadBalancerPolicy`,
+`DeleteLoadBalancerPolicy`, `DescribeLoadBalancerPolicies`, `DescribeLoadBalancerPolicyTypes`,
+`SetLoadBalancerPoliciesForBackendServer`, `SetLoadBalancerPoliciesOfListener`,
+`SetLoadBalancerListenerSSLCertificate`.
+
+Floci also does not run a Classic **data plane**: listener ports are recorded but no socket is
+opened and no traffic is forwarded. Only the control plane and health checking are emulated.
+
+## Behavior Notes
+
+- Load balancer state is persisted through Floci storage and health checking is restarted on
+ startup.
+- A new load balancer gets AWS's default health check (`TCP:80`, interval 30, timeout 5,
+ unhealthy 2, healthy 10) and AWS's default attributes (cross-zone off, access log off,
+ connection draining off with a 300 second timeout, 60 second idle timeout).
+- Health checks probe the instance's reachable local address. `HTTP:`/`HTTPS:` targets are probed
+ with an HTTP request to the target's path and any 2xx/3xx is healthy; `TCP:`/`SSL:` targets are
+ probed by connecting. TLS is not terminated — an `HTTPS:` target is probed over plain HTTP on
+ the same port.
+- Between registration and the first successful check an instance reports `OutOfService` with
+ reason code `ELB`, as it does on AWS.
+- An Auto Scaling group that names Classic load balancers in `LoadBalancerNames` has its instances
+ registered and deregistered automatically, so a Terraform `min_elb_capacity` wait can be
+ satisfied.
+
+## Configuration
+
+| Environment variable | Default | Description |
+|---|---|---|
+| `FLOCI_SERVICES_ELB_ENABLED` | `true` | Enable or disable the Classic ELB service |
+| `FLOCI_SERVICES_ELB_MOCK` | `false` | When `true`, never probe: a registered instance is `InService` immediately |
+
+## Examples
+
+```bash
+export AWS_ENDPOINT_URL=http://localhost:4566
+
+aws elb create-load-balancer \
+ --load-balancer-name my-classic-elb \
+ --listeners "Protocol=HTTP,LoadBalancerPort=80,InstanceProtocol=HTTP,InstancePort=8080" \
+ --subnets subnet-12345678
+
+aws elb configure-health-check \
+ --load-balancer-name my-classic-elb \
+ --health-check Target=HTTP:8080/,Interval=10,Timeout=3,UnhealthyThreshold=2,HealthyThreshold=2
+
+aws elb register-instances-with-load-balancer \
+ --load-balancer-name my-classic-elb \
+ --instances i-1234567890abcdef0
+
+aws elb describe-instance-health --load-balancer-name my-classic-elb
+
+aws elb delete-load-balancer --load-balancer-name my-classic-elb
+```
diff --git a/docs/services/elb.md b/docs/services/elb.md
index 8704952b96..d7b7b3d0a5 100644
--- a/docs/services/elb.md
+++ b/docs/services/elb.md
@@ -4,6 +4,10 @@
Floci supports Application Load Balancers (ALB) and Network Load Balancers (NLB) through the ELBv2 management API. The control plane is AWS SDK / CLI / Terraform compatible, and HTTP listeners can forward to registered instance targets using the target's reachable local address.
+> Classic (v1) Elastic Load Balancing is a **different API** served from the same endpoint host —
+> see [ELB Classic (v1)](elb-classic.md). Requests are routed by their `Version` parameter:
+> `2015-12-01` here, `2012-06-01` there.
+
## Supported Actions
### Load Balancers
diff --git a/mkdocs.yml b/mkdocs.yml
index a32fee9b88..f2c25126ab 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -132,6 +132,7 @@ nav:
- Bedrock Runtime: services/bedrock-runtime.md
- Bedrock AgentCore: services/bedrock-agentcore.md
- ELB v2: services/elb.md
+ - ELB Classic (v1): services/elb-classic.md
- Auto Scaling: services/autoscaling.md
- Application Auto Scaling: services/applicationautoscaling.md
- Elastic Beanstalk: services/elastic-beanstalk.md
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index 40fdf62332..79d4c0992a 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -659,6 +659,7 @@ public interface EmulatorConfig {
PipesServiceConfig pipes();
BedrockAgentCoreControlServiceConfig bedrockAgentCoreControl();
BedrockAgentCoreServiceConfig bedrockAgentCore();
+ ElbServiceConfig elb();
ElbV2ServiceConfig elbv2();
CodeBuildServiceConfig codebuild();
CodeDeployServiceConfig codedeploy();
@@ -2079,6 +2080,16 @@ public interface EmulatorConfig {
boolean validateRuntimeExists();
}
+ /** Classic (2012-06-01) Elastic Load Balancing — a separate API from {@link ElbV2ServiceConfig}. */
+ interface ElbServiceConfig {
+ @WithDefault("true")
+ boolean enabled();
+
+ /** When true, no health check is ever probed and a registered instance is InService at once. */
+ @WithDefault("false")
+ boolean mock();
+ }
+
interface ElbV2ServiceConfig {
@WithDefault("true")
boolean enabled();
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsNamespaces.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsNamespaces.java
index 0936f33df0..c7118c8612 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsNamespaces.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsNamespaces.java
@@ -17,6 +17,10 @@ public final class AwsNamespaces {
public static final String S3_CONTROL = "http://awss3control.amazonaws.com/doc/2018-08-20/";
public static final String SES = "http://ses.amazonaws.com/doc/2010-12-01/";
public static final String EC2 = "http://ec2.amazonaws.com/doc/2016-11-15/";
+ /** Classic (v1) Elastic Load Balancing. Shares an endpoint host with {@link #ELB_V2},
+ * but is a different API: requests declaring {@code Version=2012-06-01} must be answered
+ * in this namespace, never in the 2015-12-01 one. */
+ public static final String ELB_CLASSIC = "http://elasticloadbalancing.amazonaws.com/doc/2012-06-01/";
public static final String ELB_V2 = "https://elasticloadbalancing.amazonaws.com/doc/2015-12-01/";
public static final String AUTOSCALING = "https://autoscaling.amazonaws.com/doc/2011-01-01/";
public static final String ELASTIC_BEANSTALK = "https://elasticbeanstalk.amazonaws.com/docs/2010-12-01/";
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
index f2689e54d0..88e6db23a2 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.services.autoscaling.AutoScalingQueryHandler;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler;
import io.github.hectorvent.floci.services.ec2.Ec2QueryHandler;
import io.github.hectorvent.floci.services.elasticbeanstalk.ElasticBeanstalkQueryHandler;
+import io.github.hectorvent.floci.services.elb.ElbClassicQueryHandler;
import io.github.hectorvent.floci.services.elbv2.ElbV2QueryHandler;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsQueryHandler;
import io.github.hectorvent.floci.services.cognito.CognitoJsonHandler;
@@ -195,6 +196,7 @@ public class AwsQueryController {
private final CognitoJsonHandler cognitoJsonHandler;
private final Ec2QueryHandler ec2QueryHandler;
private final ElbV2QueryHandler elbV2QueryHandler;
+ private final ElbClassicQueryHandler elbClassicQueryHandler;
private final AutoScalingQueryHandler autoScalingQueryHandler;
private final ElasticBeanstalkQueryHandler elasticBeanstalkQueryHandler;
private final RedshiftQueryHandler redshiftQueryHandler;
@@ -217,6 +219,7 @@ public class AwsQueryController {
CognitoJsonHandler cognitoJsonHandler,
Ec2QueryHandler ec2QueryHandler,
ElbV2QueryHandler elbV2QueryHandler,
+ ElbClassicQueryHandler elbClassicQueryHandler,
AutoScalingQueryHandler autoScalingQueryHandler,
ElasticBeanstalkQueryHandler elasticBeanstalkQueryHandler,
RedshiftQueryHandler redshiftQueryHandler,
@@ -239,6 +242,7 @@ public class AwsQueryController {
this.cognitoJsonHandler = cognitoJsonHandler;
this.ec2QueryHandler = ec2QueryHandler;
this.elbV2QueryHandler = elbV2QueryHandler;
+ this.elbClassicQueryHandler = elbClassicQueryHandler;
this.autoScalingQueryHandler = autoScalingQueryHandler;
this.elasticBeanstalkQueryHandler = elasticBeanstalkQueryHandler;
this.redshiftQueryHandler = redshiftQueryHandler;
@@ -343,7 +347,9 @@ public class AwsQueryController {
case "cloudformation" -> cloudFormationQueryHandler.handle(action, formParams, region);
case "cognito-idp" -> handleCognitoQuery(action, formParams, region);
case "ec2" -> ec2QueryHandler.handle(action, formParams, region);
- case "elasticloadbalancing" -> elbV2QueryHandler.handle(action, formParams, region);
+ case "elasticloadbalancing" -> isElbClassicRequest(action, formParams)
+ ? elbClassicQueryHandler.handle(action, formParams, region)
+ : elbV2QueryHandler.handle(action, formParams, region);
case "autoscaling" -> autoScalingQueryHandler.handle(action, formParams, region);
case "elasticbeanstalk" -> elasticBeanstalkQueryHandler.handle(action, formParams, region);
case "redshift" -> redshiftQueryHandler.handle(action, formParams);
@@ -352,6 +358,48 @@ public class AwsQueryController {
};
}
+ /** The API version a Classic (v1) Elastic Load Balancing request declares. */
+ private static final String ELB_CLASSIC_API_VERSION = "2012-06-01";
+
+ /** The API version an ELBv2 (ALB/NLB) request declares. */
+ private static final String ELB_V2_API_VERSION = "2015-12-01";
+
+ /**
+ * Whether an {@code elasticloadbalancing} request is for the Classic (2012-06-01) API.
+ *
+ *
Classic ELB and ELBv2 share an endpoint host and a credential scope, so the
+ * service name cannot separate them — the same in-case split the {@code rds} scope already
+ * needs for Neptune and DocumentDB. What separates them is the API version, which every
+ * Query-protocol request carries as the {@code Version} form parameter and which both service
+ * models declare. That is the discriminator used here, in preference to guessing from the
+ * shape of the parameters: a client that says {@code Version=2012-06-01} has told us which API
+ * it is speaking, and answering it from the other one is the defect this routing exists to fix.
+ *
+ *
The parameter shape is only a fallback, for a hand-rolled client that omitted
+ * {@code Version}. Then an action unique to one API decides, and for the action names both
+ * APIs define, the presence of a Classic-only parameter does: {@code LoadBalancerName} or
+ * {@code LoadBalancerNames} identify a load balancer by name, which is Classic's addressing
+ * model, whereas ELBv2 uses {@code LoadBalancerArn}, {@code Name} or {@code ResourceArns}.
+ * With neither present the request stays with ELBv2, which is the pre-existing behaviour.
+ */
+ private static boolean isElbClassicRequest(String action, MultivaluedMap formParams) {
+ String version = formParams.getFirst("Version");
+ if (ELB_CLASSIC_API_VERSION.equals(version)) {
+ return true;
+ }
+ if (ELB_V2_API_VERSION.equals(version)) {
+ return false;
+ }
+ if (ElbClassicQueryHandler.CLASSIC_ONLY_ACTIONS.contains(action)) {
+ return true;
+ }
+ if (!ElbClassicQueryHandler.SHARED_ACTIONS.contains(action)) {
+ return false;
+ }
+ return formParams.getFirst("LoadBalancerName") != null
+ || formParams.getFirst("LoadBalancerNames.member.1") != null;
+ }
+
/**
* The AlreadyExists answer when a create names an identifier RDS already holds here, or null.
*
@@ -589,7 +637,8 @@ public class AwsQueryController {
if (EC2_ACTIONS.contains(action)) {
return "ec2";
}
- if (ELB_V2_ACTIONS.contains(action)) {
+ if (ELB_V2_ACTIONS.contains(action)
+ || ElbClassicQueryHandler.CLASSIC_ONLY_ACTIONS.contains(action)) {
return "elasticloadbalancing";
}
if (AUTOSCALING_ACTIONS.contains(action)) {
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
index 5b96a52572..ab6dc75999 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
@@ -340,6 +340,14 @@ public class ResolvedServiceCatalog {
"elbv2", config.storage().mode(), 5000L, AwsNamespaces.ELB_V2, ServiceProtocol.QUERY,
protocols(ServiceProtocol.QUERY),
Set.of(), Set.of("elasticloadbalancing"), Set.of(), Set.of()),
+ // Classic (v1) ELB shares the elasticloadbalancing endpoint and credential scope
+ // with ELBv2 above, so it claims neither here; AwsQueryController splits the two on
+ // the request's Version parameter. Listed so the service and its config knob are
+ // visible in status.
+ descriptor("elb", "elb", config.services().elb().enabled(), true,
+ "elb", config.storage().mode(), 5000L, AwsNamespaces.ELB_CLASSIC, ServiceProtocol.QUERY,
+ protocols(ServiceProtocol.QUERY),
+ Set.of(), Set.of(), Set.of(), Set.of()),
descriptor("codebuild", "codebuild", config.services().codebuild().enabled(), true,
"codebuild", storageMode(config.storage().services().codebuild().mode(), config.storage().mode()),
config.storage().services().codebuild().flushIntervalMs(), null, ServiceProtocol.JSON,
diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java
index af1ae39e7e..2e2229071e 100644
--- a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java
+++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java
@@ -25,6 +25,7 @@ import io.github.hectorvent.floci.services.neptune.container.NeptuneContainerMan
import io.github.hectorvent.floci.services.neptune.proxy.NeptuneProxyManager;
import io.github.hectorvent.floci.services.pipes.PipesService;
import io.github.hectorvent.floci.services.appsync.graphql.SchemaCreationWorker;
+import io.github.hectorvent.floci.services.elb.ElbClassicService;
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
import io.github.hectorvent.floci.services.rds.RdsService;
import io.github.hectorvent.floci.services.memorydb.container.MemoryDbContainerManager;
@@ -82,6 +83,7 @@ public class EmulatorLifecycle {
private final FlinkContainerManager flinkContainerManager;
private final RdsService rdsService;
private final ElbV2Service elbV2Service;
+ private final ElbClassicService elbClassicService;
private final InitializationHooksRunner initializationHooksRunner;
private final SqsEventSourcePoller sqsPoller;
private final KinesisEventSourcePoller kinesisPoller;
@@ -114,6 +116,7 @@ public class EmulatorLifecycle {
FlinkContainerManager flinkContainerManager,
RdsService rdsService,
ElbV2Service elbV2Service,
+ ElbClassicService elbClassicService,
InitializationHooksRunner initializationHooksRunner,
SqsEventSourcePoller sqsPoller,
KinesisEventSourcePoller kinesisPoller,
@@ -145,6 +148,7 @@ public class EmulatorLifecycle {
this.flinkContainerManager = flinkContainerManager;
this.rdsService = rdsService;
this.elbV2Service = elbV2Service;
+ this.elbClassicService = elbClassicService;
this.initializationHooksRunner = initializationHooksRunner;
this.sqsPoller = sqsPoller;
this.kinesisPoller = kinesisPoller;
@@ -202,6 +206,9 @@ public class EmulatorLifecycle {
if (config.services().elbv2().enabled()) {
elbV2Service.restorePersistedRuntime();
}
+ if (config.services().elb().enabled()) {
+ elbClassicService.restorePersistedRuntime();
+ }
if (config.services().ec2().enabled() && !config.services().ec2().mock()) {
ec2MetadataServer.start().exceptionally(ex -> {
diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java
index 31e7750ea0..0160e42210 100644
--- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
import io.github.hectorvent.floci.services.ec2.model.Reservation;
+import io.github.hectorvent.floci.services.elb.ElbClassicService;
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
import io.github.hectorvent.floci.services.elbv2.model.TargetDescription;
import io.github.hectorvent.floci.services.elbv2.model.TargetHealth;
@@ -37,22 +38,25 @@ public class AutoScalingReconciler {
private final AutoScalingService asgService;
private final Ec2Service ec2Service;
private final ElbV2Service elbV2Service;
+ private final ElbClassicService elbClassicService;
private final SsmCommandService ssmCommandService;
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(
r -> new Thread(r, "asg-reconciler"));
@Inject
AutoScalingReconciler(AutoScalingService asgService, Ec2Service ec2Service,
- ElbV2Service elbV2Service, SsmCommandService ssmCommandService) {
+ ElbV2Service elbV2Service, ElbClassicService elbClassicService,
+ SsmCommandService ssmCommandService) {
this.asgService = asgService;
this.ec2Service = ec2Service;
this.elbV2Service = elbV2Service;
+ this.elbClassicService = elbClassicService;
this.ssmCommandService = ssmCommandService;
}
AutoScalingReconciler(AutoScalingService asgService, Ec2Service ec2Service,
ElbV2Service elbV2Service) {
- this(asgService, ec2Service, elbV2Service, null);
+ this(asgService, ec2Service, elbV2Service, null, null);
}
@PostConstruct
@@ -124,6 +128,7 @@ public class AutoScalingReconciler {
asgInst.setLifecycleState("InService");
asgInst.setHealthStatus("Healthy");
registerWithTargetGroups(asg, asgInst);
+ registerWithClassicLoadBalancers(asg, asgInst);
changed = true;
asgService.recordActivity(asg.getRegion(), asg.getAutoScalingGroupName(),
"Launching a new EC2 instance: " + asgInst.getInstanceId(),
@@ -154,6 +159,8 @@ public class AutoScalingReconciler {
.map(AsgInstance::getInstanceId)
.collect(Collectors.toList());
failActiveSsmInvocations(asg, instanceIds);
+ deregisterFromTargetGroups(asg, instanceIds);
+ deregisterFromClassicLoadBalancers(asg, instanceIds);
asg.getInstances().removeIf(instance -> instanceIds.contains(instance.getInstanceId()));
asgService.saveAutoScalingGroup(asg);
asgService.recordActivity(asg.getRegion(), asg.getAutoScalingGroupName(),
@@ -258,6 +265,7 @@ public class AutoScalingReconciler {
.map(AsgInstance::getInstanceId)
.collect(Collectors.toList());
deregisterFromTargetGroups(asg, instanceIds);
+ deregisterFromClassicLoadBalancers(asg, instanceIds);
try {
ec2Service.terminateInstances(asg.getRegion(), instanceIds);
} catch (Exception e) {
@@ -361,6 +369,7 @@ public class AutoScalingReconciler {
.collect(Collectors.toList());
deregisterFromTargetGroups(asg, instanceIds);
+ deregisterFromClassicLoadBalancers(asg, instanceIds);
try {
ec2Service.terminateInstances(asg.getRegion(), instanceIds);
@@ -391,6 +400,45 @@ public class AutoScalingReconciler {
}
}
+ /**
+ * Registers a newly launched instance with every Classic load balancer the group names.
+ *
+ * An ASG attached through {@code LoadBalancerNames} feeds a Classic load balancer, not a
+ * target group, and the two lists are independent — a group can carry either or both. Without
+ * this the Classic load balancer would stay empty, and a {@code min_elb_capacity} wait would
+ * never be satisfied.
+ */
+ private void registerWithClassicLoadBalancers(AutoScalingGroup asg, AsgInstance asgInst) {
+ if (elbClassicService == null) {
+ return;
+ }
+ for (String lbName : asg.getLoadBalancerNames()) {
+ try {
+ elbClassicService.registerInstances(asg.getRegion(), lbName,
+ List.of(asgInst.getInstanceId()));
+ LOG.debugv("ASG {0}: registered {1} with Classic ELB {2}",
+ asg.getAutoScalingGroupName(), asgInst.getInstanceId(), lbName);
+ } catch (Exception e) {
+ LOG.warnv("ASG {0}: could not register {1} with Classic ELB {2}: {3}",
+ asg.getAutoScalingGroupName(), asgInst.getInstanceId(), lbName, e.getMessage());
+ }
+ }
+ }
+
+ private void deregisterFromClassicLoadBalancers(AutoScalingGroup asg, List instanceIds) {
+ if (elbClassicService == null) {
+ return;
+ }
+ for (String lbName : asg.getLoadBalancerNames()) {
+ try {
+ elbClassicService.deregisterInstances(asg.getRegion(), lbName, instanceIds);
+ } catch (Exception e) {
+ LOG.debugv("ASG {0}: could not deregister from Classic ELB {1}: {2}",
+ asg.getAutoScalingGroupName(), lbName, e.getMessage());
+ }
+ }
+ }
+
private void registerWithTargetGroups(AutoScalingGroup asg, AsgInstance asgInst) {
for (String tgArn : asg.getTargetGroupARNs()) {
try {
diff --git a/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicHealthChecker.java b/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicHealthChecker.java
new file mode 100644
index 0000000000..87246d59af
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicHealthChecker.java
@@ -0,0 +1,283 @@
+package io.github.hectorvent.floci.services.elb;
+
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.Resettable;
+import io.github.hectorvent.floci.services.ec2.Ec2Service;
+import io.github.hectorvent.floci.services.ec2.model.Instance;
+import io.github.hectorvent.floci.services.elb.model.ClassicHealthCheck;
+import io.github.hectorvent.floci.services.elb.model.ClassicLoadBalancer;
+import io.vertx.core.Vertx;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.net.URL;
+import java.util.Collection;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * Health checking for Classic (2012-06-01) load balancers.
+ *
+ * Classic health is per instance on one load balancer, not per target on a target group, and
+ * the check itself is described by a single {@code Target} string such as {@code HTTP:8080/} or
+ * {@code TCP:80} rather than by separate protocol, port and path members — so this cannot reuse
+ * {@code ElbV2HealthChecker}. The probing shape is deliberately the same: a Vert.x periodic timer
+ * per load balancer, consecutive success/failure counters, and the configured thresholds.
+ *
+ *
With {@code floci.services.elb.mock=true} no probe is ever made and a registered instance is
+ * reported {@code InService} straight away.
+ */
+@ApplicationScoped
+public class ElbClassicHealthChecker implements Resettable {
+
+ private static final Logger LOG = Logger.getLogger(ElbClassicHealthChecker.class);
+
+ /** The health of one registered instance, in the {@code InstanceState} shape of the v1 model. */
+ public record InstanceHealth(String state, String reasonCode, String description) {
+
+ static InstanceHealth inService() {
+ return new InstanceHealth("InService", "N/A", "N/A");
+ }
+
+ static InstanceHealth registering() {
+ return new InstanceHealth("OutOfService", "ELB",
+ "Instance registration is still in progress.");
+ }
+
+ static InstanceHealth failedChecks() {
+ return new InstanceHealth("OutOfService", "Instance",
+ "Instance has failed at least the UnhealthyThreshold number of health checks "
+ + "consecutively.");
+ }
+ }
+
+ private final Vertx vertx;
+ private final EmulatorConfig config;
+ private final Ec2Service ec2Service;
+
+ // "region|lbName" → instanceId → state
+ private final Map> states = new ConcurrentHashMap<>();
+ // "region|lbName" → Vert.x timer id
+ private final Map timers = new ConcurrentHashMap<>();
+
+ @Inject
+ public ElbClassicHealthChecker(Vertx vertx, EmulatorConfig config, Ec2Service ec2Service) {
+ this.vertx = vertx;
+ this.config = config;
+ this.ec2Service = ec2Service;
+ }
+
+ public static String key(String region, String loadBalancerName) {
+ return region + "|" + loadBalancerName;
+ }
+
+ public void startMonitoring(ClassicLoadBalancer lb) {
+ String k = key(lb.getRegion(), lb.getLoadBalancerName());
+ states.computeIfAbsent(k, x -> new ConcurrentHashMap<>());
+ if (mock() || vertx == null) {
+ return;
+ }
+ stopTimer(k);
+ int interval = lb.getHealthCheck() != null && lb.getHealthCheck().getInterval() != null
+ ? lb.getHealthCheck().getInterval() : 30;
+ timers.put(k, vertx.setPeriodic(interval * 1000L, id -> probeAll(lb)));
+ }
+
+ public void stopMonitoring(String region, String loadBalancerName) {
+ String k = key(region, loadBalancerName);
+ stopTimer(k);
+ states.remove(k);
+ }
+
+ /** Re-arms the periodic timer after {@code ConfigureHealthCheck} changed the interval. */
+ public void healthCheckChanged(ClassicLoadBalancer lb) {
+ if (states.containsKey(key(lb.getRegion(), lb.getLoadBalancerName()))) {
+ startMonitoring(lb);
+ }
+ }
+
+ public void registerInstances(ClassicLoadBalancer lb, Collection instanceIds) {
+ Map lbStates =
+ states.computeIfAbsent(key(lb.getRegion(), lb.getLoadBalancerName()),
+ k -> new ConcurrentHashMap<>());
+ for (String id : instanceIds) {
+ lbStates.putIfAbsent(id, new InstanceState());
+ }
+ if (!mock() && vertx != null) {
+ vertx.setTimer(1, ignored -> probeAll(lb));
+ }
+ }
+
+ public void deregisterInstances(String region, String loadBalancerName, Collection instanceIds) {
+ Map lbStates = states.get(key(region, loadBalancerName));
+ if (lbStates != null) {
+ instanceIds.forEach(lbStates::remove);
+ }
+ }
+
+ /**
+ * The health of one instance registered with a load balancer.
+ *
+ * An instance with no probe result yet is {@code OutOfService}/{@code ELB}, which is what a
+ * live Classic load balancer reports between {@code RegisterInstancesWithLoadBalancer} and the
+ * first successful check.
+ */
+ public InstanceHealth getHealth(String region, String loadBalancerName, String instanceId) {
+ if (mock()) {
+ return InstanceHealth.inService();
+ }
+ Map lbStates = states.get(key(region, loadBalancerName));
+ InstanceState s = lbStates != null ? lbStates.get(instanceId) : null;
+ if (s == null || s.health == null) {
+ return InstanceHealth.registering();
+ }
+ return s.health;
+ }
+
+ @Override
+ public void clear() {
+ if (vertx != null) {
+ timers.values().forEach(vertx::cancelTimer);
+ }
+ timers.clear();
+ states.clear();
+ }
+
+ private boolean mock() {
+ return config != null && config.services().elb().mock();
+ }
+
+ private void stopTimer(String k) {
+ Long timerId = timers.remove(k);
+ if (timerId != null && vertx != null) {
+ vertx.cancelTimer(timerId);
+ }
+ }
+
+ private void probeAll(ClassicLoadBalancer lb) {
+ Map lbStates = states.get(key(lb.getRegion(), lb.getLoadBalancerName()));
+ if (lbStates == null || lbStates.isEmpty()) {
+ return;
+ }
+ ClassicHealthCheck hc = lb.getHealthCheck() != null ? lb.getHealthCheck() : ClassicHealthCheck.defaults();
+ Target target = Target.parse(hc.getTarget());
+ if (target == null) {
+ return;
+ }
+ int timeout = hc.getTimeout() != null ? hc.getTimeout() : 5;
+ int healthyThreshold = hc.getHealthyThreshold() != null ? hc.getHealthyThreshold() : 10;
+ int unhealthyThreshold = hc.getUnhealthyThreshold() != null ? hc.getUnhealthyThreshold() : 2;
+
+ for (Map.Entry entry : lbStates.entrySet()) {
+ String instanceId = entry.getKey();
+ InstanceState state = entry.getValue();
+ String host = resolveHost(instanceId);
+ vertx.executeBlocking(() -> probe(host, target, timeout))
+ .onSuccess(ok -> {
+ if (Boolean.TRUE.equals(ok)) {
+ state.consecutiveFailures = 0;
+ state.consecutiveSuccesses++;
+ if (state.consecutiveSuccesses >= healthyThreshold) {
+ state.health = InstanceHealth.inService();
+ }
+ } else {
+ recordFailure(state, unhealthyThreshold);
+ }
+ })
+ .onFailure(err -> {
+ recordFailure(state, unhealthyThreshold);
+ LOG.debugv("Classic ELB health check failed for {0} ({1}): {2}",
+ instanceId, host, err.getMessage());
+ });
+ }
+ }
+
+ private static void recordFailure(InstanceState state, int unhealthyThreshold) {
+ state.consecutiveSuccesses = 0;
+ state.consecutiveFailures++;
+ if (state.consecutiveFailures >= unhealthyThreshold) {
+ state.health = InstanceHealth.failedChecks();
+ }
+ }
+
+ private String resolveHost(String instanceId) {
+ if (ec2Service == null) {
+ return instanceId;
+ }
+ Instance instance = ec2Service.findInstanceById(instanceId);
+ if (instance == null) {
+ return instanceId;
+ }
+ String bridgeIp = instance.getContainerBridgeIp();
+ return bridgeIp != null && !bridgeIp.isBlank() ? bridgeIp : instanceId;
+ }
+
+ private static boolean probe(String host, Target target, int timeoutSeconds) throws IOException {
+ int timeoutMs = timeoutSeconds * 1000;
+ if (target.path() == null) {
+ try (Socket socket = new Socket()) {
+ socket.connect(new InetSocketAddress(host, target.port()), timeoutMs);
+ return true;
+ }
+ }
+ URL url = new URL(target.scheme(), host, target.port(), target.path());
+ HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+ conn.setConnectTimeout(timeoutMs);
+ conn.setReadTimeout(timeoutMs);
+ conn.setInstanceFollowRedirects(false);
+ try {
+ int code = conn.getResponseCode();
+ // Classic ELB treats any 2xx or 3xx as a healthy HTTP check.
+ return code >= 200 && code < 400;
+ } finally {
+ conn.disconnect();
+ }
+ }
+
+ /**
+ * A parsed {@code HealthCheck.Target} — {@code HTTP:8080/health}, {@code TCP:80}, and so on.
+ * {@code path} is null for the connection-only protocols, which is what selects a TCP probe.
+ */
+ record Target(String scheme, int port, String path) {
+
+ static Target parse(String raw) {
+ if (raw == null || raw.isBlank()) {
+ return null;
+ }
+ int colon = raw.indexOf(':');
+ if (colon < 0) {
+ return null;
+ }
+ String protocol = raw.substring(0, colon).toUpperCase();
+ String rest = raw.substring(colon + 1);
+ int slash = rest.indexOf('/');
+ String portPart = slash < 0 ? rest : rest.substring(0, slash);
+ String path = slash < 0 ? null : rest.substring(slash);
+ int port;
+ try {
+ port = Integer.parseInt(portPart.trim());
+ } catch (NumberFormatException e) {
+ return null;
+ }
+ return switch (protocol) {
+ case "HTTP" -> new Target("http", port, path != null ? path : "/");
+ // Floci does not terminate TLS for Classic health checks; an HTTPS target is
+ // probed over plain HTTP against the same port rather than reported unknown.
+ case "HTTPS" -> new Target("http", port, path != null ? path : "/");
+ case "TCP", "SSL" -> new Target(null, port, null);
+ default -> null;
+ };
+ }
+ }
+
+ private static final class InstanceState {
+ volatile InstanceHealth health;
+ volatile int consecutiveSuccesses;
+ volatile int consecutiveFailures;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicQueryHandler.java
new file mode 100644
index 0000000000..bcf92c12c3
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicQueryHandler.java
@@ -0,0 +1,621 @@
+package io.github.hectorvent.floci.services.elb;
+
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.AwsNamespaces;
+import io.github.hectorvent.floci.core.common.AwsQueryResponse;
+import io.github.hectorvent.floci.core.common.XmlBuilder;
+import io.github.hectorvent.floci.services.elb.model.ClassicHealthCheck;
+import io.github.hectorvent.floci.services.elb.model.ClassicListener;
+import io.github.hectorvent.floci.services.elb.model.ClassicLoadBalancer;
+import io.github.hectorvent.floci.services.elb.model.ClassicLoadBalancerAttributes;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.Response;
+import org.jboss.logging.Logger;
+
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Query-protocol handler for Classic (2012-06-01) Elastic Load Balancing.
+ *
+ * Every response is emitted in the 2012-06-01 namespace with the wrapper element names the
+ * 2012-06-01 model declares. A Classic {@code CreateLoadBalancer} answer carries {@code DNSName}
+ * and nothing else — no ARN and no {@code LoadBalancers} member list, both of which belong to the
+ * 2015-12-01 API.
+ *
+ *
Scope. Implemented are the operations the AWS provider drives for {@code aws_elb} and
+ * for an Auto Scaling group attached to one. The stickiness- and backend-policy operations are not
+ * implemented and are answered with {@code UnsupportedOperation}, which is honest and lets a caller
+ * see the boundary, rather than a fabricated success.
+ */
+@ApplicationScoped
+public class ElbClassicQueryHandler {
+
+ private static final Logger LOG = Logger.getLogger(ElbClassicQueryHandler.class);
+
+ private static final DateTimeFormatter ISO_FMT =
+ DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC);
+
+ /**
+ * Actions that exist only in the Classic API. Used by the dispatcher to route a request that
+ * arrived without a {@code Version} parameter, and never overlapping {@link #SHARED_ACTIONS}.
+ */
+ public static final Set CLASSIC_ONLY_ACTIONS = Set.of(
+ "ConfigureHealthCheck",
+ "RegisterInstancesWithLoadBalancer", "DeregisterInstancesFromLoadBalancer",
+ "DescribeInstanceHealth",
+ "CreateLoadBalancerListeners", "DeleteLoadBalancerListeners",
+ "SetLoadBalancerListenerSSLCertificate",
+ "ApplySecurityGroupsToLoadBalancer",
+ "AttachLoadBalancerToSubnets", "DetachLoadBalancerFromSubnets",
+ "EnableAvailabilityZonesForLoadBalancer", "DisableAvailabilityZonesForLoadBalancer",
+ "CreateAppCookieStickinessPolicy", "CreateLBCookieStickinessPolicy",
+ "CreateLoadBalancerPolicy", "DeleteLoadBalancerPolicy",
+ "DescribeLoadBalancerPolicies", "DescribeLoadBalancerPolicyTypes",
+ "SetLoadBalancerPoliciesForBackendServer", "SetLoadBalancerPoliciesOfListener"
+ );
+
+ /** Action names that both API versions define, and so cannot route on their own. */
+ public static final Set SHARED_ACTIONS = Set.of(
+ "CreateLoadBalancer", "DeleteLoadBalancer", "DescribeLoadBalancers",
+ "ModifyLoadBalancerAttributes", "DescribeLoadBalancerAttributes",
+ "AddTags", "RemoveTags", "DescribeTags", "DescribeAccountLimits"
+ );
+
+ private static final Map ACCOUNT_LIMITS = new LinkedHashMap<>();
+
+ static {
+ ACCOUNT_LIMITS.put("classic-load-balancers", "20");
+ ACCOUNT_LIMITS.put("classic-listeners", "100");
+ ACCOUNT_LIMITS.put("classic-registered-instances", "1000");
+ }
+
+ private final ElbClassicService service;
+ private final EmulatorConfig config;
+
+ @Inject
+ public ElbClassicQueryHandler(ElbClassicService service, EmulatorConfig config) {
+ this.service = service;
+ this.config = config;
+ }
+
+ public Response handle(String action, MultivaluedMap params, String region) {
+ LOG.debugv("ELB Classic action: {0}", action);
+ if (!config.services().elb().enabled()) {
+ return xmlError("ServiceUnavailable",
+ "The Elastic Load Balancing 2012-06-01 API is disabled "
+ + "(floci.services.elb.enabled=false).", 503);
+ }
+ try {
+ return switch (action) {
+ case "CreateLoadBalancer" -> createLoadBalancer(params, region);
+ case "DeleteLoadBalancer" -> deleteLoadBalancer(params, region);
+ case "DescribeLoadBalancers" -> describeLoadBalancers(params, region);
+ case "CreateLoadBalancerListeners" -> createListeners(params, region);
+ case "DeleteLoadBalancerListeners" -> deleteListeners(params, region);
+ case "ConfigureHealthCheck" -> configureHealthCheck(params, region);
+ case "RegisterInstancesWithLoadBalancer" -> registerInstances(params, region);
+ case "DeregisterInstancesFromLoadBalancer" -> deregisterInstances(params, region);
+ case "DescribeInstanceHealth" -> describeInstanceHealth(params, region);
+ case "ModifyLoadBalancerAttributes" -> modifyAttributes(params, region);
+ case "DescribeLoadBalancerAttributes" -> describeAttributes(params, region);
+ case "ApplySecurityGroupsToLoadBalancer" -> applySecurityGroups(params, region);
+ case "AttachLoadBalancerToSubnets" -> attachSubnets(params, region);
+ case "DetachLoadBalancerFromSubnets" -> detachSubnets(params, region);
+ case "EnableAvailabilityZonesForLoadBalancer" -> enableZones(params, region);
+ case "DisableAvailabilityZonesForLoadBalancer" -> disableZones(params, region);
+ case "AddTags" -> addTags(params, region);
+ case "RemoveTags" -> removeTags(params, region);
+ case "DescribeTags" -> describeTags(params, region);
+ case "DescribeAccountLimits" -> describeAccountLimits();
+ default -> xmlError("UnsupportedOperation",
+ "Action " + action + " is not supported by the Elastic Load Balancing "
+ + "2012-06-01 API in Floci.", 400);
+ };
+ } catch (AwsException e) {
+ return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
+ }
+ }
+
+ // ── Load balancers ────────────────────────────────────────────────────────
+
+ private Response createLoadBalancer(MultivaluedMap p, String region) {
+ ClassicLoadBalancer lb = service.createLoadBalancer(
+ region,
+ p.getFirst("LoadBalancerName"),
+ parseListeners(p, "Listeners"),
+ memberList(p, "AvailabilityZones"),
+ memberList(p, "Subnets"),
+ memberList(p, "SecurityGroups"),
+ p.getFirst("Scheme"),
+ parseTags(p));
+
+ // The 2012-06-01 model gives CreateAccessPointOutput exactly one member: DNSName.
+ return ok(new XmlBuilder()
+ .start("CreateLoadBalancerResponse", AwsNamespaces.ELB_CLASSIC)
+ .start("CreateLoadBalancerResult")
+ .elem("DNSName", lb.getDnsName())
+ .end("CreateLoadBalancerResult")
+ .raw(AwsQueryResponse.responseMetadata())
+ .end("CreateLoadBalancerResponse")
+ .build());
+ }
+
+ private Response deleteLoadBalancer(MultivaluedMap p, String region) {
+ service.deleteLoadBalancer(region, requireName(p));
+ return emptyResult("DeleteLoadBalancer");
+ }
+
+ private Response describeLoadBalancers(MultivaluedMap p, String region) {
+ List lbs = service.describeLoadBalancers(region, memberList(p, "LoadBalancerNames"));
+
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeLoadBalancersResponse", AwsNamespaces.ELB_CLASSIC)
+ .start("DescribeLoadBalancersResult")
+ .start("LoadBalancerDescriptions");
+ for (ClassicLoadBalancer lb : lbs) {
+ xml.start("member").raw(loadBalancerDescriptionXml(lb)).end("member");
+ }
+ xml.end("LoadBalancerDescriptions")
+ .end("DescribeLoadBalancersResult")
+ .raw(AwsQueryResponse.responseMetadata())
+ .end("DescribeLoadBalancersResponse");
+ return ok(xml.build());
+ }
+
+ // ── Listeners ─────────────────────────────────────────────────────────────
+
+ private Response createListeners(MultivaluedMap p, String region) {
+ service.createLoadBalancerListeners(region, requireName(p), parseListeners(p, "Listeners"));
+ return emptyResult("CreateLoadBalancerListeners");
+ }
+
+ private Response deleteListeners(MultivaluedMap p, String region) {
+ List ports = new ArrayList<>();
+ for (String port : memberList(p, "LoadBalancerPorts")) {
+ ports.add(Integer.parseInt(port));
+ }
+ service.deleteLoadBalancerListeners(region, requireName(p), ports);
+ return emptyResult("DeleteLoadBalancerListeners");
+ }
+
+ // ── Health ────────────────────────────────────────────────────────────────
+
+ private Response configureHealthCheck(MultivaluedMap p, String region) {
+ ClassicHealthCheck hc = new ClassicHealthCheck();
+ hc.setTarget(p.getFirst("HealthCheck.Target"));
+ hc.setInterval(intOrNull(p.getFirst("HealthCheck.Interval")));
+ hc.setTimeout(intOrNull(p.getFirst("HealthCheck.Timeout")));
+ hc.setUnhealthyThreshold(intOrNull(p.getFirst("HealthCheck.UnhealthyThreshold")));
+ hc.setHealthyThreshold(intOrNull(p.getFirst("HealthCheck.HealthyThreshold")));
+
+ ClassicHealthCheck stored = service.configureHealthCheck(region, requireName(p), hc);
+ return ok(new XmlBuilder()
+ .start("ConfigureHealthCheckResponse", AwsNamespaces.ELB_CLASSIC)
+ .start("ConfigureHealthCheckResult")
+ .raw(healthCheckXml(stored))
+ .end("ConfigureHealthCheckResult")
+ .raw(AwsQueryResponse.responseMetadata())
+ .end("ConfigureHealthCheckResponse")
+ .build());
+ }
+
+ private Response registerInstances(MultivaluedMap p, String region) {
+ List registered = service.registerInstances(region, requireName(p), parseInstanceIds(p));
+ return ok(instanceListResponse("RegisterInstancesWithLoadBalancer", registered));
+ }
+
+ private Response deregisterInstances(MultivaluedMap p, String region) {
+ List remaining = service.deregisterInstances(region, requireName(p), parseInstanceIds(p));
+ return ok(instanceListResponse("DeregisterInstancesFromLoadBalancer", remaining));
+ }
+
+ private Response describeInstanceHealth(MultivaluedMap p, String region) {
+ Map health =
+ service.describeInstanceHealth(region, requireName(p), parseInstanceIds(p));
+
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeInstanceHealthResponse", AwsNamespaces.ELB_CLASSIC)
+ .start("DescribeInstanceHealthResult")
+ .start("InstanceStates");
+ for (Map.Entry e : health.entrySet()) {
+ xml.start("member")
+ .elem("InstanceId", e.getKey())
+ .elem("State", e.getValue().state())
+ .elem("ReasonCode", e.getValue().reasonCode())
+ .elem("Description", e.getValue().description())
+ .end("member");
+ }
+ xml.end("InstanceStates")
+ .end("DescribeInstanceHealthResult")
+ .raw(AwsQueryResponse.responseMetadata())
+ .end("DescribeInstanceHealthResponse");
+ return ok(xml.build());
+ }
+
+ // ── Attributes ────────────────────────────────────────────────────────────
+
+ private Response modifyAttributes(MultivaluedMap p, String region) {
+ String prefix = "LoadBalancerAttributes.";
+ Map additional = new LinkedHashMap<>();
+ int i = 1;
+ while (true) {
+ String key = p.getFirst(prefix + "AdditionalAttributes.member." + i + ".Key");
+ if (key == null) break;
+ additional.put(key, p.getFirst(prefix + "AdditionalAttributes.member." + i + ".Value"));
+ i++;
+ }
+ ElbClassicService.AttributeUpdate update = new ElbClassicService.AttributeUpdate(
+ boolOrNull(p.getFirst(prefix + "CrossZoneLoadBalancing.Enabled")),
+ boolOrNull(p.getFirst(prefix + "AccessLog.Enabled")),
+ p.getFirst(prefix + "AccessLog.S3BucketName"),
+ p.getFirst(prefix + "AccessLog.S3BucketPrefix"),
+ intOrNull(p.getFirst(prefix + "AccessLog.EmitInterval")),
+ boolOrNull(p.getFirst(prefix + "ConnectionDraining.Enabled")),
+ intOrNull(p.getFirst(prefix + "ConnectionDraining.Timeout")),
+ intOrNull(p.getFirst(prefix + "ConnectionSettings.IdleTimeout")),
+ additional);
+
+ ClassicLoadBalancer lb = service.modifyLoadBalancerAttributes(region, requireName(p), update);
+ return ok(new XmlBuilder()
+ .start("ModifyLoadBalancerAttributesResponse", AwsNamespaces.ELB_CLASSIC)
+ .start("ModifyLoadBalancerAttributesResult")
+ .elem("LoadBalancerName", lb.getLoadBalancerName())
+ .raw(attributesXml(lb.getAttributes()))
+ .end("ModifyLoadBalancerAttributesResult")
+ .raw(AwsQueryResponse.responseMetadata())
+ .end("ModifyLoadBalancerAttributesResponse")
+ .build());
+ }
+
+ private Response describeAttributes(MultivaluedMap p, String region) {
+ ClassicLoadBalancer lb = service.requireLoadBalancer(region, requireName(p));
+ return ok(new XmlBuilder()
+ .start("DescribeLoadBalancerAttributesResponse", AwsNamespaces.ELB_CLASSIC)
+ .start("DescribeLoadBalancerAttributesResult")
+ .raw(attributesXml(lb.getAttributes()))
+ .end("DescribeLoadBalancerAttributesResult")
+ .raw(AwsQueryResponse.responseMetadata())
+ .end("DescribeLoadBalancerAttributesResponse")
+ .build());
+ }
+
+ // ── Zones, subnets, security groups ───────────────────────────────────────
+
+ private Response applySecurityGroups(MultivaluedMap p, String region) {
+ List sgs = service.applySecurityGroups(region, requireName(p), memberList(p, "SecurityGroups"));
+ return ok(stringListResponse("ApplySecurityGroupsToLoadBalancer", "SecurityGroups", sgs));
+ }
+
+ private Response attachSubnets(MultivaluedMap p, String region) {
+ List subnets = service.attachToSubnets(region, requireName(p), memberList(p, "Subnets"));
+ return ok(stringListResponse("AttachLoadBalancerToSubnets", "Subnets", subnets));
+ }
+
+ private Response detachSubnets(MultivaluedMap p, String region) {
+ List subnets = service.detachFromSubnets(region, requireName(p), memberList(p, "Subnets"));
+ return ok(stringListResponse("DetachLoadBalancerFromSubnets", "Subnets", subnets));
+ }
+
+ private Response enableZones(MultivaluedMap p, String region) {
+ List zones = service.enableAvailabilityZones(region, requireName(p),
+ memberList(p, "AvailabilityZones"));
+ return ok(stringListResponse("EnableAvailabilityZonesForLoadBalancer", "AvailabilityZones", zones));
+ }
+
+ private Response disableZones(MultivaluedMap p, String region) {
+ List zones = service.disableAvailabilityZones(region, requireName(p),
+ memberList(p, "AvailabilityZones"));
+ return ok(stringListResponse("DisableAvailabilityZonesForLoadBalancer", "AvailabilityZones", zones));
+ }
+
+ // ── Tags ──────────────────────────────────────────────────────────────────
+
+ private Response addTags(MultivaluedMap p, String region) {
+ service.addTags(region, memberList(p, "LoadBalancerNames"), parseTags(p));
+ return emptyResult("AddTags");
+ }
+
+ private Response removeTags(MultivaluedMap p, String region) {
+ // RemoveTags carries TagKeyOnly members — Key without Value.
+ List keys = new ArrayList<>();
+ int i = 1;
+ while (true) {
+ String key = p.getFirst("Tags.member." + i + ".Key");
+ if (key == null) break;
+ keys.add(key);
+ i++;
+ }
+ service.removeTags(region, memberList(p, "LoadBalancerNames"), keys);
+ return emptyResult("RemoveTags");
+ }
+
+ private Response describeTags(MultivaluedMap p, String region) {
+ Map> tags =
+ service.describeTags(region, memberList(p, "LoadBalancerNames"));
+
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeTagsResponse", AwsNamespaces.ELB_CLASSIC)
+ .start("DescribeTagsResult")
+ .start("TagDescriptions");
+ for (Map.Entry> lbTags : tags.entrySet()) {
+ xml.start("member")
+ .elem("LoadBalancerName", lbTags.getKey())
+ .start("Tags");
+ for (Map.Entry tag : lbTags.getValue().entrySet()) {
+ xml.start("member").elem("Key", tag.getKey()).elem("Value", tag.getValue()).end("member");
+ }
+ xml.end("Tags").end("member");
+ }
+ xml.end("TagDescriptions")
+ .end("DescribeTagsResult")
+ .raw(AwsQueryResponse.responseMetadata())
+ .end("DescribeTagsResponse");
+ return ok(xml.build());
+ }
+
+ private Response describeAccountLimits() {
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeAccountLimitsResponse", AwsNamespaces.ELB_CLASSIC)
+ .start("DescribeAccountLimitsResult")
+ .start("Limits");
+ for (Map.Entry limit : ACCOUNT_LIMITS.entrySet()) {
+ xml.start("member").elem("Name", limit.getKey()).elem("Max", limit.getValue()).end("member");
+ }
+ xml.end("Limits")
+ .end("DescribeAccountLimitsResult")
+ .raw(AwsQueryResponse.responseMetadata())
+ .end("DescribeAccountLimitsResponse");
+ return ok(xml.build());
+ }
+
+ // ── XML fragments ─────────────────────────────────────────────────────────
+
+ private String loadBalancerDescriptionXml(ClassicLoadBalancer lb) {
+ XmlBuilder xml = new XmlBuilder()
+ .elem("LoadBalancerName", lb.getLoadBalancerName())
+ .elem("DNSName", lb.getDnsName())
+ .elem("CanonicalHostedZoneName", lb.getCanonicalHostedZoneName())
+ .elem("CanonicalHostedZoneNameID", lb.getCanonicalHostedZoneNameId())
+ .start("ListenerDescriptions");
+ for (ClassicListener listener : lb.getListeners()) {
+ xml.start("member")
+ .start("Listener")
+ .elem("Protocol", listener.getProtocol())
+ .elem("LoadBalancerPort", String.valueOf(listener.getLoadBalancerPort()))
+ .elem("InstanceProtocol", listener.getInstanceProtocol())
+ .elem("InstancePort", String.valueOf(listener.getInstancePort()))
+ .elem("SSLCertificateId", listener.getSslCertificateId())
+ .end("Listener")
+ .start("PolicyNames").end("PolicyNames")
+ .end("member");
+ }
+ xml.end("ListenerDescriptions")
+ // Floci implements no Classic policies; the element is present and empty, as it is on a
+ // live load balancer that has none.
+ .start("Policies")
+ .start("AppCookieStickinessPolicies").end("AppCookieStickinessPolicies")
+ .start("LBCookieStickinessPolicies").end("LBCookieStickinessPolicies")
+ .start("OtherPolicies").end("OtherPolicies")
+ .end("Policies")
+ .start("BackendServerDescriptions").end("BackendServerDescriptions")
+ .start("AvailabilityZones");
+ for (String zone : lb.getAvailabilityZones()) {
+ xml.elem("member", zone);
+ }
+ xml.end("AvailabilityZones").start("Subnets");
+ for (String subnet : lb.getSubnets()) {
+ xml.elem("member", subnet);
+ }
+ xml.end("Subnets")
+ .elem("VPCId", lb.getVpcId())
+ .start("Instances");
+ for (String instanceId : lb.getInstanceIds()) {
+ xml.start("member").elem("InstanceId", instanceId).end("member");
+ }
+ xml.end("Instances")
+ .raw(healthCheckXml(lb.getHealthCheck()))
+ .start("SourceSecurityGroup")
+ .elem("OwnerAlias", lb.getSourceSecurityGroupOwnerAlias())
+ .elem("GroupName", lb.getSourceSecurityGroupName())
+ .end("SourceSecurityGroup")
+ .start("SecurityGroups");
+ for (String sg : lb.getSecurityGroups()) {
+ xml.elem("member", sg);
+ }
+ xml.end("SecurityGroups")
+ .elem("CreatedTime", lb.getCreatedTime() != null ? ISO_FMT.format(lb.getCreatedTime()) : null)
+ .elem("Scheme", lb.getScheme());
+ return xml.build();
+ }
+
+ private static String healthCheckXml(ClassicHealthCheck hc) {
+ return new XmlBuilder()
+ .start("HealthCheck")
+ .elem("Target", hc.getTarget())
+ .elem("Interval", String.valueOf(hc.getInterval()))
+ .elem("Timeout", String.valueOf(hc.getTimeout()))
+ .elem("UnhealthyThreshold", String.valueOf(hc.getUnhealthyThreshold()))
+ .elem("HealthyThreshold", String.valueOf(hc.getHealthyThreshold()))
+ .end("HealthCheck")
+ .build();
+ }
+
+ private static String attributesXml(ClassicLoadBalancerAttributes a) {
+ XmlBuilder xml = new XmlBuilder()
+ .start("LoadBalancerAttributes")
+ .start("CrossZoneLoadBalancing")
+ .elem("Enabled", a.isCrossZoneLoadBalancingEnabled())
+ .end("CrossZoneLoadBalancing")
+ .start("AccessLog")
+ .elem("Enabled", a.isAccessLogEnabled())
+ .elem("S3BucketName", a.getAccessLogS3BucketName())
+ .elem("S3BucketPrefix", a.getAccessLogS3BucketPrefix())
+ .elem("EmitInterval", a.getAccessLogEmitInterval() != null
+ ? String.valueOf(a.getAccessLogEmitInterval()) : null)
+ .end("AccessLog")
+ .start("ConnectionDraining")
+ .elem("Enabled", a.isConnectionDrainingEnabled())
+ .elem("Timeout", a.getConnectionDrainingTimeout() != null
+ ? String.valueOf(a.getConnectionDrainingTimeout()) : null)
+ .end("ConnectionDraining")
+ .start("ConnectionSettings")
+ .elem("IdleTimeout", a.getIdleTimeout() != null
+ ? String.valueOf(a.getIdleTimeout()) : null)
+ .end("ConnectionSettings")
+ .start("AdditionalAttributes");
+ for (Map.Entry e : a.getAdditionalAttributes().entrySet()) {
+ xml.start("member").elem("Key", e.getKey()).elem("Value", e.getValue()).end("member");
+ }
+ xml.end("AdditionalAttributes").end("LoadBalancerAttributes");
+ return xml.build();
+ }
+
+ private static String instanceListResponse(String action, List instanceIds) {
+ XmlBuilder xml = new XmlBuilder()
+ .start(action + "Response", AwsNamespaces.ELB_CLASSIC)
+ .start(action + "Result")
+ .start("Instances");
+ for (String id : instanceIds) {
+ xml.start("member").elem("InstanceId", id).end("member");
+ }
+ xml.end("Instances")
+ .end(action + "Result")
+ .raw(AwsQueryResponse.responseMetadata())
+ .end(action + "Response");
+ return xml.build();
+ }
+
+ private static String stringListResponse(String action, String listElement, List values) {
+ XmlBuilder xml = new XmlBuilder()
+ .start(action + "Response", AwsNamespaces.ELB_CLASSIC)
+ .start(action + "Result")
+ .start(listElement);
+ for (String value : values) {
+ xml.elem("member", value);
+ }
+ xml.end(listElement)
+ .end(action + "Result")
+ .raw(AwsQueryResponse.responseMetadata())
+ .end(action + "Response");
+ return xml.build();
+ }
+
+ // ── Parsing helpers ───────────────────────────────────────────────────────
+
+ private static String requireName(MultivaluedMap p) {
+ String name = p.getFirst("LoadBalancerName");
+ if (name == null) {
+ throw new AwsException("ValidationError",
+ "LoadBalancerName is required for load balancer.", 400);
+ }
+ return name;
+ }
+
+ private static List memberList(MultivaluedMap p, String prefix) {
+ List result = new ArrayList<>();
+ int i = 1;
+ while (true) {
+ String value = p.getFirst(prefix + ".member." + i);
+ if (value == null) break;
+ result.add(value);
+ i++;
+ }
+ return result;
+ }
+
+ private static List parseInstanceIds(MultivaluedMap p) {
+ List result = new ArrayList<>();
+ int i = 1;
+ while (true) {
+ String id = p.getFirst("Instances.member." + i + ".InstanceId");
+ if (id == null) break;
+ result.add(id);
+ i++;
+ }
+ return result;
+ }
+
+ private static List parseListeners(MultivaluedMap p, String prefix) {
+ List result = new ArrayList<>();
+ int i = 1;
+ while (true) {
+ String base = prefix + ".member." + i + ".";
+ String protocol = p.getFirst(base + "Protocol");
+ String lbPort = p.getFirst(base + "LoadBalancerPort");
+ if (protocol == null && lbPort == null) break;
+ ClassicListener listener = new ClassicListener();
+ listener.setProtocol(protocol);
+ listener.setLoadBalancerPort(intOrNull(lbPort));
+ listener.setInstanceProtocol(p.getFirst(base + "InstanceProtocol"));
+ listener.setInstancePort(intOrNull(p.getFirst(base + "InstancePort")));
+ listener.setSslCertificateId(p.getFirst(base + "SSLCertificateId"));
+ result.add(listener);
+ i++;
+ }
+ return result;
+ }
+
+ private static Map parseTags(MultivaluedMap p) {
+ Map tags = new LinkedHashMap<>();
+ int i = 1;
+ while (true) {
+ String key = p.getFirst("Tags.member." + i + ".Key");
+ if (key == null) break;
+ String value = p.getFirst("Tags.member." + i + ".Value");
+ tags.put(key, value != null ? value : "");
+ i++;
+ }
+ return tags;
+ }
+
+ private static Integer intOrNull(String s) {
+ if (s == null || s.isEmpty()) return null;
+ try {
+ return Integer.valueOf(s);
+ } catch (NumberFormatException e) {
+ throw new AwsException("ValidationError", "'" + s + "' is not a valid integer.", 400);
+ }
+ }
+
+ private static Boolean boolOrNull(String s) {
+ if (s == null || s.isEmpty()) return null;
+ return Boolean.valueOf(s);
+ }
+
+ private static Response ok(String xml) {
+ return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
+ }
+
+ private static Response emptyResult(String action) {
+ return ok(new XmlBuilder()
+ .start(action + "Response", AwsNamespaces.ELB_CLASSIC)
+ .start(action + "Result").end(action + "Result")
+ .raw(AwsQueryResponse.responseMetadata())
+ .end(action + "Response")
+ .build());
+ }
+
+ private static Response xmlError(String code, String message, int status) {
+ String xml = new XmlBuilder()
+ .start("ErrorResponse", AwsNamespaces.ELB_CLASSIC)
+ .start("Error")
+ .elem("Type", "Sender")
+ .elem("Code", code)
+ .elem("Message", message)
+ .end("Error")
+ .raw(AwsQueryResponse.responseMetadata())
+ .end("ErrorResponse")
+ .build();
+ return Response.status(status).entity(xml).type(MediaType.APPLICATION_XML).build();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicService.java b/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicService.java
new file mode 100644
index 0000000000..40dac4d04c
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicService.java
@@ -0,0 +1,532 @@
+package io.github.hectorvent.floci.services.elb;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
+import io.github.hectorvent.floci.core.storage.StorageBackedMap;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.ec2.Ec2Service;
+import io.github.hectorvent.floci.services.ec2.model.Subnet;
+import io.github.hectorvent.floci.services.elb.model.ClassicHealthCheck;
+import io.github.hectorvent.floci.services.elb.model.ClassicListener;
+import io.github.hectorvent.floci.services.elb.model.ClassicLoadBalancer;
+import jakarta.annotation.PostConstruct;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.security.SecureRandom;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.stream.Collectors;
+
+/**
+ * State and behaviour for Classic (2012-06-01) Elastic Load Balancing.
+ *
+ * Kept apart from {@code ElbV2Service} on purpose. The two APIs share an endpoint host and a
+ * credential scope but not a data model: a Classic load balancer is keyed by name and has no ARN,
+ * carries its listeners inline rather than through listener and target-group resources, and holds
+ * one structured attribute record instead of a key/value list. Answering a Classic request from
+ * the v2 store is exactly the defect this class exists to remove.
+ *
+ *
Scope is deliberately the operations the AWS provider drives for {@code aws_elb} and for an
+ * Auto Scaling group attached to one. Stickiness and backend-server policies are not implemented;
+ * {@code ElbClassicQueryHandler} answers those with {@code UnsupportedOperation} rather than
+ * inventing a result.
+ */
+@ApplicationScoped
+public class ElbClassicService {
+
+ /** The hosted zone ID AWS reports for Classic load balancers; fixed per region on AWS too. */
+ private static final String CANONICAL_HOSTED_ZONE_ID = "Z35SXDOTRQ7X7K";
+
+ private static final SecureRandom RANDOM = new SecureRandom();
+
+ private final Ec2Service ec2Service;
+ private final ElbClassicHealthChecker healthChecker;
+ private final StorageFactory storageFactory;
+ private final EmulatorConfig config;
+
+ // region → load balancer name → record
+ private Map> loadBalancers = new ConcurrentHashMap<>();
+
+ @Inject
+ public ElbClassicService(Ec2Service ec2Service,
+ ElbClassicHealthChecker healthChecker,
+ StorageFactory storageFactory,
+ EmulatorConfig config) {
+ this.ec2Service = ec2Service;
+ this.healthChecker = healthChecker;
+ this.storageFactory = storageFactory;
+ this.config = config;
+ }
+
+ @PostConstruct
+ void initializeStorage() {
+ if (storageFactory == null) {
+ return;
+ }
+ this.loadBalancers = new StorageBackedMap<>(storageFactory.create("elb", "elb-load-balancers.json",
+ new TypeReference