mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
refactor(cloudformation): move the ElasticLoadBalancingV2 types into ElbV2CfnProvisioner (#3115)
* refactor(cloudformation): move the ElasticLoadBalancingV2 types into ElbV2CfnProvisioner AWS::ElasticLoadBalancingV2::LoadBalancer, TargetGroup, Listener and ListenerRule leave the legacy switch together with the ELBv2-only helpers (ELB-safe name generation, full-name derivation, matcher, certificates, action and rule-condition parsing). The monolith no longer depends on ElbV2Service; its constructor loses that parameter and CfnProvisionerFixture passes one argument less. Behaviour is unchanged except where the move fixes it. An unnamed load balancer or target group keeps the name its first execution generated, read back from the LoadBalancerName / TargetGroupName attribute since the physical id is the ARN; the switch generated a fresh name on every pass and left the previous resource behind. Listener and ListenerRule branch create-vs-update on the provision context, and a listener moved to another load balancer or a rule moved to another listener (both create-only properties) is created as a replacement instead of being modified under the old parent; one removed out of band is created again. A non-integer Port or Priority is a ValidationError instead of an uncaught NumberFormatException. Deletes call the service directly: it already returns silently for an unknown ARN, and its refusals (ResourceInUse, OperationNotPermitted) must keep failing the stack delete. Fn::GetAtt follows the registry schemas' readOnly properties. The five load balancer attributes, ListenerArn, RuleArn and IsDefault are as before; TargetGroup gains LoadBalancerArns (comma-joined, empty until a listener forwards to the group), which the switch never set and the schema coverage test now requires. CloudFormationIntegrationTest keeps asserting the stack outputs end to end; ElbV2CfnProvisionerTest covers the four types against a mocked ElbV2Service. The whole CloudFormation test package passes on this tree apart from the pre-existing ACM schema-gap row. * refactor(cloudformation): clean up the ELBv2 entity a replacing update displaced Review found that a listener moved to another load balancer, or a rule moved to another listener, was created anew while the displaced one kept running, holding its target groups in use and never appearing in the stack's cleanup. The same was true of a renamed load balancer or target group. Every replacing update of the four types now enters the replacement-cleanup lifecycle the engine already runs (UPDATE_COMPLETE_CLEANUP_IN_PROGRESS, DELETE_IN_PROGRESS on the prior ARN, three attempts, UpdateReplacePolicy Retain honoured). ReplacementCleanup is the plain bookkeeping for provisioners without a rollback snapshot, beside the richer record PipesCfnProvisioner keeps; the provisioner delegates the four interface hooks to it and deletes through its own delete arm. The direct service deletes stay as they were: ElbV2Service returns silently for an unknown ARN, so there is no already-gone code for CfnDeletes.safeDelete to tolerate, and its refusals (ResourceInUse, OperationNotPermitted) must keep failing the stack delete. * refactor(cloudformation): roll an ELBv2 replacement back and clean up dependents first Review found two gaps in the replacement handling. A replacement this provisioner produces (a listener moved to another load balancer, a rule moved to another listener, a renamed load balancer or target group) could not be rolled back when a later resource failed the stack update: rollbackUpdate had no implementation, so the engine reported "Rollback is not implemented", left the replacement running and the stack in UPDATE_ROLLBACK_FAILED. And the committed-update cleanup walked resources in creation order, so a target group renamed in the same update as its listener was moved would be deleted while the old listener still forwarded to it, fail ResourceInUse three times and be left behind. ReplacementCleanup now keeps the attributes the resource carried before the provision alongside the prior physical id, and rollback() puts both back and deletes the replacement through the provisioner's own delete arm, spending the record before the delete so a failing delete cannot put the restored prior on the next cleanup's list. The provisioner records once, in provision(), and delegates rollbackUpdate. A load balancer or target group without a record has nothing to put back, every property being create-only and the update having only described the existing entity, so it rolls back as complete; a listener or rule modified in place keeps the engine's existing handling, as under the switch. CloudFormationService's committed cleanup walks resources in reverse creation order, as every other teardown walk does. CloudFormationElbV2ReplacementIntegrationTest drives both through the engine: a renamed target group plus a moved listener end with DELETE_COMPLETE events on both prior ARNs and neither entity left, and a moved listener followed by a failing resource lands the stack in UPDATE_ROLLBACK_COMPLETE with the prior listener restored and the replacement gone. * refactor(cloudformation): order replacement cleanup by the template and keep an orphaned replacement owed Two gaps in the replacement lifecycle, both found in review. The committed cleanup walked the resource map reversed, but the map is insertion order and a resource a later update added sits after the resources that depend on it, so a target group added after its listener would still be deleted first, fail ResourceInUse three times and be left behind. The cleanup now walks resourcesInCreationOrder reversed, the template's dependency order, exactly as DeleteStack does; a resource the template no longer names sorts last. And a rollback whose delete of the replacement failed forgot the replacement: the record was cleared before the delete, so nothing could remove that entity later even though UPDATE_ROLLBACK_FAILED is updatable here and both the next committed update and DeleteStack run the cleanup first. The record is now a list of every entity owed a delete: a replacement whose rollback delete fails is listed in the prior's place, never retained (a failed update created it), and the prior's own id and attributes are kept beside the list only while this update's replacement can still be rolled back. Every listed entity gets its attempt on every cleanup call, so one that keeps failing does not leave the others untried. The load balancer and target group rollback note now says what is true: this provisioner never modifies an existing one, so an update that kept the name has nothing to put back (in-place changes to their updatable properties are not applied, as under the switch). CloudFormationElbV2ReplacementIntegrationTest gains the appended-dependency case: a target group added by a later update than its listener, then both replaced, ends with both prior ARNs DELETE_COMPLETE. * refactor(cloudformation): keep a displaced entity owed until its own attempts are used up Review found that once any listed entity reached three failed deletes, the engine's give-up cleared the whole record, forgetting entities that still had attempts left. clearUpdate now drops only the entries that used up their attempts (and the rollback fields), and the cleanup result reports the lowest attempt count among what remains, naming that entity, so the engine keeps retrying until every remaining entity has had its own three attempts. * refactor(cloudformation): tolerate the ELBv2 not-found codes on delete and name one entity per cleanup The four ELBv2 deletes go through CfnDeletes.safeDelete with the not-found code ElbV2Service defines for each type (LoadBalancerNotFound, TargetGroupNotFound, ListenerNotFound, RuleNotFound), the convention every other per-service provisioner follows. The service's delete paths return silently on an unknown ARN today, so nothing changes in behaviour; its refusals (ResourceInUse, OperationNotPermitted) are not in the list and keep failing the stack delete. The replacement cleanup picks the entity it works on through one rule, the owed entry with the fewest attempts, for both the physical id it announces (DELETE_IN_PROGRESS) and the one it reports on failure (DELETE_FAILED), so a cleanup's progress and failure events name the same thing. The unused parameter on the record's region lookup goes.
This commit is contained in:
1 parent
acc0904be4
commit
2541f1b68d
7 files changed
+1473
-347
No files matched your search
-320
@@ -58,13 +58,6 @@ import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;
|
||||
import io.github.hectorvent.floci.services.eks.EksService;
|
||||
import io.github.hectorvent.floci.services.eks.model.CreateClusterRequest;
|
||||
import io.github.hectorvent.floci.services.eks.model.Nodegroup;
|
||||
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Action;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Listener;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.LoadBalancer;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Rule;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.RuleCondition;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.TargetGroup;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.github.hectorvent.floci.services.kms.KmsService;
|
||||
@@ -223,10 +216,6 @@ public class CloudFormationResourceProvisioner {
|
||||
"AWS::EC2::SubnetRouteTableAssociation",
|
||||
"AWS::EKS::Cluster",
|
||||
"AWS::EKS::Nodegroup",
|
||||
"AWS::ElasticLoadBalancingV2::Listener",
|
||||
"AWS::ElasticLoadBalancingV2::ListenerRule",
|
||||
"AWS::ElasticLoadBalancingV2::LoadBalancer",
|
||||
"AWS::ElasticLoadBalancingV2::TargetGroup",
|
||||
"AWS::Events::EventBus",
|
||||
"AWS::Events::EventBusPolicy",
|
||||
"AWS::Events::Rule",
|
||||
@@ -271,7 +260,6 @@ public class CloudFormationResourceProvisioner {
|
||||
private final ObjectMapper objectMapper;
|
||||
private final CustomResourceResponseStore customResourceResponseStore;
|
||||
private final ContainerReachableEndpoint reachableEndpoint;
|
||||
private final ElbV2Service elbV2Service;
|
||||
private final StepFunctionsService stepFunctionsService;
|
||||
private final BatchService batchService;
|
||||
private final Ec2Service ec2Service;
|
||||
@@ -302,7 +290,6 @@ public class CloudFormationResourceProvisioner {
|
||||
ObjectMapper objectMapper,
|
||||
CustomResourceResponseStore customResourceResponseStore,
|
||||
ContainerReachableEndpoint reachableEndpoint,
|
||||
ElbV2Service elbV2Service,
|
||||
StepFunctionsService stepFunctionsService,
|
||||
BatchService batchService,
|
||||
Ec2Service ec2Service,
|
||||
@@ -331,7 +318,6 @@ public class CloudFormationResourceProvisioner {
|
||||
this.objectMapper = objectMapper;
|
||||
this.customResourceResponseStore = customResourceResponseStore;
|
||||
this.reachableEndpoint = reachableEndpoint;
|
||||
this.elbV2Service = elbV2Service;
|
||||
this.stepFunctionsService = stepFunctionsService;
|
||||
this.batchService = batchService;
|
||||
this.ec2Service = ec2Service;
|
||||
@@ -425,14 +411,6 @@ public class CloudFormationResourceProvisioner {
|
||||
case "AWS::CloudFormation::CustomResource" ->
|
||||
provisionCustomResource(resource, properties, engine, region, accountId, stackName);
|
||||
case "Custom::DynamoDBReplica" -> provisionDynamoDbReplica(resource, properties, engine, region);
|
||||
case "AWS::ElasticLoadBalancingV2::LoadBalancer" ->
|
||||
provisionLoadBalancer(resource, properties, engine, region, stackName);
|
||||
case "AWS::ElasticLoadBalancingV2::TargetGroup" ->
|
||||
provisionTargetGroup(resource, properties, engine, region, stackName);
|
||||
case "AWS::ElasticLoadBalancingV2::Listener" ->
|
||||
provisionListener(resource, properties, engine, region);
|
||||
case "AWS::ElasticLoadBalancingV2::ListenerRule" ->
|
||||
provisionListenerRule(resource, properties, engine, region);
|
||||
case "AWS::Batch::ComputeEnvironment" ->
|
||||
provisionBatchComputeEnvironment(resource, properties, engine, region, stackName);
|
||||
case "AWS::Batch::JobQueue" ->
|
||||
@@ -706,10 +684,6 @@ public class CloudFormationResourceProvisioner {
|
||||
case "AWS::ApiGatewayV2::Api" -> apiGatewayV2Service.deleteApi(region, physicalId);
|
||||
case "AWS::StepFunctions::StateMachine" -> stepFunctionsService.deleteStateMachine(physicalId);
|
||||
case "AWS::Lambda::LayerVersion" -> deleteLambdaLayerVersion(physicalId, region);
|
||||
case "AWS::ElasticLoadBalancingV2::LoadBalancer" -> elbV2Service.deleteLoadBalancer(region, physicalId);
|
||||
case "AWS::ElasticLoadBalancingV2::TargetGroup" -> elbV2Service.deleteTargetGroup(region, physicalId);
|
||||
case "AWS::ElasticLoadBalancingV2::Listener" -> elbV2Service.deleteListener(region, physicalId);
|
||||
case "AWS::ElasticLoadBalancingV2::ListenerRule" -> elbV2Service.deleteRule(region, physicalId);
|
||||
case "AWS::EC2::SecurityGroup" -> ec2Service.deleteSecurityGroup(region, physicalId);
|
||||
case "AWS::EC2::Instance" -> ec2Service.terminateInstances(region, List.of(physicalId));
|
||||
case "AWS::RDS::DBInstance" -> rdsService.deleteDbInstance(physicalId, region);
|
||||
@@ -6102,300 +6076,6 @@ public class CloudFormationResourceProvisioner {
|
||||
return result;
|
||||
}
|
||||
|
||||
// ── ELBv2 ────────────────────────────────────────────────────────────────
|
||||
|
||||
private void provisionLoadBalancer(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
String region, String stackName) {
|
||||
String name = resolveOptional(props, "Name", engine);
|
||||
if (name == null || name.isBlank()) {
|
||||
name = generateElbName(stackName, r.getLogicalId());
|
||||
}
|
||||
String scheme = resolveOptional(props, "Scheme", engine);
|
||||
String type = resolveOptional(props, "Type", engine);
|
||||
String ipAddressType = resolveOptional(props, "IpAddressType", engine);
|
||||
List<String> subnets = resolveStringListOrEmpty(props, "Subnets", engine);
|
||||
List<String> securityGroups = resolveStringListOrEmpty(props, "SecurityGroups", engine);
|
||||
Map<String, String> tags = parseCfnTags(props != null ? props.get("Tags") : null, engine);
|
||||
|
||||
LoadBalancer lb;
|
||||
try {
|
||||
lb = elbV2Service.createLoadBalancer(region, name, scheme, type, ipAddressType,
|
||||
subnets, securityGroups, tags);
|
||||
} catch (AwsException e) {
|
||||
if ("DuplicateLoadBalancerName".equals(e.getErrorCode())) {
|
||||
lb = elbV2Service.describeLoadBalancers(region, null, List.of(name), null, null).get(0);
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
r.setPhysicalId(lb.getLoadBalancerArn());
|
||||
r.getAttributes().put("LoadBalancerArn", lb.getLoadBalancerArn());
|
||||
r.getAttributes().put("DNSName", lb.getDnsName());
|
||||
r.getAttributes().put("CanonicalHostedZoneID", lb.getCanonicalHostedZoneId());
|
||||
r.getAttributes().put("LoadBalancerName", lb.getLoadBalancerName());
|
||||
r.getAttributes().put("LoadBalancerFullName", loadBalancerFullName(lb.getLoadBalancerArn()));
|
||||
}
|
||||
|
||||
private void provisionTargetGroup(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
String region, String stackName) {
|
||||
String name = resolveOptional(props, "Name", engine);
|
||||
if (name == null || name.isBlank()) {
|
||||
name = generateElbName(stackName, r.getLogicalId());
|
||||
}
|
||||
String protocol = resolveOptional(props, "Protocol", engine);
|
||||
String protocolVersion = resolveOptional(props, "ProtocolVersion", engine);
|
||||
Integer port = parseIntOrNull(resolveOptional(props, "Port", engine));
|
||||
String vpcId = resolveOptional(props, "VpcId", engine);
|
||||
String targetType = resolveOptional(props, "TargetType", engine);
|
||||
String hcProtocol = resolveOptional(props, "HealthCheckProtocol", engine);
|
||||
String hcPort = resolveOptional(props, "HealthCheckPort", engine);
|
||||
Boolean hcEnabled = parseBooleanOrNull(resolveOptional(props, "HealthCheckEnabled", engine));
|
||||
String hcPath = resolveOptional(props, "HealthCheckPath", engine);
|
||||
Integer hcInterval = parseIntOrNull(resolveOptional(props, "HealthCheckIntervalSeconds", engine));
|
||||
Integer hcTimeout = parseIntOrNull(resolveOptional(props, "HealthCheckTimeoutSeconds", engine));
|
||||
Integer healthyThreshold = parseIntOrNull(resolveOptional(props, "HealthyThresholdCount", engine));
|
||||
Integer unhealthyThreshold = parseIntOrNull(resolveOptional(props, "UnhealthyThresholdCount", engine));
|
||||
String matcher = parseMatcher(props, engine);
|
||||
String ipAddressType = resolveOptional(props, "IpAddressType", engine);
|
||||
Map<String, String> tags = parseCfnTags(props != null ? props.get("Tags") : null, engine);
|
||||
|
||||
TargetGroup tg;
|
||||
try {
|
||||
tg = elbV2Service.createTargetGroup(region, name, protocol, protocolVersion, port, vpcId, targetType,
|
||||
hcProtocol, hcPort, hcEnabled, hcPath, hcInterval, hcTimeout,
|
||||
healthyThreshold, unhealthyThreshold, matcher, ipAddressType, tags);
|
||||
} catch (AwsException e) {
|
||||
if ("DuplicateTargetGroupName".equals(e.getErrorCode())) {
|
||||
tg = elbV2Service.describeTargetGroups(region, null, null, List.of(name)).get(0);
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
r.setPhysicalId(tg.getTargetGroupArn());
|
||||
r.getAttributes().put("TargetGroupArn", tg.getTargetGroupArn());
|
||||
r.getAttributes().put("TargetGroupName", tg.getTargetGroupName());
|
||||
r.getAttributes().put("TargetGroupFullName", targetGroupFullName(tg.getTargetGroupArn()));
|
||||
}
|
||||
|
||||
private void provisionListener(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
String region) {
|
||||
String lbArn = resolveOptional(props, "LoadBalancerArn", engine);
|
||||
String protocol = resolveOrDefault(props, "Protocol", engine, "HTTP");
|
||||
int port = intOrDefault(resolveOptional(props, "Port", engine), 80);
|
||||
String sslPolicy = resolveOptional(props, "SslPolicy", engine);
|
||||
List<String> certificates = parseCertificates(props, engine);
|
||||
List<Action> defaultActions = parseCfnActions(props != null ? props.get("DefaultActions") : null, engine);
|
||||
|
||||
Listener listener;
|
||||
if (r.getPhysicalId() == null) {
|
||||
listener = elbV2Service.createListener(region, lbArn, protocol, port, sslPolicy, certificates,
|
||||
defaultActions, null, Map.of());
|
||||
} else {
|
||||
listener = elbV2Service.modifyListener(region, r.getPhysicalId(), protocol, port, sslPolicy,
|
||||
certificates, defaultActions, null);
|
||||
}
|
||||
|
||||
r.setPhysicalId(listener.getListenerArn());
|
||||
r.getAttributes().put("ListenerArn", listener.getListenerArn());
|
||||
}
|
||||
|
||||
private void provisionListenerRule(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
String region) {
|
||||
String listenerArn = resolveOptional(props, "ListenerArn", engine);
|
||||
int priority = intOrDefault(resolveOptional(props, "Priority", engine), 1);
|
||||
List<RuleCondition> conditions =
|
||||
parseCfnRuleConditions(props != null ? props.get("Conditions") : null, engine);
|
||||
List<Action> actions = parseCfnActions(props != null ? props.get("Actions") : null, engine);
|
||||
|
||||
Rule rule;
|
||||
if (r.getPhysicalId() == null) {
|
||||
rule = elbV2Service.createRule(region, listenerArn, conditions, priority, actions, Map.of());
|
||||
} else {
|
||||
rule = elbV2Service.modifyRule(region, r.getPhysicalId(), conditions, actions);
|
||||
}
|
||||
|
||||
r.setPhysicalId(rule.getRuleArn());
|
||||
r.getAttributes().put("RuleArn", rule.getRuleArn());
|
||||
r.getAttributes().put("IsDefault", String.valueOf(rule.isDefault()));
|
||||
}
|
||||
|
||||
private List<Action> parseCfnActions(JsonNode node, CloudFormationTemplateEngine engine) {
|
||||
List<Action> result = new ArrayList<>();
|
||||
if (node == null || node.isNull()) {
|
||||
return result;
|
||||
}
|
||||
JsonNode resolved = engine.resolveNode(node);
|
||||
if (!resolved.isArray()) {
|
||||
return result;
|
||||
}
|
||||
for (JsonNode item : resolved) {
|
||||
Action action = new Action();
|
||||
action.setType(textOrNull(item, "Type"));
|
||||
if (item.hasNonNull("Order")) {
|
||||
action.setOrder(item.path("Order").asInt());
|
||||
}
|
||||
if (item.hasNonNull("TargetGroupArn")) {
|
||||
action.setTargetGroupArn(item.path("TargetGroupArn").asText());
|
||||
}
|
||||
JsonNode forward = item.path("ForwardConfig");
|
||||
if (forward.isObject()) {
|
||||
JsonNode tgs = forward.path("TargetGroups");
|
||||
if (tgs.isArray()) {
|
||||
List<Action.TargetGroupTuple> tuples = new ArrayList<>();
|
||||
for (JsonNode t : tgs) {
|
||||
Action.TargetGroupTuple tuple = new Action.TargetGroupTuple();
|
||||
if (t.hasNonNull("TargetGroupArn")) {
|
||||
tuple.setTargetGroupArn(t.path("TargetGroupArn").asText());
|
||||
}
|
||||
if (t.hasNonNull("Weight")) {
|
||||
tuple.setWeight(t.path("Weight").asInt());
|
||||
}
|
||||
tuples.add(tuple);
|
||||
}
|
||||
action.setTargetGroups(tuples);
|
||||
}
|
||||
JsonNode stickiness = forward.path("TargetGroupStickinessConfig");
|
||||
if (stickiness.isObject()) {
|
||||
if (stickiness.hasNonNull("Enabled")) {
|
||||
action.setStickinessEnabled(stickiness.path("Enabled").asBoolean());
|
||||
}
|
||||
if (stickiness.hasNonNull("DurationSeconds")) {
|
||||
action.setStickinessDurationSeconds(stickiness.path("DurationSeconds").asInt());
|
||||
}
|
||||
}
|
||||
}
|
||||
JsonNode redirect = item.path("RedirectConfig");
|
||||
if (redirect.isObject()) {
|
||||
action.setRedirectProtocol(textOrNull(redirect, "Protocol"));
|
||||
action.setRedirectPort(textOrNull(redirect, "Port"));
|
||||
action.setRedirectHost(textOrNull(redirect, "Host"));
|
||||
action.setRedirectPath(textOrNull(redirect, "Path"));
|
||||
action.setRedirectQuery(textOrNull(redirect, "Query"));
|
||||
action.setRedirectStatusCode(textOrNull(redirect, "StatusCode"));
|
||||
}
|
||||
JsonNode fixed = item.path("FixedResponseConfig");
|
||||
if (fixed.isObject()) {
|
||||
action.setFixedResponseStatusCode(textOrNull(fixed, "StatusCode"));
|
||||
action.setFixedResponseContentType(textOrNull(fixed, "ContentType"));
|
||||
action.setFixedResponseMessageBody(textOrNull(fixed, "MessageBody"));
|
||||
}
|
||||
result.add(action);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<RuleCondition> parseCfnRuleConditions(JsonNode node, CloudFormationTemplateEngine engine) {
|
||||
List<RuleCondition> result = new ArrayList<>();
|
||||
if (node == null || node.isNull()) {
|
||||
return result;
|
||||
}
|
||||
JsonNode resolved = engine.resolveNode(node);
|
||||
if (!resolved.isArray()) {
|
||||
return result;
|
||||
}
|
||||
for (JsonNode item : resolved) {
|
||||
RuleCondition condition = new RuleCondition();
|
||||
condition.setField(textOrNull(item, "Field"));
|
||||
if (item.path("Values").isArray()) {
|
||||
condition.setValues(jsonArrayToStringList(item.path("Values")));
|
||||
}
|
||||
JsonNode pathCfg = item.path("PathPatternConfig");
|
||||
if (pathCfg.path("Values").isArray()) {
|
||||
condition.setPathPatternValues(jsonArrayToStringList(pathCfg.path("Values")));
|
||||
}
|
||||
JsonNode hostCfg = item.path("HostHeaderConfig");
|
||||
if (hostCfg.path("Values").isArray()) {
|
||||
condition.setHostHeaderValues(jsonArrayToStringList(hostCfg.path("Values")));
|
||||
}
|
||||
JsonNode httpHeaderCfg = item.path("HttpHeaderConfig");
|
||||
if (httpHeaderCfg.isObject()) {
|
||||
condition.setHttpHeaderName(textOrNull(httpHeaderCfg, "HttpHeaderName"));
|
||||
if (httpHeaderCfg.path("Values").isArray()) {
|
||||
condition.setHttpHeaderValues(jsonArrayToStringList(httpHeaderCfg.path("Values")));
|
||||
}
|
||||
}
|
||||
JsonNode methodCfg = item.path("HttpRequestMethodConfig");
|
||||
if (methodCfg.path("Values").isArray()) {
|
||||
condition.setHttpMethodValues(jsonArrayToStringList(methodCfg.path("Values")));
|
||||
}
|
||||
JsonNode sourceIpCfg = item.path("SourceIpConfig");
|
||||
if (sourceIpCfg.path("Values").isArray()) {
|
||||
condition.setSourceIpValues(jsonArrayToStringList(sourceIpCfg.path("Values")));
|
||||
}
|
||||
JsonNode queryCfg = item.path("QueryStringConfig");
|
||||
if (queryCfg.path("Values").isArray()) {
|
||||
List<RuleCondition.QueryStringPair> pairs = new ArrayList<>();
|
||||
for (JsonNode q : queryCfg.path("Values")) {
|
||||
RuleCondition.QueryStringPair pair = new RuleCondition.QueryStringPair();
|
||||
pair.setKey(textOrNull(q, "Key"));
|
||||
pair.setValue(textOrNull(q, "Value"));
|
||||
pairs.add(pair);
|
||||
}
|
||||
condition.setQueryStringValues(pairs);
|
||||
}
|
||||
result.add(condition);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<String> parseCertificates(JsonNode props, CloudFormationTemplateEngine engine) {
|
||||
List<String> result = new ArrayList<>();
|
||||
if (props == null || !props.has("Certificates") || props.get("Certificates").isNull()) {
|
||||
return result;
|
||||
}
|
||||
JsonNode resolved = engine.resolveNode(props.get("Certificates"));
|
||||
if (resolved.isArray()) {
|
||||
for (JsonNode c : resolved) {
|
||||
if (c.hasNonNull("CertificateArn")) {
|
||||
result.add(c.path("CertificateArn").asText());
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private String parseMatcher(JsonNode props, CloudFormationTemplateEngine engine) {
|
||||
if (props == null || !props.has("Matcher") || props.get("Matcher").isNull()) {
|
||||
return null;
|
||||
}
|
||||
JsonNode m = engine.resolveNode(props.get("Matcher"));
|
||||
if (m.hasNonNull("HttpCode")) {
|
||||
return m.path("HttpCode").asText();
|
||||
}
|
||||
if (m.hasNonNull("GrpcCode")) {
|
||||
return m.path("GrpcCode").asText();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String loadBalancerFullName(String lbArn) {
|
||||
// LB ARN resource: loadbalancer/<type>/<name>/<id> → full name drops the "loadbalancer/" prefix.
|
||||
String resource = AwsArnUtils.parse(lbArn).resource();
|
||||
String prefix = "loadbalancer/";
|
||||
return resource.startsWith(prefix) ? resource.substring(prefix.length()) : resource;
|
||||
}
|
||||
|
||||
private String targetGroupFullName(String tgArn) {
|
||||
// TG full name keeps the "targetgroup/" prefix, e.g. targetgroup/<name>/<id>.
|
||||
return AwsArnUtils.parse(tgArn).resource();
|
||||
}
|
||||
|
||||
private static String generateElbName(String stackName, String logicalId) {
|
||||
// ELBv2 names: ≤32 chars, [A-Za-z0-9-], no leading/trailing hyphen.
|
||||
String base = (stackName + "-" + logicalId).replaceAll("[^A-Za-z0-9-]", "");
|
||||
String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
|
||||
int maxBase = 32 - 1 - suffix.length();
|
||||
if (base.length() > maxBase) {
|
||||
base = base.substring(0, maxBase);
|
||||
}
|
||||
base = base.replaceAll("-+$", "");
|
||||
if (base.isEmpty()) {
|
||||
base = "elb";
|
||||
}
|
||||
return base + "-" + suffix;
|
||||
}
|
||||
|
||||
private static Integer parseIntOrNull(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
|
||||
+511
@@ -0,0 +1,511 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Action;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Listener;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.LoadBalancer;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Rule;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.RuleCondition;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.TargetGroup;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* CloudFormation provisioning for the Elastic Load Balancing v2 types,
|
||||
* {@code AWS::ElasticLoadBalancingV2::LoadBalancer}, {@code TargetGroup}, {@code Listener} and
|
||||
* {@code ListenerRule}, moved out of the {@code CloudFormationResourceProvisioner} switch.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ElbV2CfnProvisioner.class);
|
||||
|
||||
private static final String LOAD_BALANCER = "AWS::ElasticLoadBalancingV2::LoadBalancer";
|
||||
private static final String TARGET_GROUP = "AWS::ElasticLoadBalancingV2::TargetGroup";
|
||||
private static final String LISTENER = "AWS::ElasticLoadBalancingV2::Listener";
|
||||
private static final String LISTENER_RULE = "AWS::ElasticLoadBalancingV2::ListenerRule";
|
||||
|
||||
private final ElbV2Service elbV2Service;
|
||||
|
||||
@Inject
|
||||
public ElbV2CfnProvisioner(ElbV2Service elbV2Service) {
|
||||
this.elbV2Service = elbV2Service;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of(LOAD_BALANCER, TARGET_GROUP, LISTENER, LISTENER_RULE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
|
||||
switch (r.getResourceType()) {
|
||||
case LOAD_BALANCER -> provisionLoadBalancer(r, props, ctx);
|
||||
case TARGET_GROUP -> provisionTargetGroup(r, props, ctx);
|
||||
case LISTENER -> provisionListener(r, props, ctx);
|
||||
case LISTENER_RULE -> provisionListenerRule(r, props, ctx);
|
||||
default -> throw new IllegalStateException("ElbV2CfnProvisioner cannot handle " + r.getResourceType());
|
||||
}
|
||||
// A provision that left the resource with a new physical id replaced the entity: the
|
||||
// displaced one is deleted once the update commits, or restored if the update rolls back.
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore);
|
||||
}
|
||||
|
||||
/**
|
||||
* Each delete tolerates only the not-found code ElbV2Service defines for that type, so an
|
||||
* entity already gone is delete-complete, while the service's refusals (ResourceInUse on a
|
||||
* target group a listener still forwards to, OperationNotPermitted on a listener's default
|
||||
* rule) keep failing the stack delete.
|
||||
*/
|
||||
@Override
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
if (physicalId == null || physicalId.isBlank()) {
|
||||
return;
|
||||
}
|
||||
switch (resourceType) {
|
||||
case LOAD_BALANCER -> CfnDeletes.safeDelete("load balancer", physicalId,
|
||||
() -> elbV2Service.deleteLoadBalancer(region, physicalId), "LoadBalancerNotFound");
|
||||
case TARGET_GROUP -> CfnDeletes.safeDelete("target group", physicalId,
|
||||
() -> elbV2Service.deleteTargetGroup(region, physicalId), "TargetGroupNotFound");
|
||||
case LISTENER -> CfnDeletes.safeDelete("listener", physicalId,
|
||||
() -> elbV2Service.deleteListener(region, physicalId), "ListenerNotFound");
|
||||
case LISTENER_RULE -> CfnDeletes.safeDelete("listener rule", physicalId,
|
||||
() -> elbV2Service.deleteRule(region, physicalId), "RuleNotFound");
|
||||
default -> { }
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasReplacementUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.hasReplacement(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String updateCleanupPhysicalId(StackResource resource) {
|
||||
return ReplacementCleanup.cleanupPhysicalId(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.complete(resource, this::delete);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearUpdate(StackResource resource) {
|
||||
ReplacementCleanup.clear(resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* A replacement is undone through the cleanup record. Without one, a load balancer or target
|
||||
* group has nothing to put back: this provisioner never modifies an existing one (an update that
|
||||
* kept the name only described it, the way the switch did), so nothing changed. A listener or
|
||||
* rule without a record was modified in place, and putting that back needs a snapshot this
|
||||
* provisioner does not keep, so the engine reports it as not rolled back, as it did for the switch.
|
||||
*/
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource) {
|
||||
if (ReplacementCleanup.rollback(resource, this::delete)) {
|
||||
return true;
|
||||
}
|
||||
return LOAD_BALANCER.equals(resource.getResourceType()) || TARGET_GROUP.equals(resource.getResourceType());
|
||||
}
|
||||
|
||||
/**
|
||||
* The physical id is the ARN, so the name an unnamed load balancer got at create time is read
|
||||
* back from the {@code LoadBalancerName} attribute before a new one is generated; the switch
|
||||
* generated afresh on every pass and left the previous balancer behind. A name that already
|
||||
* exists is reused, which is what makes an unchanged update a no-op. A changed name (create-only)
|
||||
* creates the replacement and hands the displaced balancer to the replacement cleanup.
|
||||
*/
|
||||
private void provisionLoadBalancer(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String name = nameOrPrior(ctx.resolveOptional(props, "Name"), r.getAttributes().get("LoadBalancerName"),
|
||||
ctx, r.getLogicalId());
|
||||
String scheme = ctx.resolveOptional(props, "Scheme");
|
||||
String type = ctx.resolveOptional(props, "Type");
|
||||
String ipAddressType = ctx.resolveOptional(props, "IpAddressType");
|
||||
List<String> subnets = ctx.resolveStringList(props, "Subnets");
|
||||
List<String> securityGroups = ctx.resolveStringList(props, "SecurityGroups");
|
||||
Map<String, String> tags = ctx.resolveTags(props, "Tags");
|
||||
|
||||
LoadBalancer lb;
|
||||
try {
|
||||
lb = elbV2Service.createLoadBalancer(ctx.region(), name, scheme, type, ipAddressType,
|
||||
subnets, securityGroups, tags);
|
||||
} catch (AwsException e) {
|
||||
if (!"DuplicateLoadBalancerName".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
lb = elbV2Service.describeLoadBalancers(ctx.region(), null, List.of(name), null, null).get(0);
|
||||
}
|
||||
|
||||
r.setPhysicalId(lb.getLoadBalancerArn());
|
||||
r.getAttributes().put("LoadBalancerArn", lb.getLoadBalancerArn());
|
||||
r.getAttributes().put("DNSName", lb.getDnsName());
|
||||
r.getAttributes().put("CanonicalHostedZoneID", lb.getCanonicalHostedZoneId());
|
||||
r.getAttributes().put("LoadBalancerName", lb.getLoadBalancerName());
|
||||
r.getAttributes().put("LoadBalancerFullName", loadBalancerFullName(lb.getLoadBalancerArn()));
|
||||
}
|
||||
|
||||
private void provisionTargetGroup(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String name = nameOrPrior(ctx.resolveOptional(props, "Name"), r.getAttributes().get("TargetGroupName"),
|
||||
ctx, r.getLogicalId());
|
||||
String protocol = ctx.resolveOptional(props, "Protocol");
|
||||
String protocolVersion = ctx.resolveOptional(props, "ProtocolVersion");
|
||||
Integer port = parseIntOrNull(ctx.resolveOptional(props, "Port"));
|
||||
String vpcId = ctx.resolveOptional(props, "VpcId");
|
||||
String targetType = ctx.resolveOptional(props, "TargetType");
|
||||
String hcProtocol = ctx.resolveOptional(props, "HealthCheckProtocol");
|
||||
String hcPort = ctx.resolveOptional(props, "HealthCheckPort");
|
||||
Boolean hcEnabled = parseBooleanOrNull(ctx.resolveOptional(props, "HealthCheckEnabled"));
|
||||
String hcPath = ctx.resolveOptional(props, "HealthCheckPath");
|
||||
Integer hcInterval = parseIntOrNull(ctx.resolveOptional(props, "HealthCheckIntervalSeconds"));
|
||||
Integer hcTimeout = parseIntOrNull(ctx.resolveOptional(props, "HealthCheckTimeoutSeconds"));
|
||||
Integer healthyThreshold = parseIntOrNull(ctx.resolveOptional(props, "HealthyThresholdCount"));
|
||||
Integer unhealthyThreshold = parseIntOrNull(ctx.resolveOptional(props, "UnhealthyThresholdCount"));
|
||||
String matcher = parseMatcher(props, ctx);
|
||||
String ipAddressType = ctx.resolveOptional(props, "IpAddressType");
|
||||
Map<String, String> tags = ctx.resolveTags(props, "Tags");
|
||||
|
||||
TargetGroup tg;
|
||||
try {
|
||||
tg = elbV2Service.createTargetGroup(ctx.region(), name, protocol, protocolVersion, port, vpcId, targetType,
|
||||
hcProtocol, hcPort, hcEnabled, hcPath, hcInterval, hcTimeout,
|
||||
healthyThreshold, unhealthyThreshold, matcher, ipAddressType, tags);
|
||||
} catch (AwsException e) {
|
||||
if (!"DuplicateTargetGroupName".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
tg = elbV2Service.describeTargetGroups(ctx.region(), null, null, List.of(name)).get(0);
|
||||
}
|
||||
|
||||
r.setPhysicalId(tg.getTargetGroupArn());
|
||||
r.getAttributes().put("TargetGroupArn", tg.getTargetGroupArn());
|
||||
r.getAttributes().put("TargetGroupName", tg.getTargetGroupName());
|
||||
r.getAttributes().put("TargetGroupFullName", targetGroupFullName(tg.getTargetGroupArn()));
|
||||
// A list-valued attribute, joined the way Route53's NameServers is. Empty until a listener
|
||||
// forwards to the group, as on AWS.
|
||||
r.getAttributes().put("LoadBalancerArns", String.join(",", tg.getLoadBalancerArns()));
|
||||
}
|
||||
|
||||
/**
|
||||
* LoadBalancerArn is create-only: an update that keeps it modifies the listener the stack
|
||||
* already owns, one that moves the listener to another balancer creates a replacement and the
|
||||
* displaced listener is deleted once the stack update commits.
|
||||
*/
|
||||
private void provisionListener(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String lbArn = ctx.resolveOptional(props, "LoadBalancerArn");
|
||||
String protocol = resolveOrDefault(props, "Protocol", ctx, "HTTP");
|
||||
int port = parseInt(ctx.resolveOptional(props, "Port"), "Port", 80);
|
||||
String sslPolicy = ctx.resolveOptional(props, "SslPolicy");
|
||||
List<String> certificates = parseCertificates(props, ctx);
|
||||
List<Action> defaultActions = parseActions(props != null ? props.get("DefaultActions") : null, ctx);
|
||||
|
||||
Listener listener;
|
||||
Listener prior = ctx.isUpdate() ? priorListener(ctx) : null;
|
||||
if (prior != null && (lbArn == null || lbArn.equals(prior.getLoadBalancerArn()))) {
|
||||
listener = elbV2Service.modifyListener(ctx.region(), ctx.priorPhysicalId(), protocol, port, sslPolicy,
|
||||
certificates, defaultActions, null);
|
||||
} else {
|
||||
listener = elbV2Service.createListener(ctx.region(), lbArn, protocol, port, sslPolicy, certificates,
|
||||
defaultActions, null, Map.of());
|
||||
}
|
||||
|
||||
r.setPhysicalId(listener.getListenerArn());
|
||||
r.getAttributes().put("ListenerArn", listener.getListenerArn());
|
||||
}
|
||||
|
||||
/**
|
||||
* ListenerArn is create-only: an update that keeps it modifies the rule the stack already owns,
|
||||
* one that moves the rule to another listener creates a replacement and the displaced rule is
|
||||
* deleted once the stack update commits.
|
||||
*/
|
||||
private void provisionListenerRule(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String listenerArn = ctx.resolveOptional(props, "ListenerArn");
|
||||
int priority = parseInt(ctx.resolveOptional(props, "Priority"), "Priority", 1);
|
||||
List<RuleCondition> conditions = parseRuleConditions(props != null ? props.get("Conditions") : null, ctx);
|
||||
List<Action> actions = parseActions(props != null ? props.get("Actions") : null, ctx);
|
||||
|
||||
Rule rule;
|
||||
Rule prior = ctx.isUpdate() ? priorRule(ctx) : null;
|
||||
if (prior != null && (listenerArn == null || listenerArn.equals(prior.getListenerArn()))) {
|
||||
rule = elbV2Service.modifyRule(ctx.region(), ctx.priorPhysicalId(), conditions, actions);
|
||||
} else {
|
||||
rule = elbV2Service.createRule(ctx.region(), listenerArn, conditions, priority, actions, Map.of());
|
||||
}
|
||||
|
||||
r.setPhysicalId(rule.getRuleArn());
|
||||
r.getAttributes().put("RuleArn", rule.getRuleArn());
|
||||
r.getAttributes().put("IsDefault", String.valueOf(rule.isDefault()));
|
||||
}
|
||||
|
||||
/** The listener the stack points at, or null when it was removed out of band (then create). */
|
||||
private Listener priorListener(ProvisionContext ctx) {
|
||||
try {
|
||||
return elbV2Service.describeListeners(ctx.region(), null, List.of(ctx.priorPhysicalId()))
|
||||
.stream().findFirst().orElse(null);
|
||||
} catch (AwsException e) {
|
||||
if (!"ListenerNotFound".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
LOG.debugv("Listener {0} no longer exists, creating it again", ctx.priorPhysicalId());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private Rule priorRule(ProvisionContext ctx) {
|
||||
try {
|
||||
return elbV2Service.describeRules(ctx.region(), null, List.of(ctx.priorPhysicalId()))
|
||||
.stream().findFirst().orElse(null);
|
||||
} catch (AwsException e) {
|
||||
if (!"RuleNotFound".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
LOG.debugv("Rule {0} no longer exists, creating it again", ctx.priorPhysicalId());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String nameOrPrior(String declared, String prior, ProvisionContext ctx, String logicalId) {
|
||||
if (declared != null && !declared.isBlank()) {
|
||||
return declared;
|
||||
}
|
||||
if (prior != null && !prior.isBlank()) {
|
||||
return prior;
|
||||
}
|
||||
return generateElbName(ctx.stackName(), logicalId);
|
||||
}
|
||||
|
||||
/** ELBv2 names: at most 32 characters of {@code [A-Za-z0-9-]}, no leading or trailing hyphen. */
|
||||
private static String generateElbName(String stackName, String logicalId) {
|
||||
String base = (stackName + "-" + logicalId).replaceAll("[^A-Za-z0-9-]", "");
|
||||
String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
|
||||
int maxBase = 32 - 1 - suffix.length();
|
||||
if (base.length() > maxBase) {
|
||||
base = base.substring(0, maxBase);
|
||||
}
|
||||
base = base.replaceAll("-+$", "");
|
||||
if (base.isEmpty()) {
|
||||
base = "elb";
|
||||
}
|
||||
return base + "-" + suffix;
|
||||
}
|
||||
|
||||
/** The ARN resource is {@code loadbalancer/<type>/<name>/<id>}; the full name drops the prefix. */
|
||||
private static String loadBalancerFullName(String lbArn) {
|
||||
String resource = AwsArnUtils.parse(lbArn).resource();
|
||||
String prefix = "loadbalancer/";
|
||||
return resource.startsWith(prefix) ? resource.substring(prefix.length()) : resource;
|
||||
}
|
||||
|
||||
/** The target group full name keeps its prefix: {@code targetgroup/<name>/<id>}. */
|
||||
private static String targetGroupFullName(String tgArn) {
|
||||
return AwsArnUtils.parse(tgArn).resource();
|
||||
}
|
||||
|
||||
private static String parseMatcher(JsonNode props, ProvisionContext ctx) {
|
||||
if (props == null || !props.has("Matcher") || props.get("Matcher").isNull()) {
|
||||
return null;
|
||||
}
|
||||
JsonNode m = ctx.engine().resolveNode(props.get("Matcher"));
|
||||
if (m.hasNonNull("HttpCode")) {
|
||||
return m.path("HttpCode").asText();
|
||||
}
|
||||
if (m.hasNonNull("GrpcCode")) {
|
||||
return m.path("GrpcCode").asText();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static List<String> parseCertificates(JsonNode props, ProvisionContext ctx) {
|
||||
List<String> result = new ArrayList<>();
|
||||
if (props == null || !props.has("Certificates") || props.get("Certificates").isNull()) {
|
||||
return result;
|
||||
}
|
||||
JsonNode resolved = ctx.engine().resolveNode(props.get("Certificates"));
|
||||
if (resolved.isArray()) {
|
||||
for (JsonNode c : resolved) {
|
||||
if (c.hasNonNull("CertificateArn")) {
|
||||
result.add(c.path("CertificateArn").asText());
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static List<Action> parseActions(JsonNode node, ProvisionContext ctx) {
|
||||
List<Action> result = new ArrayList<>();
|
||||
if (node == null || node.isNull()) {
|
||||
return result;
|
||||
}
|
||||
JsonNode resolved = ctx.engine().resolveNode(node);
|
||||
if (!resolved.isArray()) {
|
||||
return result;
|
||||
}
|
||||
for (JsonNode item : resolved) {
|
||||
Action action = new Action();
|
||||
action.setType(textOrNull(item, "Type"));
|
||||
if (item.hasNonNull("Order")) {
|
||||
action.setOrder(item.path("Order").asInt());
|
||||
}
|
||||
if (item.hasNonNull("TargetGroupArn")) {
|
||||
action.setTargetGroupArn(item.path("TargetGroupArn").asText());
|
||||
}
|
||||
JsonNode forward = item.path("ForwardConfig");
|
||||
if (forward.isObject()) {
|
||||
JsonNode tgs = forward.path("TargetGroups");
|
||||
if (tgs.isArray()) {
|
||||
List<Action.TargetGroupTuple> tuples = new ArrayList<>();
|
||||
for (JsonNode t : tgs) {
|
||||
Action.TargetGroupTuple tuple = new Action.TargetGroupTuple();
|
||||
if (t.hasNonNull("TargetGroupArn")) {
|
||||
tuple.setTargetGroupArn(t.path("TargetGroupArn").asText());
|
||||
}
|
||||
if (t.hasNonNull("Weight")) {
|
||||
tuple.setWeight(t.path("Weight").asInt());
|
||||
}
|
||||
tuples.add(tuple);
|
||||
}
|
||||
action.setTargetGroups(tuples);
|
||||
}
|
||||
JsonNode stickiness = forward.path("TargetGroupStickinessConfig");
|
||||
if (stickiness.isObject()) {
|
||||
if (stickiness.hasNonNull("Enabled")) {
|
||||
action.setStickinessEnabled(stickiness.path("Enabled").asBoolean());
|
||||
}
|
||||
if (stickiness.hasNonNull("DurationSeconds")) {
|
||||
action.setStickinessDurationSeconds(stickiness.path("DurationSeconds").asInt());
|
||||
}
|
||||
}
|
||||
}
|
||||
JsonNode redirect = item.path("RedirectConfig");
|
||||
if (redirect.isObject()) {
|
||||
action.setRedirectProtocol(textOrNull(redirect, "Protocol"));
|
||||
action.setRedirectPort(textOrNull(redirect, "Port"));
|
||||
action.setRedirectHost(textOrNull(redirect, "Host"));
|
||||
action.setRedirectPath(textOrNull(redirect, "Path"));
|
||||
action.setRedirectQuery(textOrNull(redirect, "Query"));
|
||||
action.setRedirectStatusCode(textOrNull(redirect, "StatusCode"));
|
||||
}
|
||||
JsonNode fixed = item.path("FixedResponseConfig");
|
||||
if (fixed.isObject()) {
|
||||
action.setFixedResponseStatusCode(textOrNull(fixed, "StatusCode"));
|
||||
action.setFixedResponseContentType(textOrNull(fixed, "ContentType"));
|
||||
action.setFixedResponseMessageBody(textOrNull(fixed, "MessageBody"));
|
||||
}
|
||||
result.add(action);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static List<RuleCondition> parseRuleConditions(JsonNode node, ProvisionContext ctx) {
|
||||
List<RuleCondition> result = new ArrayList<>();
|
||||
if (node == null || node.isNull()) {
|
||||
return result;
|
||||
}
|
||||
JsonNode resolved = ctx.engine().resolveNode(node);
|
||||
if (!resolved.isArray()) {
|
||||
return result;
|
||||
}
|
||||
for (JsonNode item : resolved) {
|
||||
RuleCondition condition = new RuleCondition();
|
||||
condition.setField(textOrNull(item, "Field"));
|
||||
if (item.path("Values").isArray()) {
|
||||
condition.setValues(toStringList(item.path("Values")));
|
||||
}
|
||||
JsonNode pathCfg = item.path("PathPatternConfig");
|
||||
if (pathCfg.path("Values").isArray()) {
|
||||
condition.setPathPatternValues(toStringList(pathCfg.path("Values")));
|
||||
}
|
||||
JsonNode hostCfg = item.path("HostHeaderConfig");
|
||||
if (hostCfg.path("Values").isArray()) {
|
||||
condition.setHostHeaderValues(toStringList(hostCfg.path("Values")));
|
||||
}
|
||||
JsonNode httpHeaderCfg = item.path("HttpHeaderConfig");
|
||||
if (httpHeaderCfg.isObject()) {
|
||||
condition.setHttpHeaderName(textOrNull(httpHeaderCfg, "HttpHeaderName"));
|
||||
if (httpHeaderCfg.path("Values").isArray()) {
|
||||
condition.setHttpHeaderValues(toStringList(httpHeaderCfg.path("Values")));
|
||||
}
|
||||
}
|
||||
JsonNode methodCfg = item.path("HttpRequestMethodConfig");
|
||||
if (methodCfg.path("Values").isArray()) {
|
||||
condition.setHttpMethodValues(toStringList(methodCfg.path("Values")));
|
||||
}
|
||||
JsonNode sourceIpCfg = item.path("SourceIpConfig");
|
||||
if (sourceIpCfg.path("Values").isArray()) {
|
||||
condition.setSourceIpValues(toStringList(sourceIpCfg.path("Values")));
|
||||
}
|
||||
JsonNode queryCfg = item.path("QueryStringConfig");
|
||||
if (queryCfg.path("Values").isArray()) {
|
||||
List<RuleCondition.QueryStringPair> pairs = new ArrayList<>();
|
||||
for (JsonNode q : queryCfg.path("Values")) {
|
||||
RuleCondition.QueryStringPair pair = new RuleCondition.QueryStringPair();
|
||||
pair.setKey(textOrNull(q, "Key"));
|
||||
pair.setValue(textOrNull(q, "Value"));
|
||||
pairs.add(pair);
|
||||
}
|
||||
condition.setQueryStringValues(pairs);
|
||||
}
|
||||
result.add(condition);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String resolveOrDefault(JsonNode props, String name, ProvisionContext ctx, String fallback) {
|
||||
String value = ctx.resolveOptional(props, name);
|
||||
return value != null && !value.isBlank() ? value : fallback;
|
||||
}
|
||||
|
||||
/** An absent value takes the default; anything present has to be an integer. */
|
||||
private static int parseInt(String value, String property, int fallback) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return fallback;
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(value.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
throw new AwsException("ValidationError", "Value of property " + property + " must be an integer.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/** The switch treated an unparsable optional integer as unset; kept so a stray value does not fail a stack. */
|
||||
private static Integer parseIntOrNull(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Integer.valueOf(value.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
LOG.debugv("Ignoring non-integer value {0}", value);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static Boolean parseBooleanOrNull(String value) {
|
||||
return value == null || value.isBlank() ? null : Boolean.valueOf(value);
|
||||
}
|
||||
|
||||
private static String textOrNull(JsonNode node, String field) {
|
||||
return node != null && node.hasNonNull(field) ? node.path(field).asText() : null;
|
||||
}
|
||||
|
||||
private static List<String> toStringList(JsonNode node) {
|
||||
List<String> result = new ArrayList<>();
|
||||
if (node != null && node.isArray()) {
|
||||
node.forEach(v -> result.add(v.asText()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+32
-22
@@ -107,9 +107,9 @@ final class ReplacementCleanup {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
deleter.delete(r.getResourceType(), replacement, region(cleanup, r));
|
||||
deleter.delete(r.getResourceType(), replacement, region(cleanup));
|
||||
} catch (RuntimeException deleteFailure) {
|
||||
addDisplaced(cleanup, replacement, r.getResourceType(), region(cleanup, r), false);
|
||||
addDisplaced(cleanup, replacement, r.getResourceType(), region(cleanup), false);
|
||||
write(r, cleanup);
|
||||
throw deleteFailure;
|
||||
}
|
||||
@@ -122,22 +122,38 @@ final class ReplacementCleanup {
|
||||
}
|
||||
|
||||
/**
|
||||
* The first entity still owed a delete, or null when none is or {@code UpdateReplacePolicy:
|
||||
* Retain} keeps it. The engine announces one physical id per resource, so a resource owing
|
||||
* more than one names the first; the rest are deleted in the same cleanup.
|
||||
* The entity the cleanup is working on, or null when none is owed or {@code UpdateReplacePolicy:
|
||||
* Retain} keeps it. The engine announces one physical id per resource, so a resource owing more
|
||||
* than one names the one with the fewest attempts, the same entity {@link #complete} reports,
|
||||
* so the progress and failure events of one cleanup name the same thing.
|
||||
*/
|
||||
static String cleanupPhysicalId(StackResource r) {
|
||||
ObjectNode cleanup = read(r);
|
||||
if (cleanup == null) {
|
||||
return null;
|
||||
}
|
||||
boolean retain = "Retain".equals(r.getUpdateReplacePolicy());
|
||||
for (JsonNode entry : cleanup.path("displaced")) {
|
||||
if (!(retain && entry.path("retainable").asBoolean(false))) {
|
||||
return entry.path("physicalId").asText(null);
|
||||
JsonNode next = nextOwed(cleanup.path("displaced"), r.getPhysicalId(), "Retain".equals(r.getUpdateReplacePolicy()));
|
||||
return next == null ? null : next.path("physicalId").asText(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The owed entry with the fewest attempts, ties by list order: the one the engine's retries are
|
||||
* still for. Skips the resource's own entity and, under Retain, the entities a committed
|
||||
* replacement displaced.
|
||||
*/
|
||||
private static JsonNode nextOwed(JsonNode displaced, String currentPhysicalId, boolean retain) {
|
||||
JsonNode next = null;
|
||||
for (JsonNode entry : displaced) {
|
||||
String physicalId = entry.path("physicalId").asText(null);
|
||||
if (physicalId == null || physicalId.equals(currentPhysicalId)
|
||||
|| (retain && entry.path("retainable").asBoolean(false))) {
|
||||
continue;
|
||||
}
|
||||
if (next == null || entry.path("cleanupAttempts").asInt(0) < next.path("cleanupAttempts").asInt(0)) {
|
||||
next = entry;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -186,9 +202,6 @@ final class ReplacementCleanup {
|
||||
boolean retain = "Retain".equals(r.getUpdateReplacePolicy());
|
||||
ArrayNode displaced = cleanup.withArray("displaced");
|
||||
ArrayNode remaining = MAPPER.createArrayNode();
|
||||
int attempts = Integer.MAX_VALUE;
|
||||
String failureReason = null;
|
||||
String firstRemaining = null;
|
||||
for (JsonNode node : displaced) {
|
||||
ObjectNode entry = (ObjectNode) node;
|
||||
String physicalId = entry.path("physicalId").asText(null);
|
||||
@@ -209,20 +222,17 @@ final class ReplacementCleanup {
|
||||
}
|
||||
}
|
||||
remaining.add(entry);
|
||||
// The result names the entity with the fewest attempts, the one the engine's retries
|
||||
// are still for, so its DELETE_FAILED event points at what is actually still owed.
|
||||
if (entryAttempts < attempts) {
|
||||
attempts = entryAttempts;
|
||||
failureReason = entry.path("cleanupFailureReason").asText(null);
|
||||
firstRemaining = physicalId;
|
||||
}
|
||||
}
|
||||
cleanup.set("displaced", remaining);
|
||||
write(r, cleanup);
|
||||
if (remaining.isEmpty()) {
|
||||
return new UpdateCleanupResult(true, true, firstDisplaced(displaced), 0, null);
|
||||
}
|
||||
return new UpdateCleanupResult(true, false, firstRemaining, attempts, failureReason);
|
||||
// The result names the entity with the fewest attempts, the one the engine's retries are
|
||||
// still for and the one cleanupPhysicalId announced, so both events point at the same thing.
|
||||
JsonNode next = nextOwed(remaining, r.getPhysicalId(), retain);
|
||||
return new UpdateCleanupResult(true, false, next.path("physicalId").asText(null),
|
||||
next.path("cleanupAttempts").asInt(0), next.path("cleanupFailureReason").asText(null));
|
||||
}
|
||||
|
||||
private static String firstDisplaced(ArrayNode displaced) {
|
||||
@@ -257,7 +267,7 @@ final class ReplacementCleanup {
|
||||
kept.forEach(displaced::add);
|
||||
}
|
||||
|
||||
private static String region(ObjectNode cleanup, StackResource r) {
|
||||
private static String region(ObjectNode cleanup) {
|
||||
return cleanup.path("region").asText(null);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user