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>>() {})); + for (Map.Entry> entry + : new ArrayList<>(loadBalancers.entrySet())) { + if (!(entry.getValue() instanceof ConcurrentHashMap)) { + loadBalancers.put(entry.getKey(), new ConcurrentHashMap<>(entry.getValue())); + } + } + } + + /** + * Restarts health checking for load balancers restored from disk. Called from + * {@code EmulatorLifecycle} once the bean is constructed, like {@code ElbV2Service} does — + * nothing reachable from {@link #initializeStorage()} may touch an injected collaborator. + */ + public void restorePersistedRuntime() { + for (Map regionLbs : loadBalancers.values()) { + for (ClassicLoadBalancer lb : regionLbs.values()) { + healthChecker.startMonitoring(lb); + healthChecker.registerInstances(lb, lb.getInstanceIds()); + } + } + } + + // ── Load balancers ──────────────────────────────────────────────────────── + + public ClassicLoadBalancer createLoadBalancer(String region, String name, + List listeners, + List availabilityZones, + List subnets, + List securityGroups, + String scheme, + Map tags) { + validateName(name); + if (listeners == null || listeners.isEmpty()) { + // Listeners is a required member of CreateAccessPointInput, and unlike LoadBalancerName + // the model gives its member shape required fields — an empty list cannot be honoured. + throw new AwsException("ValidationError", + "At least one listener must be specified.", 400); + } + for (ClassicListener listener : listeners) { + validateListener(listener); + } + + Map regionLbs = + loadBalancers.computeIfAbsent(region, k -> new ConcurrentHashMap<>()); + if (regionLbs.containsKey(name)) { + throw new AwsException("DuplicateLoadBalancerName", + "Load balancer named " + name + " already exists and is not compatible with the " + + "requested configuration.", 400); + } + + String id = randomHex(); + String dnsName = name + "-" + id + ".elb." + dnsSuffix(); + + ClassicLoadBalancer lb = new ClassicLoadBalancer(); + lb.setLoadBalancerName(name); + lb.setRegion(region); + lb.setDnsName(dnsName); + lb.setCanonicalHostedZoneName(dnsName); + lb.setCanonicalHostedZoneNameId(CANONICAL_HOSTED_ZONE_ID); + lb.setScheme(scheme != null && !scheme.isBlank() ? scheme : "internet-facing"); + lb.setCreatedTime(Instant.now()); + lb.setListeners(new ArrayList<>(listeners)); + lb.setSecurityGroups(securityGroups != null ? new ArrayList<>(securityGroups) : new ArrayList<>()); + lb.setHealthCheck(ClassicHealthCheck.defaults()); + if (tags != null && !tags.isEmpty()) { + lb.setTags(new LinkedHashMap<>(tags)); + } + + if (subnets != null && !subnets.isEmpty()) { + lb.setSubnets(new ArrayList<>(subnets)); + Map byId = resolveSubnets(region, subnets); + lb.setVpcId(singleVpcId(byId.values())); + lb.setAvailabilityZones(byId.values().stream() + .map(Subnet::getAvailabilityZone) + .distinct() + .collect(Collectors.toCollection(ArrayList::new))); + } else if (availabilityZones != null) { + lb.setAvailabilityZones(new ArrayList<>(availabilityZones)); + } + + regionLbs.put(name, lb); + loadBalancers.put(region, regionLbs); + healthChecker.startMonitoring(lb); + return lb; + } + + public List describeLoadBalancers(String region, List names) { + Map regionLbs = loadBalancers.getOrDefault(region, Map.of()); + if (names == null || names.isEmpty()) { + return new ArrayList<>(regionLbs.values()); + } + List result = new ArrayList<>(); + for (String name : names) { + ClassicLoadBalancer lb = regionLbs.get(name); + if (lb == null) { + throw new AwsException("LoadBalancerNotFound", + "There is no ACTIVE Load Balancer named '" + name + "'", 400); + } + result.add(lb); + } + return result; + } + + /** Deletes a load balancer. Deleting one that does not exist succeeds, as it does on AWS. */ + public void deleteLoadBalancer(String region, String name) { + Map regionLbs = loadBalancers.get(region); + if (regionLbs == null) { + return; + } + if (regionLbs.remove(name) != null) { + healthChecker.stopMonitoring(region, name); + loadBalancers.put(region, regionLbs); + } + } + + public boolean hasLoadBalancer(String region, String name) { + return loadBalancers.getOrDefault(region, Map.of()).containsKey(name); + } + + public ClassicLoadBalancer requireLoadBalancer(String region, String name) { + ClassicLoadBalancer lb = loadBalancers.getOrDefault(region, Map.of()).get(name); + if (lb == null) { + throw new AwsException("LoadBalancerNotFound", + "There is no ACTIVE Load Balancer named '" + name + "'", 400); + } + return lb; + } + + // ── Listeners ───────────────────────────────────────────────────────────── + + public void createLoadBalancerListeners(String region, String name, List listeners) { + ClassicLoadBalancer lb = requireLoadBalancer(region, name); + for (ClassicListener listener : listeners) { + validateListener(listener); + } + for (ClassicListener listener : listeners) { + ClassicListener existing = lb.getListeners().stream() + .filter(l -> l.getLoadBalancerPort().equals(listener.getLoadBalancerPort())) + .findFirst() + .orElse(null); + if (existing != null) { + // AWS accepts a repeat of an identical listener and rejects a conflicting one. + if (!sameListener(existing, listener)) { + throw new AwsException("DuplicateListener", + "A listener already exists for " + name + " with LoadBalancerPort " + + listener.getLoadBalancerPort() + + ", but with a different InstancePort, Protocol, or " + + "SSLCertificateId", 400); + } + continue; + } + lb.getListeners().add(listener); + } + persist(region); + } + + public void deleteLoadBalancerListeners(String region, String name, List loadBalancerPorts) { + ClassicLoadBalancer lb = requireLoadBalancer(region, name); + lb.getListeners().removeIf(l -> loadBalancerPorts.contains(l.getLoadBalancerPort())); + persist(region); + } + + // ── Health ──────────────────────────────────────────────────────────────── + + public ClassicHealthCheck configureHealthCheck(String region, String name, ClassicHealthCheck healthCheck) { + ClassicLoadBalancer lb = requireLoadBalancer(region, name); + validateHealthCheck(healthCheck); + lb.setHealthCheck(healthCheck); + persist(region); + healthChecker.healthCheckChanged(lb); + return healthCheck; + } + + public List registerInstances(String region, String name, List instanceIds) { + ClassicLoadBalancer lb = requireLoadBalancer(region, name); + for (String id : instanceIds) { + if (!lb.getInstanceIds().contains(id)) { + lb.getInstanceIds().add(id); + } + } + persist(region); + healthChecker.registerInstances(lb, instanceIds); + return List.copyOf(lb.getInstanceIds()); + } + + public List deregisterInstances(String region, String name, List instanceIds) { + ClassicLoadBalancer lb = requireLoadBalancer(region, name); + lb.getInstanceIds().removeAll(instanceIds); + persist(region); + healthChecker.deregisterInstances(region, name, instanceIds); + return List.copyOf(lb.getInstanceIds()); + } + + /** The health of each requested instance, or of every registered instance when none is named. */ + public Map describeInstanceHealth( + String region, String name, List instanceIds) { + ClassicLoadBalancer lb = requireLoadBalancer(region, name); + List wanted = instanceIds == null || instanceIds.isEmpty() + ? lb.getInstanceIds() + : instanceIds; + Map result = new LinkedHashMap<>(); + for (String id : wanted) { + if (!lb.getInstanceIds().contains(id)) { + throw new AwsException("InvalidInstance", + "Could not find EC2 instance " + id + ".", 400); + } + result.put(id, healthChecker.getHealth(region, name, id)); + } + return result; + } + + // ── Attributes, zones, subnets, security groups ─────────────────────────── + + public ClassicLoadBalancer modifyLoadBalancerAttributes(String region, String name, + AttributeUpdate update) { + ClassicLoadBalancer lb = requireLoadBalancer(region, name); + update.applyTo(lb.getAttributes()); + persist(region); + return lb; + } + + /** The subset of {@code LoadBalancerAttributes} a request actually carried; unset stays unset. */ + public record AttributeUpdate(Boolean crossZoneEnabled, + Boolean accessLogEnabled, + String accessLogS3BucketName, + String accessLogS3BucketPrefix, + Integer accessLogEmitInterval, + Boolean connectionDrainingEnabled, + Integer connectionDrainingTimeout, + Integer idleTimeout, + Map additionalAttributes) { + + void applyTo(io.github.hectorvent.floci.services.elb.model.ClassicLoadBalancerAttributes attrs) { + if (crossZoneEnabled != null) attrs.setCrossZoneLoadBalancingEnabled(crossZoneEnabled); + if (accessLogEnabled != null) attrs.setAccessLogEnabled(accessLogEnabled); + if (accessLogS3BucketName != null) attrs.setAccessLogS3BucketName(accessLogS3BucketName); + if (accessLogS3BucketPrefix != null) attrs.setAccessLogS3BucketPrefix(accessLogS3BucketPrefix); + if (accessLogEmitInterval != null) attrs.setAccessLogEmitInterval(accessLogEmitInterval); + if (connectionDrainingEnabled != null) attrs.setConnectionDrainingEnabled(connectionDrainingEnabled); + if (connectionDrainingTimeout != null) attrs.setConnectionDrainingTimeout(connectionDrainingTimeout); + if (idleTimeout != null) attrs.setIdleTimeout(idleTimeout); + if (additionalAttributes != null && !additionalAttributes.isEmpty()) { + attrs.getAdditionalAttributes().putAll(additionalAttributes); + } + } + } + + public List applySecurityGroups(String region, String name, List securityGroups) { + ClassicLoadBalancer lb = requireLoadBalancer(region, name); + lb.setSecurityGroups(new ArrayList<>(securityGroups)); + persist(region); + return List.copyOf(lb.getSecurityGroups()); + } + + public List attachToSubnets(String region, String name, List subnets) { + ClassicLoadBalancer lb = requireLoadBalancer(region, name); + resolveSubnets(region, subnets); + for (String subnet : subnets) { + if (!lb.getSubnets().contains(subnet)) { + lb.getSubnets().add(subnet); + } + } + refreshZonesFromSubnets(region, lb); + persist(region); + return List.copyOf(lb.getSubnets()); + } + + public List detachFromSubnets(String region, String name, List subnets) { + ClassicLoadBalancer lb = requireLoadBalancer(region, name); + lb.getSubnets().removeAll(subnets); + refreshZonesFromSubnets(region, lb); + persist(region); + return List.copyOf(lb.getSubnets()); + } + + public List enableAvailabilityZones(String region, String name, List zones) { + ClassicLoadBalancer lb = requireLoadBalancer(region, name); + for (String zone : zones) { + if (!lb.getAvailabilityZones().contains(zone)) { + lb.getAvailabilityZones().add(zone); + } + } + persist(region); + return List.copyOf(lb.getAvailabilityZones()); + } + + public List disableAvailabilityZones(String region, String name, List zones) { + ClassicLoadBalancer lb = requireLoadBalancer(region, name); + lb.getAvailabilityZones().removeAll(zones); + persist(region); + return List.copyOf(lb.getAvailabilityZones()); + } + + // ── Tags ────────────────────────────────────────────────────────────────── + + public void addTags(String region, List names, Map tags) { + for (String name : names) { + requireLoadBalancer(region, name).getTags().putAll(tags); + } + persist(region); + } + + public void removeTags(String region, List names, Collection tagKeys) { + for (String name : names) { + requireLoadBalancer(region, name).getTags().keySet().removeAll(tagKeys); + } + persist(region); + } + + public Map> describeTags(String region, List names) { + Map> result = new LinkedHashMap<>(); + for (String name : names) { + result.put(name, Map.copyOf(requireLoadBalancer(region, name).getTags())); + } + return result; + } + + // ── Internals ───────────────────────────────────────────────────────────── + + private void persist(String region) { + Map regionLbs = loadBalancers.get(region); + if (regionLbs != null) { + loadBalancers.put(region, regionLbs); + } + } + + private void refreshZonesFromSubnets(String region, ClassicLoadBalancer lb) { + if (lb.getSubnets().isEmpty()) { + lb.setAvailabilityZones(new ArrayList<>()); + return; + } + Map byId = resolveSubnets(region, lb.getSubnets()); + lb.setVpcId(singleVpcId(byId.values())); + lb.setAvailabilityZones(byId.values().stream() + .map(Subnet::getAvailabilityZone) + .distinct() + .collect(Collectors.toCollection(ArrayList::new))); + } + + private Map resolveSubnets(String region, List subnetIds) { + Map byId = ec2Service.describeSubnets(region, subnetIds, Map.of()).stream() + .collect(Collectors.toMap(Subnet::getSubnetId, s -> s, (l, r) -> l, + LinkedHashMap::new)); + for (String subnetId : subnetIds) { + if (!byId.containsKey(subnetId)) { + throw new AwsException("SubnetNotFound", + "The subnet ID '" + subnetId + "' does not exist", 400); + } + } + return byId; + } + + private static String singleVpcId(Collection subnets) { + Set vpcIds = subnets.stream() + .map(Subnet::getVpcId) + .collect(Collectors.toCollection(LinkedHashSet::new)); + if (vpcIds.size() > 1) { + // CreateLoadBalancer's own Errors table documents InvalidConfigurationRequest at 409, + // not 400: a client that retries on 409 but fails hard on 400 needs the real status. + throw new AwsException("InvalidConfigurationRequest", + "All subnets must belong to the same VPC.", 409); + } + return vpcIds.isEmpty() ? null : vpcIds.iterator().next(); + } + + private String dnsSuffix() { + if (config == null) { + return EmbeddedDnsServer.DEFAULT_SUFFIX; + } + return config.hostname().orElse(EmbeddedDnsServer.DEFAULT_SUFFIX); + } + + private static String randomHex() { + byte[] bytes = new byte[5]; + RANDOM.nextBytes(bytes); + StringBuilder sb = new StringBuilder(); + for (byte b : bytes) { + sb.append(String.format("%02x", b)); + } + return sb.toString(); + } + + /** + * Rejects a load balancer name AWS would reject. + * + *

{@code LoadBalancerName} is a required member, and required means present — the model + * declares no {@code min} on {@code AccessPointName}, so an empty string is a missing name + * only in the sense that the member was not supplied. The 32-character ceiling and the + * alphanumeric-and-hyphen rule are AWS's documented constraints for Classic names. + */ + private static void validateName(String name) { + if (name == null) { + throw new AwsException("ValidationError", + "LoadBalancerName is required for load balancer.", 400); + } + if (name.isEmpty() || name.length() > 32) { + throw new AwsException("ValidationError", + "LoadBalancerName must be between 1 and 32 characters long.", 400); + } + if (!name.matches("[a-zA-Z0-9-]+")) { + throw new AwsException("ValidationError", + "LoadBalancerName '" + name + "' contains invalid characters. Use alphanumeric " + + "characters and hyphens.", 400); + } + if (name.startsWith("-") || name.endsWith("-")) { + throw new AwsException("ValidationError", + "LoadBalancerName '" + name + "' cannot start or end with a hyphen.", 400); + } + } + + private static void validateListener(ClassicListener listener) { + if (listener.getProtocol() == null || listener.getLoadBalancerPort() == null + || listener.getInstancePort() == null) { + throw new AwsException("ValidationError", + "Protocol, LoadBalancerPort and InstancePort are required for each listener.", 400); + } + if (listener.getInstancePort() < 1 || listener.getInstancePort() > 65535) { + throw new AwsException("ValidationError", + "InstancePort must be between 1 and 65535.", 400); + } + } + + /** + * Rejects a health check outside the ranges the model declares — {@code Interval} 5–300, + * {@code Timeout} 2–60, both thresholds 2–10 — and one with no {@code Target}, which the model + * marks required. + */ + private static void validateHealthCheck(ClassicHealthCheck hc) { + if (hc.getTarget() == null || hc.getTarget().isBlank()) { + throw new AwsException("ValidationError", + "HealthCheck.Target is required.", 400); + } + requireRange("HealthCheck.Interval", hc.getInterval(), 5, 300); + requireRange("HealthCheck.Timeout", hc.getTimeout(), 2, 60); + requireRange("HealthCheck.UnhealthyThreshold", hc.getUnhealthyThreshold(), 2, 10); + requireRange("HealthCheck.HealthyThreshold", hc.getHealthyThreshold(), 2, 10); + } + + private static void requireRange(String member, Integer value, int min, int max) { + if (value == null) { + throw new AwsException("ValidationError", member + " is required.", 400); + } + if (value < min || value > max) { + throw new AwsException("ValidationError", + member + " must be between " + min + " and " + max + ".", 400); + } + } + + private static boolean sameListener(ClassicListener a, ClassicListener b) { + return java.util.Objects.equals(a.getProtocol(), b.getProtocol()) + && java.util.Objects.equals(a.getInstancePort(), b.getInstancePort()) + && java.util.Objects.equals(a.getInstanceProtocol(), b.getInstanceProtocol()) + && java.util.Objects.equals(a.getSslCertificateId(), b.getSslCertificateId()); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/elb/model/ClassicHealthCheck.java b/src/main/java/io/github/hectorvent/floci/services/elb/model/ClassicHealthCheck.java new file mode 100644 index 0000000000..ac03e72e41 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/elb/model/ClassicHealthCheck.java @@ -0,0 +1,50 @@ +package io.github.hectorvent.floci.services.elb.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * The {@code HealthCheck} shape of the Classic (2012-06-01) load balancing API. + * + *

Every member is required by the model, so a stored health check is always complete. The + * defaults applied on {@code CreateLoadBalancer} are AWS's own documented defaults, which is + * what a Classic load balancer reports before {@code ConfigureHealthCheck} is ever called. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class ClassicHealthCheck { + + /** AWS's default health check for a newly created Classic load balancer. */ + public static ClassicHealthCheck defaults() { + ClassicHealthCheck hc = new ClassicHealthCheck(); + hc.setTarget("TCP:80"); + hc.setInterval(30); + hc.setTimeout(5); + hc.setUnhealthyThreshold(2); + hc.setHealthyThreshold(10); + return hc; + } + + private String target; + private Integer interval; + private Integer timeout; + private Integer unhealthyThreshold; + private Integer healthyThreshold; + + public ClassicHealthCheck() {} + + public String getTarget() { return target; } + public void setTarget(String target) { this.target = target; } + + public Integer getInterval() { return interval; } + public void setInterval(Integer interval) { this.interval = interval; } + + public Integer getTimeout() { return timeout; } + public void setTimeout(Integer timeout) { this.timeout = timeout; } + + public Integer getUnhealthyThreshold() { return unhealthyThreshold; } + public void setUnhealthyThreshold(Integer unhealthyThreshold) { this.unhealthyThreshold = unhealthyThreshold; } + + public Integer getHealthyThreshold() { return healthyThreshold; } + public void setHealthyThreshold(Integer healthyThreshold) { this.healthyThreshold = healthyThreshold; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/elb/model/ClassicListener.java b/src/main/java/io/github/hectorvent/floci/services/elb/model/ClassicListener.java new file mode 100644 index 0000000000..bdacb069c7 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/elb/model/ClassicListener.java @@ -0,0 +1,39 @@ +package io.github.hectorvent.floci.services.elb.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * A Classic (2012-06-01) load balancer listener. + * + *

Mirrors the {@code Listener} shape of the {@code elasticloadbalancing} 2012-06-01 model: + * {@code Protocol}, {@code LoadBalancerPort} and {@code InstancePort} are required members, + * {@code InstanceProtocol} and {@code SSLCertificateId} are optional. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class ClassicListener { + + private String protocol; + private Integer loadBalancerPort; + private String instanceProtocol; + private Integer instancePort; + private String sslCertificateId; + + public ClassicListener() {} + + public String getProtocol() { return protocol; } + public void setProtocol(String protocol) { this.protocol = protocol; } + + public Integer getLoadBalancerPort() { return loadBalancerPort; } + public void setLoadBalancerPort(Integer loadBalancerPort) { this.loadBalancerPort = loadBalancerPort; } + + public String getInstanceProtocol() { return instanceProtocol; } + public void setInstanceProtocol(String instanceProtocol) { this.instanceProtocol = instanceProtocol; } + + public Integer getInstancePort() { return instancePort; } + public void setInstancePort(Integer instancePort) { this.instancePort = instancePort; } + + public String getSslCertificateId() { return sslCertificateId; } + public void setSslCertificateId(String sslCertificateId) { this.sslCertificateId = sslCertificateId; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/elb/model/ClassicLoadBalancer.java b/src/main/java/io/github/hectorvent/floci/services/elb/model/ClassicLoadBalancer.java new file mode 100644 index 0000000000..fecb5e5e6b --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/elb/model/ClassicLoadBalancer.java @@ -0,0 +1,100 @@ +package io.github.hectorvent.floci.services.elb.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +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; + +/** + * A Classic (2012-06-01) load balancer — the {@code LoadBalancerDescription} shape. + * + *

Deliberately not the ELBv2 {@code LoadBalancer}: a Classic load balancer has no ARN, no + * target groups, and is addressed by name for the whole life of the record. Sharing the v2 model + * is what produced the defect this type exists to fix. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class ClassicLoadBalancer { + + private String loadBalancerName; + private String dnsName; + private String canonicalHostedZoneName; + private String canonicalHostedZoneNameId; + private String scheme; + private String vpcId; + private String region; + private Instant createdTime; + + private List listeners = new ArrayList<>(); + private List availabilityZones = new ArrayList<>(); + private List subnets = new ArrayList<>(); + private List securityGroups = new ArrayList<>(); + private List instanceIds = new ArrayList<>(); + + private String sourceSecurityGroupOwnerAlias; + private String sourceSecurityGroupName; + + private ClassicHealthCheck healthCheck = ClassicHealthCheck.defaults(); + private ClassicLoadBalancerAttributes attributes = new ClassicLoadBalancerAttributes(); + private Map tags = new LinkedHashMap<>(); + + public ClassicLoadBalancer() {} + + public String getLoadBalancerName() { return loadBalancerName; } + public void setLoadBalancerName(String v) { this.loadBalancerName = v; } + + public String getDnsName() { return dnsName; } + public void setDnsName(String v) { this.dnsName = v; } + + public String getCanonicalHostedZoneName() { return canonicalHostedZoneName; } + public void setCanonicalHostedZoneName(String v) { this.canonicalHostedZoneName = v; } + + public String getCanonicalHostedZoneNameId() { return canonicalHostedZoneNameId; } + public void setCanonicalHostedZoneNameId(String v) { this.canonicalHostedZoneNameId = v; } + + public String getScheme() { return scheme; } + public void setScheme(String v) { this.scheme = v; } + + public String getVpcId() { return vpcId; } + public void setVpcId(String v) { this.vpcId = v; } + + public String getRegion() { return region; } + public void setRegion(String v) { this.region = v; } + + public Instant getCreatedTime() { return createdTime; } + public void setCreatedTime(Instant v) { this.createdTime = v; } + + public List getListeners() { return listeners; } + public void setListeners(List v) { this.listeners = v; } + + public List getAvailabilityZones() { return availabilityZones; } + public void setAvailabilityZones(List v) { this.availabilityZones = v; } + + public List getSubnets() { return subnets; } + public void setSubnets(List v) { this.subnets = v; } + + public List getSecurityGroups() { return securityGroups; } + public void setSecurityGroups(List v) { this.securityGroups = v; } + + public List getInstanceIds() { return instanceIds; } + public void setInstanceIds(List v) { this.instanceIds = v; } + + public String getSourceSecurityGroupOwnerAlias() { return sourceSecurityGroupOwnerAlias; } + public void setSourceSecurityGroupOwnerAlias(String v) { this.sourceSecurityGroupOwnerAlias = v; } + + public String getSourceSecurityGroupName() { return sourceSecurityGroupName; } + public void setSourceSecurityGroupName(String v) { this.sourceSecurityGroupName = v; } + + public ClassicHealthCheck getHealthCheck() { return healthCheck; } + public void setHealthCheck(ClassicHealthCheck v) { this.healthCheck = v; } + + public ClassicLoadBalancerAttributes getAttributes() { return attributes; } + public void setAttributes(ClassicLoadBalancerAttributes v) { this.attributes = v; } + + public Map getTags() { return tags; } + public void setTags(Map v) { this.tags = v; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/elb/model/ClassicLoadBalancerAttributes.java b/src/main/java/io/github/hectorvent/floci/services/elb/model/ClassicLoadBalancerAttributes.java new file mode 100644 index 0000000000..2c44599cbb --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/elb/model/ClassicLoadBalancerAttributes.java @@ -0,0 +1,66 @@ +package io.github.hectorvent.floci.services.elb.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * The {@code LoadBalancerAttributes} shape of the Classic (2012-06-01) load balancing API. + * + *

Classic attributes are a fixed structure rather than the ELBv2 key/value list, so they are + * modelled as fields. Only the four documented sub-structures plus {@code AdditionalAttributes} + * exist; anything else a caller sends is carried in {@code additionalAttributes} unchanged. + * + *

The initial values are AWS's own defaults for a freshly created Classic load balancer: + * cross-zone off, access logging off, connection draining off with a 300 second timeout, and a + * 60 second idle timeout. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class ClassicLoadBalancerAttributes { + + private boolean crossZoneLoadBalancingEnabled = false; + + private boolean accessLogEnabled = false; + private String accessLogS3BucketName; + private String accessLogS3BucketPrefix; + private Integer accessLogEmitInterval = 60; + + private boolean connectionDrainingEnabled = false; + private Integer connectionDrainingTimeout = 300; + + private Integer idleTimeout = 60; + + private Map additionalAttributes = new LinkedHashMap<>(); + + public ClassicLoadBalancerAttributes() {} + + public boolean isCrossZoneLoadBalancingEnabled() { return crossZoneLoadBalancingEnabled; } + public void setCrossZoneLoadBalancingEnabled(boolean v) { this.crossZoneLoadBalancingEnabled = v; } + + public boolean isAccessLogEnabled() { return accessLogEnabled; } + public void setAccessLogEnabled(boolean v) { this.accessLogEnabled = v; } + + public String getAccessLogS3BucketName() { return accessLogS3BucketName; } + public void setAccessLogS3BucketName(String v) { this.accessLogS3BucketName = v; } + + public String getAccessLogS3BucketPrefix() { return accessLogS3BucketPrefix; } + public void setAccessLogS3BucketPrefix(String v) { this.accessLogS3BucketPrefix = v; } + + public Integer getAccessLogEmitInterval() { return accessLogEmitInterval; } + public void setAccessLogEmitInterval(Integer v) { this.accessLogEmitInterval = v; } + + public boolean isConnectionDrainingEnabled() { return connectionDrainingEnabled; } + public void setConnectionDrainingEnabled(boolean v) { this.connectionDrainingEnabled = v; } + + public Integer getConnectionDrainingTimeout() { return connectionDrainingTimeout; } + public void setConnectionDrainingTimeout(Integer v) { this.connectionDrainingTimeout = v; } + + public Integer getIdleTimeout() { return idleTimeout; } + public void setIdleTimeout(Integer v) { this.idleTimeout = v; } + + public Map getAdditionalAttributes() { return additionalAttributes; } + public void setAdditionalAttributes(Map v) { this.additionalAttributes = v; } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 4ee259e915..bf234d13b3 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -67,6 +67,7 @@ quarkus: - --initialize-at-run-time=io.github.hectorvent.floci.services.cloudfront.CloudFrontService - --initialize-at-run-time=io.github.hectorvent.floci.services.emr.EmrService - --initialize-at-run-time=io.github.hectorvent.floci.services.elasticbeanstalk.ElasticBeanstalkService + - --initialize-at-run-time=io.github.hectorvent.floci.services.elb.ElbClassicService - --initialize-at-run-time=graphql.util.IdGenerator - --initialize-at-run-time=io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentials # snappy-java (Firehose Snappy/HADOOP_SNAPPY delivery) extracts and loads a @@ -488,6 +489,9 @@ floci: keep-running-on-shutdown: false dag-sync-interval-seconds: 30 install-requirements: true + elb: + enabled: true + mock: false elbv2: enabled: true mock: false diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java index 0590a5e18c..aa2c6c6de6 100644 --- a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java +++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java @@ -60,6 +60,7 @@ class EmulatorLifecycleTest { @Mock private EmulatorConfig.ServicesConfig servicesConfig; @Mock private EmulatorConfig.Ec2ServiceConfig ec2ServiceConfig; @Mock private EmulatorConfig.ElbV2ServiceConfig elbv2ServiceConfig; + @Mock private EmulatorConfig.ElbServiceConfig elbServiceConfig; @Mock private IamService iamService; @Mock private EmulatorConfig.ElastiCacheServiceConfig elastiCacheServiceConfig; @Mock private ElastiCacheService elastiCacheService; @@ -77,6 +78,7 @@ class EmulatorLifecycleTest { @Mock private io.github.hectorvent.floci.services.kinesisanalytics.container.FlinkContainerManager flinkContainerManager; @Mock private RdsService rdsService; @Mock private io.github.hectorvent.floci.services.elbv2.ElbV2Service elbV2Service; + @Mock private io.github.hectorvent.floci.services.elb.ElbClassicService elbClassicService; @Mock private InitializationHooksRunner initializationHooksRunner; @Mock private SqsEventSourcePoller sqsPoller; @Mock private KinesisEventSourcePoller kinesisPoller; @@ -102,6 +104,8 @@ class EmulatorLifecycleTest { Mockito.lenient().when(elbv2ServiceConfig.enabled()).thenReturn(false); Mockito.lenient().when(servicesConfig.elasticache()).thenReturn(elastiCacheServiceConfig); Mockito.lenient().when(elastiCacheServiceConfig.enabled()).thenReturn(false); + Mockito.lenient().when(servicesConfig.elb()).thenReturn(elbServiceConfig); + Mockito.lenient().when(elbServiceConfig.enabled()).thenReturn(false); Mockito.lenient().when(config.tls()).thenReturn(tlsConfig); Mockito.lenient().when(tlsConfig.enabled()).thenReturn(false); Mockito.lenient().when(config.port()).thenReturn(4566); @@ -113,7 +117,7 @@ class EmulatorLifecycleTest { elastiCacheProxyManager, rdsContainerManager, rdsProxyManager, memoryDbContainerManager, memoryDbProxyManager, docDbContainerManager, neptuneContainerManager, neptuneProxyManager, - rabbitMqManager, flinkContainerManager, rdsService, elbV2Service, + rabbitMqManager, flinkContainerManager, rdsService, elbV2Service, elbClassicService, initializationHooksRunner, sqsPoller, kinesisPoller, dynamodbStreamsPoller, pipesService, ec2MetadataServer, ecrRegistryManager, flociUiManager, initLifecycleState, schemaCreationWorker, containerTeardowns, persistentPathValidator); diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java index b8cca1b6d1..71816bebc3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java @@ -11,6 +11,7 @@ import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate; import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData; import io.github.hectorvent.floci.services.ec2.model.Reservation; import io.github.hectorvent.floci.services.ec2.model.Tag; +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; @@ -386,7 +387,7 @@ class AutoScalingReconcilerTest { ElbV2Service elbV2Service = mock(ElbV2Service.class); SsmCommandService ssmCommandService = mock(SsmCommandService.class); AutoScalingReconciler reconciler = new AutoScalingReconciler( - asgService, ec2Service, elbV2Service, ssmCommandService); + asgService, ec2Service, elbV2Service, null, ssmCommandService); AutoScalingGroup asg = new AutoScalingGroup(); asg.setRegion("us-east-1"); asg.setAutoScalingGroupName("app-asg"); @@ -409,6 +410,29 @@ class AutoScalingReconcilerTest { verify(ssmCommandService).failActiveInvocationsForInstances("us-east-1", Set.of("i-dead"), "Undeliverable"); } + @Test + void reconcileDeregistersStaleInstanceFromClassicLoadBalancerBeforePruning() { + AutoScalingService asgService = mock(AutoScalingService.class); + Ec2Service ec2Service = mock(Ec2Service.class); + ElbV2Service elbV2Service = mock(ElbV2Service.class); + ElbClassicService elbClassicService = mock(ElbClassicService.class); + AutoScalingReconciler reconciler = new AutoScalingReconciler( + asgService, ec2Service, elbV2Service, elbClassicService, null); + AutoScalingGroup asg = new AutoScalingGroup(); + asg.setRegion("us-east-1"); + asg.setAutoScalingGroupName("app-asg"); + asg.setDesiredCapacity(0); + asg.setLoadBalancerNames(List.of("classic-lb")); + asg.getInstances().add(instance("i-dead", "InService")); + when(ec2Service.isInstanceContainerRunning("i-dead")).thenReturn(false); + + reconciler.reconcile(asg); + + assertEquals(0, asg.getInstances().size()); + verify(elbClassicService).deregisterInstances( + eq(asg.getRegion()), eq("classic-lb"), eq(List.of("i-dead"))); + } + @Test void reconcilePromotesPendingAsgInstanceWhenEc2InstanceIsRunning() { AutoScalingService asgService = mock(AutoScalingService.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/elb/ElbClassicHealthCheckTargetTest.java b/src/test/java/io/github/hectorvent/floci/services/elb/ElbClassicHealthCheckTargetTest.java new file mode 100644 index 0000000000..aac9d5f16a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/elb/ElbClassicHealthCheckTargetTest.java @@ -0,0 +1,50 @@ +package io.github.hectorvent.floci.services.elb; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * The Classic {@code HealthCheck.Target} grammar — one string carrying protocol, port and, for the + * HTTP protocols, a path. ELBv2 splits these across three members, which is why this parsing + * exists at all. + */ +class ElbClassicHealthCheckTargetTest { + + @Test + void httpTargetCarriesItsPath() { + ElbClassicHealthChecker.Target target = ElbClassicHealthChecker.Target.parse("HTTP:8080/health"); + assertEquals("http", target.scheme()); + assertEquals(8080, target.port()); + assertEquals("/health", target.path()); + } + + @Test + void httpTargetWithNoPathDefaultsToRoot() { + ElbClassicHealthChecker.Target target = ElbClassicHealthChecker.Target.parse("HTTP:80"); + assertEquals("/", target.path()); + } + + @Test + void tcpTargetHasNoPathAndSoIsProbedByConnection() { + ElbClassicHealthChecker.Target target = ElbClassicHealthChecker.Target.parse("TCP:8080"); + assertNull(target.path()); + assertNull(target.scheme()); + assertEquals(8080, target.port()); + } + + @Test + void sslTargetIsAConnectionProbeToo() { + assertNull(ElbClassicHealthChecker.Target.parse("SSL:443").path()); + } + + @Test + void malformedTargetsAreRejectedRatherThanGuessed() { + assertNull(ElbClassicHealthChecker.Target.parse(null)); + assertNull(ElbClassicHealthChecker.Target.parse("")); + assertNull(ElbClassicHealthChecker.Target.parse("HTTP")); + assertNull(ElbClassicHealthChecker.Target.parse("HTTP:notaport/")); + assertNull(ElbClassicHealthChecker.Target.parse("GOPHER:70/")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/elb/ElbClassicIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elb/ElbClassicIntegrationTest.java new file mode 100644 index 0000000000..89719c6cd6 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/elb/ElbClassicIntegrationTest.java @@ -0,0 +1,571 @@ +package io.github.hectorvent.floci.services.elb; + +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Classic (2012-06-01) Elastic Load Balancing over the Query protocol. + * + *

Classic ELB and ELBv2 share one endpoint host and one credential scope, so these tests also + * pin the routing: a request declaring {@code Version=2012-06-01} must be answered by the Classic + * implementation, in the 2012-06-01 namespace, and one declaring {@code Version=2015-12-01} must + * still reach ELBv2. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ElbClassicIntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260427/us-east-1/elasticloadbalancing/aws4_request"; + private static final String V1 = "2012-06-01"; + private static final String V2 = "2015-12-01"; + private static final String CLASSIC_XMLNS = + "http://elasticloadbalancing.amazonaws.com/doc/2012-06-01/"; + private static final String V2_XMLNS = + "https://elasticloadbalancing.amazonaws.com/doc/2015-12-01/"; + + private static final String LB = "classic-elb-1"; + + private static String subnetA() { return Ec2Service.defaultSubnetId("us-east-1", "a"); } + + @Test + @Order(1) + void createLoadBalancerAnswersTheClassicApiNotTheV2One() { + String body = given() + .formParam("Action", "CreateLoadBalancer") + .formParam("Version", V1) + .formParam("LoadBalancerName", LB) + .formParam("Scheme", "internet-facing") + .formParam("Subnets.member.1", subnetA()) + .formParam("SecurityGroups.member.1", "sg-classic") + .formParam("Listeners.member.1.Protocol", "HTTP") + .formParam("Listeners.member.1.LoadBalancerPort", "80") + .formParam("Listeners.member.1.InstanceProtocol", "HTTP") + .formParam("Listeners.member.1.InstancePort", "8080") + .formParam("Tags.member.1.Key", "gw:example") + .formParam("Tags.member.1.Value", "with-elb") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .contentType("application/xml") + .body("CreateLoadBalancerResponse.CreateLoadBalancerResult.DNSName", + containsString(LB + "-")) + .extract().asString(); + + // The two defects this fixes: wrong namespace, and an ELBv2 object in a Classic reply. + assertTrue(body.contains("xmlns=\"" + CLASSIC_XMLNS + "\""), + "Classic response must declare the 2012-06-01 namespace: " + body); + assertFalse(body.contains(V2_XMLNS), + "Classic response must not be in the 2015-12-01 namespace: " + body); + assertFalse(body.contains("LoadBalancerArn"), + "Classic load balancers have no ARN: " + body); + assertFalse(body.contains(""), + "CreateLoadBalancerResult carries DNSName only, never a LoadBalancers list: " + body); + } + + @Test + @Order(2) + void loadBalancerNameIsAcceptedRatherThanRejectedAsMissing() { + // The reported symptom: 'Name is required for load balancer.' for a well-formed v1 request. + given() + .formParam("Action", "CreateLoadBalancer") + .formParam("Version", V1) + .formParam("LoadBalancerName", "classic-elb-name-ok") + .formParam("Listeners.member.1.Protocol", "TCP") + .formParam("Listeners.member.1.LoadBalancerPort", "443") + .formParam("Listeners.member.1.InstancePort", "443") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body("CreateLoadBalancerResponse.CreateLoadBalancerResult.DNSName", + containsString("classic-elb-name-ok-")); + + given() + .formParam("Action", "DeleteLoadBalancer") + .formParam("Version", V1) + .formParam("LoadBalancerName", "classic-elb-name-ok") + .header("Authorization", AUTH) + .when().post("/").then().statusCode(200); + } + + @Test + @Order(3) + void createRejectsARequestWithNoListeners() { + given() + .formParam("Action", "CreateLoadBalancer") + .formParam("Version", V1) + .formParam("LoadBalancerName", "classic-no-listeners") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + // Not "Name is required for load balancer." — that is the v2 handler's message, + // and seeing it here means a v1 request reached the wrong API again. + .body("ErrorResponse.Error.Message", containsString("listener")); + } + + @Test + @Order(4) + void duplicateNameIsRejected() { + given() + .formParam("Action", "CreateLoadBalancer") + .formParam("Version", V1) + .formParam("LoadBalancerName", LB) + .formParam("Listeners.member.1.Protocol", "HTTP") + .formParam("Listeners.member.1.LoadBalancerPort", "80") + .formParam("Listeners.member.1.InstancePort", "8080") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("DuplicateLoadBalancerName")); + } + + @Test + @Order(5) + void describeLoadBalancersReturnsTheClassicDescriptionShape() { + String body = given() + .formParam("Action", "DescribeLoadBalancers") + .formParam("Version", V1) + .formParam("LoadBalancerNames.member.1", LB) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult" + + ".LoadBalancerDescriptions.member.LoadBalancerName", equalTo(LB)) + .body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult" + + ".LoadBalancerDescriptions.member.Scheme", equalTo("internet-facing")) + .body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult" + + ".LoadBalancerDescriptions.member.Subnets.member", equalTo(subnetA())) + .body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult" + + ".LoadBalancerDescriptions.member.SecurityGroups.member", + equalTo("sg-classic")) + .body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult" + + ".LoadBalancerDescriptions.member.ListenerDescriptions.member" + + ".Listener.InstancePort", equalTo("8080")) + .body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult" + + ".LoadBalancerDescriptions.member.HealthCheck.Target", equalTo("TCP:80")) + .extract().asString(); + assertTrue(body.contains("xmlns=\"" + CLASSIC_XMLNS + "\""), body); + assertFalse(body.contains("LoadBalancerArn"), body); + } + + @Test + @Order(6) + void describeUnknownLoadBalancerIsNotFound() { + given() + .formParam("Action", "DescribeLoadBalancers") + .formParam("Version", V1) + .formParam("LoadBalancerNames.member.1", "no-such-elb") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("LoadBalancerNotFound")); + } + + @Test + @Order(7) + void configureHealthCheckStoresAndEchoesTheCheck() { + given() + .formParam("Action", "ConfigureHealthCheck") + .formParam("Version", V1) + .formParam("LoadBalancerName", LB) + .formParam("HealthCheck.Target", "HTTP:8080/") + .formParam("HealthCheck.Interval", "10") + .formParam("HealthCheck.Timeout", "3") + .formParam("HealthCheck.HealthyThreshold", "2") + .formParam("HealthCheck.UnhealthyThreshold", "2") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body("ConfigureHealthCheckResponse.ConfigureHealthCheckResult.HealthCheck.Target", + equalTo("HTTP:8080/")) + .body("ConfigureHealthCheckResponse.ConfigureHealthCheckResult.HealthCheck.Interval", + equalTo("10")); + } + + @Test + @Order(8) + void configureHealthCheckRejectsAnIntervalOutsideTheModelRange() { + given() + .formParam("Action", "ConfigureHealthCheck") + .formParam("Version", V1) + .formParam("LoadBalancerName", LB) + .formParam("HealthCheck.Target", "HTTP:8080/") + .formParam("HealthCheck.Interval", "1") + .formParam("HealthCheck.Timeout", "3") + .formParam("HealthCheck.HealthyThreshold", "2") + .formParam("HealthCheck.UnhealthyThreshold", "2") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")); + } + + @Test + @Order(9) + void registerDescribeAndDeregisterInstances() { + given() + .formParam("Action", "RegisterInstancesWithLoadBalancer") + .formParam("Version", V1) + .formParam("LoadBalancerName", LB) + .formParam("Instances.member.1.InstanceId", "i-1111111111111111a") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body("RegisterInstancesWithLoadBalancerResponse" + + ".RegisterInstancesWithLoadBalancerResult.Instances.member.InstanceId", + equalTo("i-1111111111111111a")); + + given() + .formParam("Action", "DescribeInstanceHealth") + .formParam("Version", V1) + .formParam("LoadBalancerName", LB) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeInstanceHealthResponse.DescribeInstanceHealthResult" + + ".InstanceStates.member.InstanceId", equalTo("i-1111111111111111a")) + .body("DescribeInstanceHealthResponse.DescribeInstanceHealthResult" + + ".InstanceStates.member.State", equalTo("InService")); + + given() + .formParam("Action", "DeregisterInstancesFromLoadBalancer") + .formParam("Version", V1) + .formParam("LoadBalancerName", LB) + .formParam("Instances.member.1.InstanceId", "i-1111111111111111a") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body("DeregisterInstancesFromLoadBalancerResponse" + + ".DeregisterInstancesFromLoadBalancerResult.Instances", equalTo("")); + } + + @Test + @Order(10) + void describeInstanceHealthRejectsAnUnregisteredInstance() { + given() + .formParam("Action", "DescribeInstanceHealth") + .formParam("Version", V1) + .formParam("LoadBalancerName", LB) + .formParam("Instances.member.1.InstanceId", "i-not-registered") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidInstance")); + } + + @Test + @Order(11) + void modifyAndDescribeAttributesRoundTrip() { + given() + .formParam("Action", "ModifyLoadBalancerAttributes") + .formParam("Version", V1) + .formParam("LoadBalancerName", LB) + .formParam("LoadBalancerAttributes.CrossZoneLoadBalancing.Enabled", "true") + .formParam("LoadBalancerAttributes.ConnectionDraining.Enabled", "true") + .formParam("LoadBalancerAttributes.ConnectionDraining.Timeout", "300") + .formParam("LoadBalancerAttributes.ConnectionSettings.IdleTimeout", "90") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body("ModifyLoadBalancerAttributesResponse.ModifyLoadBalancerAttributesResult" + + ".LoadBalancerName", equalTo(LB)); + + given() + .formParam("Action", "DescribeLoadBalancerAttributes") + .formParam("Version", V1) + .formParam("LoadBalancerName", LB) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeLoadBalancerAttributesResponse" + + ".DescribeLoadBalancerAttributesResult.LoadBalancerAttributes" + + ".CrossZoneLoadBalancing.Enabled", equalTo("true")) + .body("DescribeLoadBalancerAttributesResponse" + + ".DescribeLoadBalancerAttributesResult.LoadBalancerAttributes" + + ".ConnectionDraining.Timeout", equalTo("300")) + .body("DescribeLoadBalancerAttributesResponse" + + ".DescribeLoadBalancerAttributesResult.LoadBalancerAttributes" + + ".ConnectionSettings.IdleTimeout", equalTo("90")) + // Untouched members keep their AWS defaults rather than disappearing. + .body("DescribeLoadBalancerAttributesResponse" + + ".DescribeLoadBalancerAttributesResult.LoadBalancerAttributes" + + ".AccessLog.Enabled", equalTo("false")); + } + + @Test + @Order(12) + void listenersCanBeAddedAndRemoved() { + given() + .formParam("Action", "CreateLoadBalancerListeners") + .formParam("Version", V1) + .formParam("LoadBalancerName", LB) + .formParam("Listeners.member.1.Protocol", "TCP") + .formParam("Listeners.member.1.LoadBalancerPort", "8443") + .formParam("Listeners.member.1.InstancePort", "8443") + .header("Authorization", AUTH) + .when().post("/").then().statusCode(200); + + given() + .formParam("Action", "DescribeLoadBalancers") + .formParam("Version", V1) + .formParam("LoadBalancerNames.member.1", LB) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult" + + ".LoadBalancerDescriptions.member.ListenerDescriptions.member" + + ".Listener.LoadBalancerPort", hasItems("80", "8443")); + + given() + .formParam("Action", "DeleteLoadBalancerListeners") + .formParam("Version", V1) + .formParam("LoadBalancerName", LB) + .formParam("LoadBalancerPorts.member.1", "8443") + .header("Authorization", AUTH) + .when().post("/").then().statusCode(200); + + given() + .formParam("Action", "DescribeLoadBalancers") + .formParam("Version", V1) + .formParam("LoadBalancerNames.member.1", LB) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult" + + ".LoadBalancerDescriptions.member.ListenerDescriptions.member" + + ".Listener.LoadBalancerPort", equalTo("80")); + } + + @Test + @Order(13) + void tagsRoundTripByLoadBalancerName() { + given() + .formParam("Action", "DescribeTags") + .formParam("Version", V1) + .formParam("LoadBalancerNames.member.1", LB) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeTagsResponse.DescribeTagsResult.TagDescriptions.member" + + ".LoadBalancerName", equalTo(LB)) + .body("DescribeTagsResponse.DescribeTagsResult.TagDescriptions.member" + + ".Tags.member.Key", equalTo("gw:example")); + + given() + .formParam("Action", "AddTags") + .formParam("Version", V1) + .formParam("LoadBalancerNames.member.1", LB) + .formParam("Tags.member.1.Key", "owner") + .formParam("Tags.member.1.Value", "harness") + .header("Authorization", AUTH) + .when().post("/").then().statusCode(200); + + given() + .formParam("Action", "RemoveTags") + .formParam("Version", V1) + .formParam("LoadBalancerNames.member.1", LB) + .formParam("Tags.member.1.Key", "gw:example") + .header("Authorization", AUTH) + .when().post("/").then().statusCode(200); + + given() + .formParam("Action", "DescribeTags") + .formParam("Version", V1) + .formParam("LoadBalancerNames.member.1", LB) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeTagsResponse.DescribeTagsResult.TagDescriptions.member" + + ".Tags.member.Key", equalTo("owner")); + } + + @Test + @Order(14) + void subnetAndSecurityGroupChangesRoundTrip() { + given() + .formParam("Action", "AttachLoadBalancerToSubnets") + .formParam("Version", V1) + .formParam("LoadBalancerName", LB) + .formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "b")) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body("AttachLoadBalancerToSubnetsResponse.AttachLoadBalancerToSubnetsResult" + + ".Subnets.member", hasItems(subnetA(), + Ec2Service.defaultSubnetId("us-east-1", "b"))); + + given() + .formParam("Action", "DetachLoadBalancerFromSubnets") + .formParam("Version", V1) + .formParam("LoadBalancerName", LB) + .formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "b")) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body("DetachLoadBalancerFromSubnetsResponse.DetachLoadBalancerFromSubnetsResult" + + ".Subnets.member", equalTo(subnetA())); + + given() + .formParam("Action", "ApplySecurityGroupsToLoadBalancer") + .formParam("Version", V1) + .formParam("LoadBalancerName", LB) + .formParam("SecurityGroups.member.1", "sg-replaced") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body("ApplySecurityGroupsToLoadBalancerResponse" + + ".ApplySecurityGroupsToLoadBalancerResult.SecurityGroups.member", + equalTo("sg-replaced")); + } + + @Test + @Order(15) + void unimplementedClassicPolicyOperationsSaySoInTheClassicNamespace() { + String body = given() + .formParam("Action", "CreateLBCookieStickinessPolicy") + .formParam("Version", V1) + .formParam("LoadBalancerName", LB) + .formParam("PolicyName", "stickiness") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("UnsupportedOperation")) + .extract().asString(); + assertTrue(body.contains(CLASSIC_XMLNS), body); + } + + @Test + @Order(16) + void aRequestWithoutAVersionRoutesOnItsParameterShape() { + // A hand-rolled client that omitted Version but named a load balancer is Classic. + given() + .formParam("Action", "DescribeLoadBalancers") + .formParam("LoadBalancerNames.member.1", LB) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult" + + ".LoadBalancerDescriptions.member.LoadBalancerName", equalTo(LB)); + } + + @Test + @Order(17) + void elbV2RequestsStillReachTheV2Handler() { + String body = given() + .formParam("Action", "CreateLoadBalancer") + .formParam("Version", V2) + .formParam("Name", "v2-still-works") + .formParam("Type", "application") + .formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a")) + .formParam("Subnets.member.2", Ec2Service.defaultSubnetId("us-east-1", "b")) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member" + + ".LoadBalancerName", equalTo("v2-still-works")) + .extract().asString(); + assertTrue(body.contains(V2_XMLNS), body); + + given() + .formParam("Action", "DescribeLoadBalancers") + .formParam("Version", V2) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers" + + ".member.LoadBalancerName", not(hasItems(LB))); + } + + @Test + @Order(18) + void deleteRemovesTheClassicLoadBalancerAndIsIdempotent() { + given() + .formParam("Action", "DeleteLoadBalancer") + .formParam("Version", V1) + .formParam("LoadBalancerName", LB) + .header("Authorization", AUTH) + .when().post("/").then().statusCode(200); + + // AWS answers a delete of something already gone with success. + given() + .formParam("Action", "DeleteLoadBalancer") + .formParam("Version", V1) + .formParam("LoadBalancerName", LB) + .header("Authorization", AUTH) + .when().post("/").then().statusCode(200); + + given() + .formParam("Action", "DescribeLoadBalancers") + .formParam("Version", V1) + .formParam("LoadBalancerNames.member.1", LB) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("LoadBalancerNotFound")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/elb/ElbClassicServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/elb/ElbClassicServiceTest.java new file mode 100644 index 0000000000..0213abea6c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/elb/ElbClassicServiceTest.java @@ -0,0 +1,243 @@ +package io.github.hectorvent.floci.services.elb; + +import io.github.hectorvent.floci.core.common.AwsException; +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 org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class ElbClassicServiceTest { + + private static final String REGION = "us-west-2"; + + @Mock + Ec2Service ec2Service; + + @Mock + ElbClassicHealthChecker healthChecker; + + private ElbClassicService service; + + @BeforeEach + void setUp() { + service = new ElbClassicService(ec2Service, healthChecker, null, null); + lenient().when(ec2Service.describeSubnets(anyString(), anyList(), any())) + .thenAnswer(invocation -> { + List ids = invocation.getArgument(1); + return ids.stream().map(id -> { + Subnet subnet = new Subnet(); + subnet.setSubnetId(id); + subnet.setVpcId("vpc-1"); + subnet.setAvailabilityZone(REGION + id.substring(id.length() - 1)); + return subnet; + }).toList(); + }); + } + + private static ClassicListener httpListener() { + ClassicListener listener = new ClassicListener(); + listener.setProtocol("HTTP"); + listener.setLoadBalancerPort(80); + listener.setInstanceProtocol("HTTP"); + listener.setInstancePort(8080); + return listener; + } + + private ClassicLoadBalancer create(String name) { + return service.createLoadBalancer(REGION, name, List.of(httpListener()), + List.of(), List.of("subnet-a"), List.of("sg-1"), null, Map.of()); + } + + @Test + void createGivesADnsNameAndTheAwsDefaultHealthCheck() { + ClassicLoadBalancer lb = create("my-elb"); + + assertTrue(lb.getDnsName().startsWith("my-elb-")); + assertEquals("internet-facing", lb.getScheme()); + assertEquals("vpc-1", lb.getVpcId()); + assertEquals(List.of(REGION + "a"), lb.getAvailabilityZones()); + // AWS's documented defaults for a load balancer that has never been configured. + assertEquals("TCP:80", lb.getHealthCheck().getTarget()); + assertEquals(30, lb.getHealthCheck().getInterval()); + assertEquals(10, lb.getHealthCheck().getHealthyThreshold()); + verify(healthChecker).startMonitoring(lb); + } + + @Test + void createRejectsAMissingNameWithTheClassicParameterName() { + AwsException e = assertThrows(AwsException.class, () -> + service.createLoadBalancer(REGION, null, List.of(httpListener()), + List.of(), List.of(), List.of(), null, Map.of())); + assertEquals("ValidationError", e.getErrorCode()); + assertTrue(e.getMessage().contains("LoadBalancerName"), e.getMessage()); + } + + @Test + void createRejectsAListenerMissingARequiredMember() { + ClassicListener incomplete = new ClassicListener(); + incomplete.setProtocol("HTTP"); + incomplete.setLoadBalancerPort(80); + AwsException e = assertThrows(AwsException.class, () -> + service.createLoadBalancer(REGION, "my-elb", List.of(incomplete), + List.of(), List.of(), List.of(), null, Map.of())); + assertEquals("ValidationError", e.getErrorCode()); + } + + @Test + void createRejectsAnEmptyListenerListNamingTheMissingMember() { + AwsException e = assertThrows(AwsException.class, () -> + service.createLoadBalancer(REGION, "my-elb", List.of(), + List.of(), List.of("subnet-a"), List.of("sg-1"), null, Map.of())); + assertEquals("ValidationError", e.getErrorCode()); + assertTrue(e.getMessage().contains("listener"), e.getMessage()); + } + + /** + * CreateLoadBalancer's Errors table documents InvalidConfigurationRequest at HTTP 409, not + * 400 — a client that retries on 409 but fails hard on 400 depends on the difference. + */ + @Test + void subnetsSpanningTwoVpcsAreRejectedWithTheDocumentedStatus() { + when(ec2Service.describeSubnets(anyString(), anyList(), any())) + .thenAnswer(invocation -> { + List ids = invocation.getArgument(1); + return ids.stream().map(id -> { + Subnet subnet = new Subnet(); + subnet.setSubnetId(id); + subnet.setVpcId("vpc-" + id.charAt(id.length() - 1)); + subnet.setAvailabilityZone(REGION + id.charAt(id.length() - 1)); + return subnet; + }).toList(); + }); + + AwsException e = assertThrows(AwsException.class, () -> + service.createLoadBalancer(REGION, "my-elb", List.of(httpListener()), + List.of(), List.of("subnet-a", "subnet-b"), List.of("sg-1"), null, Map.of())); + assertEquals("InvalidConfigurationRequest", e.getErrorCode()); + assertEquals(409, e.getHttpStatus()); + } + + @Test + void createRejectsADuplicateName() { + create("my-elb"); + AwsException e = assertThrows(AwsException.class, () -> create("my-elb")); + assertEquals("DuplicateLoadBalancerName", e.getErrorCode()); + } + + @Test + void loadBalancersAreScopedByRegion() { + create("my-elb"); + assertTrue(service.hasLoadBalancer(REGION, "my-elb")); + assertTrue(service.describeLoadBalancers("eu-west-1", null).isEmpty()); + } + + @Test + void configureHealthCheckStoresAndRearmsTheChecker() { + ClassicLoadBalancer lb = create("my-elb"); + ClassicHealthCheck hc = new ClassicHealthCheck(); + hc.setTarget("HTTP:8080/health"); + hc.setInterval(10); + hc.setTimeout(3); + hc.setHealthyThreshold(2); + hc.setUnhealthyThreshold(2); + + service.configureHealthCheck(REGION, "my-elb", hc); + + assertEquals("HTTP:8080/health", lb.getHealthCheck().getTarget()); + verify(healthChecker).healthCheckChanged(lb); + } + + @Test + void configureHealthCheckEnforcesTheRangesTheModelDeclares() { + create("my-elb"); + ClassicHealthCheck hc = new ClassicHealthCheck(); + hc.setTarget("HTTP:8080/"); + hc.setInterval(301); + hc.setTimeout(3); + hc.setHealthyThreshold(2); + hc.setUnhealthyThreshold(2); + + AwsException e = assertThrows(AwsException.class, + () -> service.configureHealthCheck(REGION, "my-elb", hc)); + assertEquals("ValidationError", e.getErrorCode()); + } + + @Test + void registerAndDeregisterInstancesAreIdempotent() { + create("my-elb"); + service.registerInstances(REGION, "my-elb", List.of("i-1")); + assertEquals(List.of("i-1"), service.registerInstances(REGION, "my-elb", List.of("i-1"))); + assertEquals(List.of(), service.deregisterInstances(REGION, "my-elb", List.of("i-1"))); + verify(healthChecker).deregisterInstances(REGION, "my-elb", List.of("i-1")); + } + + @Test + void describeInstanceHealthRejectsAnInstanceThatIsNotRegistered() { + create("my-elb"); + AwsException e = assertThrows(AwsException.class, + () -> service.describeInstanceHealth(REGION, "my-elb", List.of("i-unknown"))); + assertEquals("InvalidInstance", e.getErrorCode()); + } + + @Test + void modifyAttributesLeavesUnsentMembersAtTheirDefaults() { + create("my-elb"); + service.modifyLoadBalancerAttributes(REGION, "my-elb", + new ElbClassicService.AttributeUpdate(true, null, null, null, null, + true, 300, null, Map.of())); + + ClassicLoadBalancer lb = service.requireLoadBalancer(REGION, "my-elb"); + assertTrue(lb.getAttributes().isCrossZoneLoadBalancingEnabled()); + assertTrue(lb.getAttributes().isConnectionDrainingEnabled()); + assertEquals(300, lb.getAttributes().getConnectionDrainingTimeout()); + assertEquals(60, lb.getAttributes().getIdleTimeout()); + assertNull(lb.getAttributes().getAccessLogS3BucketName()); + } + + @Test + void deleteIsSilentForALoadBalancerThatDoesNotExist() { + service.deleteLoadBalancer(REGION, "never-existed"); + assertThrows(AwsException.class, () -> service.requireLoadBalancer(REGION, "never-existed")); + } + + @Test + void addingAConflictingListenerOnAPortInUseIsRejected() { + create("my-elb"); + ClassicListener conflicting = new ClassicListener(); + conflicting.setProtocol("TCP"); + conflicting.setLoadBalancerPort(80); + conflicting.setInstancePort(9999); + + AwsException e = assertThrows(AwsException.class, () -> + service.createLoadBalancerListeners(REGION, "my-elb", List.of(conflicting))); + assertEquals("DuplicateListener", e.getErrorCode()); + } + + @Test + void repeatingAnIdenticalListenerIsAccepted() { + ClassicLoadBalancer lb = create("my-elb"); + service.createLoadBalancerListeners(REGION, "my-elb", List.of(httpListener())); + assertEquals(1, lb.getListeners().size()); + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 0954f2fcaf..277d7dd85d 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -273,6 +273,9 @@ floci: mock: true pipes: enabled: true + elb: + enabled: true + mock: true elbv2: enabled: true mock: true diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml index 1aa55e67a8..f9669b7533 100644 --- a/tools/docs/services.yaml +++ b/tools/docs/services.yaml @@ -221,6 +221,7 @@ deferred_handlers: - { path: src/main/java/io/github/hectorvent/floci/services/ecr/EcrJsonHandler.java } # doc packs multiple actions per row (`A` / `B`) + REST endpoints; needs de-grouping - { path: src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java } # non-tabular doc (grouped/inline) - { path: src/main/java/io/github/hectorvent/floci/services/elasticbeanstalk/ElasticBeanstalkQueryHandler.java } # non-tabular doc (grouped/inline) + - { path: src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicQueryHandler.java } # non-tabular doc (grouped/inline) - { path: src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2QueryHandler.java } # non-tabular doc (grouped/inline) - { path: src/main/java/io/github/hectorvent/floci/services/glue/GlueJsonHandler.java } # non-tabular doc (grouped/inline) - { path: src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java } # non-tabular doc (grouped/inline)