mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(cloudformation): provision Application Auto Scaling targets and policies (#5407)
* feat(cloudformation): provision Application Auto Scaling targets and policies AWS::ApplicationAutoScaling::ScalableTarget and ::ScalingPolicy had no provisioner, so a template that scales an ECS service failed on those two resources although the Application Auto Scaling service behind them, including the ECS capacity adjuster, was already there. This wires the two together. A scalable target has no name of its own: it is keyed by the triple of service namespace, resource id and scalable dimension, and CloudFormation's Ref is those three joined by a pipe. That composite is the physical id, which is also what a policy's ScalingTargetId carries when a template points one at the other with Ref, so the provisioner splits it back into the triple. A policy's Ref is its ARN rather than its name, so deleting one resolves the ARN through findPolicyByArn to recover the name and triple the service deletes by. Because the target's id is derived from the triple, changing any part of it replaces the target rather than updating it, so both types go through ReplacementCleanup to deregister what they displaced. Deletes tolerate only ObjectNotFoundException through CfnDeletes.safeDelete: a target takes its own policies with it, so a stack teardown reaches an already-deleted policy by ordinary ordering, while any other failure still surfaces as DELETE_FAILED. The properties each schema marks required are enforced rather than defaulted. MinCapacity and MaxCapacity on a target, and PolicyName and PolicyType on a policy, would otherwise register a target that never scales or accept a template CloudFormation itself rejects. The two scaling configuration blocks are parsed by the same code the PutScalingPolicy API path uses, extracted to ScalingConfigurationParser, since CloudFormation spells their members exactly as the API does. One parser means a template and an API call cannot disagree about what a policy means. ScheduledActions on a target is logged rather than dropped silently: Floci does not run scheduled scaling, and a template that scales on a clock should not look fully provisioned when nothing is scheduled. * fix(cloudformation): resolve intrinsics inside the scaling configuration blocks Review on #5407: the two scaling configuration blocks and SuspendedState reached the parser as raw template JSON, so an intrinsic inside one was never resolved. That is worse than it sounds, because an intrinsic is still a non-null node: hasNonNull passes and the value is read with asDouble, asText or asBoolean, which answer 0, "" and false. A policy written as TargetValue: !Ref TargetCpu registered as a policy targeting 0 percent rather than failing, a ResourceLabel built with Fn::Join arrived empty, and a flag behind Fn::If read false. Each block now goes through ctx.engine().resolveNode first, which is what AutoScalingScalingPolicyCfnProvisioner already does with its own block. Only nested objects were affected: the top-level properties were already read through ctx.resolveOptional, which resolves. A target's Tags were dropped as well, passed to the service as an empty map rather than read with ctx.resolveTags. ScheduledActions now carries a note in the generated resource-type table rather than only a warning in the log, so the gap is visible before someone wonders why their clock-based scaling never fires. * test(cloudformation): make the SuspendedState intrinsic test fail without its fix Review on #5407: anIntrinsicInsideSuspendedStateIsResolvedToo passed against the previous commit too. REFS had no Suspend entry, so the flag resolved to an empty string and read false either way, and assertNotNull held regardless because the raw block was already an object. The test pinned nothing. REFS now maps Suspend to true and the assertion is on isDynamicScalingInSuspended(), so it fails with expected: <true> but was: <false> when SuspendedState is read without resolveNode. The redundant copy of the properties node is gone.
This commit is contained in:
1 parent
3ad1a76507
commit
bfa9c2fbcc
10 files changed
+853
-60
No files matched your search
@@ -144,6 +144,7 @@ cross-resource references.
|
||||
| EC2 | `VPC`, `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway`, `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog` |
|
||||
| Elastic Load Balancing v2 | `LoadBalancer`, `TargetGroup`, `Listener`, `ListenerRule` |
|
||||
| Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup`, `LifecycleHook`, `ScalingPolicy` |
|
||||
| Application Auto Scaling | `ScalableTarget` (`ScheduledActions` are accepted and not run; Floci has no scheduled scaling), `ScalingPolicy` |
|
||||
| Route 53 | `HostedZone`, `RecordSet` |
|
||||
| Cloud Map | `HttpNamespace`, `PrivateDnsNamespace`, `PublicDnsNamespace`, `Service` |
|
||||
| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer`, `Method`, `Deployment`, `Stage`, `Account`, `DomainName`, `BasePathMapping`, `GatewayResponse`, `ApiKey`, `UsagePlan`, `UsagePlanKey` |
|
||||
|
||||
+2
-57
@@ -331,66 +331,11 @@ public class ApplicationAutoScalingJsonHandler {
|
||||
}
|
||||
|
||||
private TargetTrackingConfiguration parseTargetTracking(JsonNode node) {
|
||||
if (node == null || node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
TargetTrackingConfiguration config = new TargetTrackingConfiguration();
|
||||
if (node.hasNonNull("TargetValue")) {
|
||||
config.setTargetValue(node.get("TargetValue").asDouble());
|
||||
}
|
||||
JsonNode predefined = node.path("PredefinedMetricSpecification");
|
||||
if (predefined.isObject()) {
|
||||
PredefinedMetricSpecification spec = new PredefinedMetricSpecification();
|
||||
spec.setPredefinedMetricType(text(predefined, "PredefinedMetricType"));
|
||||
spec.setResourceLabel(text(predefined, "ResourceLabel"));
|
||||
config.setPredefinedMetricSpecification(spec);
|
||||
}
|
||||
JsonNode customized = node.path("CustomizedMetricSpecification");
|
||||
if (customized.isObject()) {
|
||||
config.setCustomizedMetricSpecification(
|
||||
objectMapper.convertValue(customized, new com.fasterxml.jackson.core.type.TypeReference<>() {}));
|
||||
}
|
||||
if (node.hasNonNull("DisableScaleIn")) {
|
||||
config.setDisableScaleIn(node.get("DisableScaleIn").asBoolean());
|
||||
}
|
||||
if (node.hasNonNull("ScaleInCooldown")) {
|
||||
config.setScaleInCooldown(node.get("ScaleInCooldown").asInt());
|
||||
}
|
||||
if (node.hasNonNull("ScaleOutCooldown")) {
|
||||
config.setScaleOutCooldown(node.get("ScaleOutCooldown").asInt());
|
||||
}
|
||||
return config;
|
||||
return ScalingConfigurationParser.parseTargetTracking(node, objectMapper);
|
||||
}
|
||||
|
||||
private StepScalingConfiguration parseStepScaling(JsonNode node) {
|
||||
if (node == null || node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
StepScalingConfiguration config = new StepScalingConfiguration();
|
||||
config.setAdjustmentType(text(node, "AdjustmentType"));
|
||||
config.setMetricAggregationType(text(node, "MetricAggregationType"));
|
||||
if (node.hasNonNull("Cooldown")) {
|
||||
config.setCooldown(node.get("Cooldown").asInt());
|
||||
}
|
||||
if (node.hasNonNull("MinAdjustmentMagnitude")) {
|
||||
config.setMinAdjustmentMagnitude(node.get("MinAdjustmentMagnitude").asInt());
|
||||
}
|
||||
List<StepAdjustment> steps = new ArrayList<>();
|
||||
for (JsonNode stepNode : node.path("StepAdjustments")) {
|
||||
StepAdjustment step = new StepAdjustment();
|
||||
if (stepNode.hasNonNull("MetricIntervalLowerBound")) {
|
||||
step.setMetricIntervalLowerBound(stepNode.get("MetricIntervalLowerBound").asDouble());
|
||||
}
|
||||
if (stepNode.hasNonNull("MetricIntervalUpperBound")) {
|
||||
step.setMetricIntervalUpperBound(stepNode.get("MetricIntervalUpperBound").asDouble());
|
||||
}
|
||||
if (stepNode.hasNonNull("ScalingAdjustment")) {
|
||||
step.setScalingAdjustment(stepNode.get("ScalingAdjustment").asInt());
|
||||
}
|
||||
steps.add(step);
|
||||
}
|
||||
config.setStepAdjustments(steps);
|
||||
return config;
|
||||
return ScalingConfigurationParser.parseStepScaling(node);
|
||||
}
|
||||
|
||||
private Map<String, String> parseTags(JsonNode node) {
|
||||
|
||||
+6
-3
@@ -528,9 +528,12 @@ public class ApplicationAutoScalingService {
|
||||
return targets.get(targetKey(region, serviceNamespace, resourceId, scalableDimension));
|
||||
}
|
||||
|
||||
/** Looked up by {@link ScalingPolicyAlarmActionHandler} when an alarm's AlarmActions
|
||||
* references a scaling-policy ARN. */
|
||||
Optional<ScalingPolicy> findPolicyByArn(String policyArn, String region) {
|
||||
/**
|
||||
* Looked up by {@link ScalingPolicyAlarmActionHandler} when an alarm's AlarmActions references
|
||||
* a scaling-policy ARN, and by the CloudFormation provisioner, whose physical id for a policy
|
||||
* is that ARN while deleting one takes the triple plus the policy name.
|
||||
*/
|
||||
public Optional<ScalingPolicy> findPolicyByArn(String policyArn, String region) {
|
||||
String prefix = region + "::";
|
||||
return policies.scan(k -> k.startsWith(prefix)).stream()
|
||||
.filter(p -> policyArn.equals(p.getPolicyArn()))
|
||||
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package io.github.hectorvent.floci.services.applicationautoscaling;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.PredefinedMetricSpecification;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.StepAdjustment;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.StepScalingConfiguration;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.TargetTrackingConfiguration;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Reads the two scaling-policy configuration blocks out of JSON.
|
||||
*
|
||||
* <p>Shared by {@link ApplicationAutoScalingJsonHandler} and the CloudFormation provisioner,
|
||||
* because {@code AWS::ApplicationAutoScaling::ScalingPolicy} spells
|
||||
* {@code TargetTrackingScalingPolicyConfiguration} and {@code StepScalingPolicyConfiguration}
|
||||
* with the same member names {@code PutScalingPolicy} does. One parser means a template and an
|
||||
* API call cannot disagree about what a policy means.
|
||||
*/
|
||||
public final class ScalingConfigurationParser {
|
||||
|
||||
private ScalingConfigurationParser() {
|
||||
}
|
||||
|
||||
public static TargetTrackingConfiguration parseTargetTracking(JsonNode node, ObjectMapper mapper) {
|
||||
if (node == null || node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
TargetTrackingConfiguration config = new TargetTrackingConfiguration();
|
||||
if (node.hasNonNull("TargetValue")) {
|
||||
config.setTargetValue(node.get("TargetValue").asDouble());
|
||||
}
|
||||
JsonNode predefined = node.path("PredefinedMetricSpecification");
|
||||
if (predefined.isObject()) {
|
||||
PredefinedMetricSpecification spec = new PredefinedMetricSpecification();
|
||||
spec.setPredefinedMetricType(text(predefined, "PredefinedMetricType"));
|
||||
spec.setResourceLabel(text(predefined, "ResourceLabel"));
|
||||
config.setPredefinedMetricSpecification(spec);
|
||||
}
|
||||
JsonNode customized = node.path("CustomizedMetricSpecification");
|
||||
if (customized.isObject()) {
|
||||
config.setCustomizedMetricSpecification(mapper.convertValue(customized, new TypeReference<>() {}));
|
||||
}
|
||||
if (node.hasNonNull("DisableScaleIn")) {
|
||||
config.setDisableScaleIn(node.get("DisableScaleIn").asBoolean());
|
||||
}
|
||||
if (node.hasNonNull("ScaleInCooldown")) {
|
||||
config.setScaleInCooldown(node.get("ScaleInCooldown").asInt());
|
||||
}
|
||||
if (node.hasNonNull("ScaleOutCooldown")) {
|
||||
config.setScaleOutCooldown(node.get("ScaleOutCooldown").asInt());
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
public static StepScalingConfiguration parseStepScaling(JsonNode node) {
|
||||
if (node == null || node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
StepScalingConfiguration config = new StepScalingConfiguration();
|
||||
config.setAdjustmentType(text(node, "AdjustmentType"));
|
||||
config.setMetricAggregationType(text(node, "MetricAggregationType"));
|
||||
if (node.hasNonNull("Cooldown")) {
|
||||
config.setCooldown(node.get("Cooldown").asInt());
|
||||
}
|
||||
if (node.hasNonNull("MinAdjustmentMagnitude")) {
|
||||
config.setMinAdjustmentMagnitude(node.get("MinAdjustmentMagnitude").asInt());
|
||||
}
|
||||
List<StepAdjustment> steps = new ArrayList<>();
|
||||
for (JsonNode stepNode : node.path("StepAdjustments")) {
|
||||
StepAdjustment step = new StepAdjustment();
|
||||
if (stepNode.hasNonNull("MetricIntervalLowerBound")) {
|
||||
step.setMetricIntervalLowerBound(stepNode.get("MetricIntervalLowerBound").asDouble());
|
||||
}
|
||||
if (stepNode.hasNonNull("MetricIntervalUpperBound")) {
|
||||
step.setMetricIntervalUpperBound(stepNode.get("MetricIntervalUpperBound").asDouble());
|
||||
}
|
||||
if (stepNode.hasNonNull("ScalingAdjustment")) {
|
||||
step.setScalingAdjustment(stepNode.get("ScalingAdjustment").asInt());
|
||||
}
|
||||
steps.add(step);
|
||||
}
|
||||
config.setStepAdjustments(steps);
|
||||
return config;
|
||||
}
|
||||
|
||||
private static String text(JsonNode node, String field) {
|
||||
return node.hasNonNull(field) ? node.get(field).asText() : null;
|
||||
}
|
||||
}
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.ApplicationAutoScalingService;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.ScalingConfigurationParser;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.ScalingPolicy;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.SuspendedState;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Provisions {@code AWS::ApplicationAutoScaling::ScalableTarget} and
|
||||
* {@code AWS::ApplicationAutoScaling::ScalingPolicy}.
|
||||
*
|
||||
* <p>A target is identified by the triple (service namespace, resource id, scalable dimension)
|
||||
* rather than by a name of its own, and CloudFormation's {@code Ref} is those three joined by
|
||||
* {@code |}. That composite is this provisioner's physical id, which is also what a policy's
|
||||
* {@code ScalingTargetId} carries when a template points one at the other with {@code Ref}.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class ApplicationAutoScalingCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
static final String SCALABLE_TARGET = "AWS::ApplicationAutoScaling::ScalableTarget";
|
||||
static final String SCALING_POLICY = "AWS::ApplicationAutoScaling::ScalingPolicy";
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ApplicationAutoScalingCfnProvisioner.class);
|
||||
|
||||
private final ApplicationAutoScalingService service;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public ApplicationAutoScalingCfnProvisioner(ApplicationAutoScalingService service, ObjectMapper objectMapper) {
|
||||
this.service = service;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of(SCALABLE_TARGET, SCALING_POLICY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
if (SCALABLE_TARGET.equals(r.getResourceType())) {
|
||||
provisionTarget(r, props, ctx);
|
||||
} else {
|
||||
provisionPolicy(r, props, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
private void provisionTarget(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
Map<String, String> attributesBefore = r.getAttributes() == null
|
||||
? new HashMap<>() : new HashMap<>(r.getAttributes());
|
||||
Triple triple = Triple.fromProperties(props, ctx);
|
||||
// Required by the resource schema, so a template missing either is refused here rather
|
||||
// than registering a target with no bounds that silently never scales.
|
||||
Integer min = requiredInteger(props, "MinCapacity", ctx);
|
||||
Integer max = requiredInteger(props, "MaxCapacity", ctx);
|
||||
String roleArn = ctx.resolveOptional(props, "RoleARN");
|
||||
if (props.hasNonNull("ScheduledActions")) {
|
||||
// Floci's Application Auto Scaling has no scheduled actions, and silently dropping them
|
||||
// would let a template that scales on a clock look provisioned while nothing is scheduled.
|
||||
LOG.warnv("ScalableTarget {0} declares ScheduledActions, which Floci does not run; "
|
||||
+ "the target itself is registered", r.getLogicalId());
|
||||
}
|
||||
service.registerScalableTarget(triple.serviceNamespace(), triple.resourceId(), triple.scalableDimension(),
|
||||
min, max, roleArn, suspendedState(props, ctx), ctx.resolveTags(props, "Tags"), ctx.region());
|
||||
r.setPhysicalId(triple.composite());
|
||||
r.getAttributes().put("Id", triple.composite());
|
||||
// The id is the triple, so changing any part of it replaces the target rather than
|
||||
// updating it, and the one it displaced has to be deregistered once the update commits.
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore);
|
||||
}
|
||||
|
||||
private void provisionPolicy(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
Map<String, String> attributesBefore = r.getAttributes() == null
|
||||
? new HashMap<>() : new HashMap<>(r.getAttributes());
|
||||
// PolicyName and PolicyType are both required by the resource schema: a generated name
|
||||
// or a defaulted type would accept a template that CloudFormation itself rejects.
|
||||
String policyName = Triple.required(ctx.resolveOptional(props, "PolicyName"), "PolicyName");
|
||||
String policyType = Triple.required(ctx.resolveOptional(props, "PolicyType"), "PolicyType");
|
||||
Triple triple = Triple.forPolicy(props, ctx);
|
||||
ScalingPolicy policy = service.putScalingPolicy(policyName, policyType,
|
||||
triple.serviceNamespace(), triple.resourceId(), triple.scalableDimension(),
|
||||
// Through the engine first: these blocks are nested objects, so an intrinsic inside
|
||||
// one is still a non-null node and would read as 0, "" or false rather than failing.
|
||||
ScalingConfigurationParser.parseTargetTracking(
|
||||
ctx.engine().resolveNode(props.path("TargetTrackingScalingPolicyConfiguration")), objectMapper),
|
||||
ScalingConfigurationParser.parseStepScaling(
|
||||
ctx.engine().resolveNode(props.path("StepScalingPolicyConfiguration"))),
|
||||
ctx.region());
|
||||
// Ref on a scaling policy is its ARN, so the ARN is the physical id rather than the name.
|
||||
r.setPhysicalId(policy.getPolicyArn());
|
||||
r.getAttributes().put("Arn", policy.getPolicyArn());
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore);
|
||||
}
|
||||
|
||||
private SuspendedState suspendedState(JsonNode props, ProvisionContext ctx) {
|
||||
JsonNode node = ctx.engine().resolveNode(props.path("SuspendedState"));
|
||||
if (node == null || !node.isObject()) {
|
||||
return null;
|
||||
}
|
||||
SuspendedState state = new SuspendedState();
|
||||
if (node.hasNonNull("DynamicScalingInSuspended")) {
|
||||
state.setDynamicScalingInSuspended(node.get("DynamicScalingInSuspended").asBoolean());
|
||||
}
|
||||
if (node.hasNonNull("DynamicScalingOutSuspended")) {
|
||||
state.setDynamicScalingOutSuspended(node.get("DynamicScalingOutSuspended").asBoolean());
|
||||
}
|
||||
if (node.hasNonNull("ScheduledScalingSuspended")) {
|
||||
state.setScheduledScalingSuspended(node.get("ScheduledScalingSuspended").asBoolean());
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
private Integer requiredInteger(JsonNode props, String name, ProvisionContext ctx) {
|
||||
String value = Triple.required(ctx.resolveOptional(props, name), name);
|
||||
try {
|
||||
return Integer.valueOf(value.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
throw new AwsException("ValidationException", name + " must be an integer, got: " + value, 400);
|
||||
}
|
||||
}
|
||||
|
||||
/** The (namespace, resource id, dimension) a target is keyed by, and CloudFormation's {@code |} form of it. */
|
||||
private record Triple(String serviceNamespace, String resourceId, String scalableDimension) {
|
||||
|
||||
static Triple fromProperties(JsonNode props, ProvisionContext ctx) {
|
||||
return new Triple(required(ctx.resolveOptional(props, "ServiceNamespace"), "ServiceNamespace"),
|
||||
required(ctx.resolveOptional(props, "ResourceId"), "ResourceId"),
|
||||
required(ctx.resolveOptional(props, "ScalableDimension"), "ScalableDimension"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A policy names its target either by the three properties or by {@code ScalingTargetId},
|
||||
* which is a {@code Ref} to the target and therefore already the composite.
|
||||
*/
|
||||
static Triple forPolicy(JsonNode props, ProvisionContext ctx) {
|
||||
String targetId = ctx.resolveOptional(props, "ScalingTargetId");
|
||||
if (targetId == null || targetId.isBlank()) {
|
||||
return fromProperties(props, ctx);
|
||||
}
|
||||
String[] parts = targetId.split("\\|", -1);
|
||||
if (parts.length != 3) {
|
||||
throw new AwsException("ValidationException",
|
||||
"ScalingTargetId must be resourceId|scalableDimension|serviceNamespace, got: " + targetId, 400);
|
||||
}
|
||||
return new Triple(parts[2], parts[0], parts[1]);
|
||||
}
|
||||
|
||||
String composite() {
|
||||
return resourceId + "|" + scalableDimension + "|" + serviceNamespace;
|
||||
}
|
||||
|
||||
static String required(String value, String name) {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new AwsException("ValidationException", name + " is required.", 400);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
if (physicalId == null || physicalId.isBlank()) {
|
||||
return;
|
||||
}
|
||||
if (SCALABLE_TARGET.equals(resourceType)) {
|
||||
String[] parts = physicalId.split("\\|", -1);
|
||||
if (parts.length == 3) {
|
||||
// Deregistering takes the target's policies and their alarms with it, as on AWS.
|
||||
CfnDeletes.safeDelete("Scalable target", physicalId,
|
||||
() -> service.deregisterScalableTarget(parts[2], parts[0], parts[1], region),
|
||||
"ObjectNotFoundException");
|
||||
}
|
||||
return;
|
||||
}
|
||||
deletePolicyByArn(physicalId, region);
|
||||
}
|
||||
|
||||
/**
|
||||
* A policy's physical id is its ARN, and the service deletes by the triple plus the name, so the
|
||||
* policy is looked up by ARN rather than parsed out of it. A policy already gone, which
|
||||
* deregistering its target does, is not an error: the stack is being torn down either way.
|
||||
*/
|
||||
private void deletePolicyByArn(String policyArn, String region) {
|
||||
service.findPolicyByArn(policyArn, region).ifPresent(policy ->
|
||||
CfnDeletes.safeDelete("Scaling policy", policyArn,
|
||||
() -> service.deleteScalingPolicy(policy.getPolicyName(), policy.getServiceNamespace(),
|
||||
policy.getResourceId(), policy.getScalableDimension(), region),
|
||||
"ObjectNotFoundException"));
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.rollback(resource, this::delete);
|
||||
}
|
||||
}
|
||||
+11
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;
|
||||
import io.github.hectorvent.floci.services.acm.AcmService;
|
||||
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.ApplicationAutoScalingService;
|
||||
import io.github.hectorvent.floci.services.appsync.AppSyncService;
|
||||
import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
|
||||
import io.github.hectorvent.floci.services.backup.BackupService;
|
||||
@@ -20,6 +21,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewa
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayUsagePlanCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayV2CfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.AppSyncCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApplicationAutoScalingCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingGroupCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingLifecycleHookCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingScalingPolicyCfnProvisioner;
|
||||
@@ -186,6 +188,7 @@ final class CfnProvisionerFixture {
|
||||
private EventBridgeService eventBridgeService;
|
||||
private ApiGatewayService apiGatewayService;
|
||||
private ApiGatewayV2Service apiGatewayV2Service;
|
||||
private ApplicationAutoScalingService applicationAutoScalingService;
|
||||
private EcrService ecrService;
|
||||
private PipesService pipesService;
|
||||
private CognitoService cognitoService;
|
||||
@@ -358,6 +361,9 @@ final class CfnProvisionerFixture {
|
||||
discovered.add(new ApiGatewayGatewayResponseCfnProvisioner(apiGatewayService));
|
||||
discovered.add(new ApiGatewayRestApiCfnProvisioner(apiGatewayService, s3Service, objectMapper));
|
||||
}
|
||||
if (applicationAutoScalingService != null) {
|
||||
discovered.add(new ApplicationAutoScalingCfnProvisioner(applicationAutoScalingService, objectMapper));
|
||||
}
|
||||
if (apiGatewayV2Service != null) {
|
||||
discovered.add(new ApiGatewayV2CfnProvisioner(apiGatewayV2Service, s3Service, objectMapper));
|
||||
}
|
||||
@@ -516,6 +522,11 @@ final class CfnProvisionerFixture {
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder applicationAutoScaling(ApplicationAutoScalingService v) {
|
||||
this.applicationAutoScalingService = v;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder apiGatewayV2(ApiGatewayV2Service v) {
|
||||
this.apiGatewayV2Service = v;
|
||||
return this;
|
||||
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.config.EncoderConfig;
|
||||
import io.restassured.http.ContentType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
/**
|
||||
* End-to-end check that CloudFormation provisions Application Auto Scaling for real rather than
|
||||
* stubbing it.
|
||||
*
|
||||
* <p>An unmapped type is stubbed as {@code CREATE_COMPLETE} with a fake ARN, so asserting the
|
||||
* stack status alone would pass against a type that was never wired. These assertions are on the
|
||||
* {@code Fn::GetAtt} keys from the resource schemas ({@code Id} for the target, {@code Arn} for the
|
||||
* policy) and on the entities being visible through the Application Auto Scaling API afterwards.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationApplicationAutoScalingIntegrationTest {
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
|
||||
private static final String AAS_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/application-autoscaling/aws4_request";
|
||||
|
||||
@Test
|
||||
void createStackProvisionsAScalableTargetAndItsPolicy() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String resourceId = "service/cfn-cluster-" + suffix + "/svc";
|
||||
String stackName = "cfn-aas-stack-" + suffix;
|
||||
String policyName = "cfn-aas-policy-" + suffix;
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"Target": {
|
||||
"Type": "AWS::ApplicationAutoScaling::ScalableTarget",
|
||||
"Properties": {
|
||||
"ServiceNamespace": "ecs",
|
||||
"ResourceId": "%s",
|
||||
"ScalableDimension": "ecs:service:DesiredCount",
|
||||
"MinCapacity": 1,
|
||||
"MaxCapacity": 4
|
||||
}
|
||||
},
|
||||
"Policy": {
|
||||
"Type": "AWS::ApplicationAutoScaling::ScalingPolicy",
|
||||
"Properties": {
|
||||
"PolicyName": "%s",
|
||||
"PolicyType": "TargetTrackingScaling",
|
||||
"ScalingTargetId": {"Ref": "Target"},
|
||||
"TargetTrackingScalingPolicyConfiguration": {
|
||||
"TargetValue": 60,
|
||||
"PredefinedMetricSpecification": {
|
||||
"PredefinedMetricType": "ECSServiceAverageCPUUtilization"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"TargetId": {"Value": {"Fn::GetAtt": ["Target", "Id"]}},
|
||||
"PolicyArn": {"Value": {"Fn::GetAtt": ["Policy", "Arn"]}}
|
||||
}
|
||||
}
|
||||
""".formatted(resourceId, policyName);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
|
||||
// Ref on a scalable target is resourceId|scalableDimension|serviceNamespace, and
|
||||
// GetAtt Id is the same composite.
|
||||
.body(containsString(resourceId + "|ecs:service:DesiredCount|ecs"))
|
||||
.body(containsString(":scalingPolicy:"))
|
||||
// An unwired type resolves Fn::GetAtt to the literal "LogicalId.Attr".
|
||||
.body(not(containsString("Target.Id")))
|
||||
.body(not(containsString("Policy.Arn")));
|
||||
|
||||
given()
|
||||
.config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig()
|
||||
.encodeContentTypeAs("application/x-amz-json-1.1", ContentType.TEXT)))
|
||||
.header("Authorization", AAS_AUTH)
|
||||
.header("X-Amz-Target", "AnyScaleFrontendService.DescribeScalableTargets")
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body("{\"ServiceNamespace\":\"ecs\",\"ResourceIds\":[\"" + resourceId + "\"]}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString(resourceId))
|
||||
.body(containsString("\"MinCapacity\":1"))
|
||||
.body(containsString("\"MaxCapacity\":4"));
|
||||
|
||||
given()
|
||||
.config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig()
|
||||
.encodeContentTypeAs("application/x-amz-json-1.1", ContentType.TEXT)))
|
||||
.header("Authorization", AAS_AUTH)
|
||||
.header("X-Amz-Target", "AnyScaleFrontendService.DescribeScalingPolicies")
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body("{\"ServiceNamespace\":\"ecs\",\"ResourceId\":\"" + resourceId + "\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString(policyName))
|
||||
.body(containsString("TargetTrackingScaling"))
|
||||
// The configuration reached the service rather than being dropped on the way through.
|
||||
.body(containsString("ECSServiceAverageCPUUtilization"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingTheStackDeregistersTheTarget() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String resourceId = "service/cfn-cluster-del-" + suffix + "/svc";
|
||||
String stackName = "cfn-aas-del-stack-" + suffix;
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"Target": {
|
||||
"Type": "AWS::ApplicationAutoScaling::ScalableTarget",
|
||||
"Properties": {
|
||||
"ServiceNamespace": "ecs",
|
||||
"ResourceId": "%s",
|
||||
"ScalableDimension": "ecs:service:DesiredCount",
|
||||
"MinCapacity": 1,
|
||||
"MaxCapacity": 2
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(resourceId);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DeleteStack")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig()
|
||||
.encodeContentTypeAs("application/x-amz-json-1.1", ContentType.TEXT)))
|
||||
.header("Authorization", AAS_AUTH)
|
||||
.header("X-Amz-Target", "AnyScaleFrontendService.DescribeScalableTargets")
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body("{\"ServiceNamespace\":\"ecs\",\"ResourceIds\":[\"" + resourceId + "\"]}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(not(containsString(resourceId)));
|
||||
}
|
||||
}
|
||||
+320
@@ -0,0 +1,320 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.ApplicationAutoScalingService;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.ScalingPolicy;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.SuspendedState;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.TargetTrackingConfiguration;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
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.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The Application Auto Scaling CFN provisioner in isolation. The cases that matter are the
|
||||
* composite target id, since that is both {@code Ref} and the link a policy follows to its target,
|
||||
* and that the policy configuration blocks survive the trip from template to service unchanged.
|
||||
*/
|
||||
class ApplicationAutoScalingCfnProvisionerTest {
|
||||
|
||||
private static final String TARGET_ID = "service/my-cluster/my-service|ecs:service:DesiredCount|ecs";
|
||||
|
||||
private final ApplicationAutoScalingService service = mock(ApplicationAutoScalingService.class);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final ApplicationAutoScalingCfnProvisioner provisioner =
|
||||
new ApplicationAutoScalingCfnProvisioner(service, mapper);
|
||||
|
||||
/** Stands in for the template's parameters, so {"Ref": "TargetCpu"} has something to become. */
|
||||
private static final Map<String, String> REFS = Map.of("TargetCpu", "70", "Env", "prod", "Suspend", "true");
|
||||
|
||||
private ProvisionContext ctx() {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(inv -> {
|
||||
JsonNode node = resolveNode(inv.getArgument(0));
|
||||
return node == null || node.isNull() ? null : node.asText();
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(inv -> resolveNode(inv.getArgument(0)));
|
||||
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
|
||||
}
|
||||
|
||||
/** The engine's job in miniature: replace every {"Ref": name} anywhere in the tree. */
|
||||
private JsonNode resolveNode(JsonNode node) {
|
||||
if (node == null || node.isNull() || node.isMissingNode()) {
|
||||
return node;
|
||||
}
|
||||
if (node.isObject()) {
|
||||
JsonNode ref = node.get("Ref");
|
||||
if (ref != null && node.size() == 1) {
|
||||
return mapper.getNodeFactory().textNode(REFS.getOrDefault(ref.asText(), ""));
|
||||
}
|
||||
ObjectNode out = mapper.createObjectNode();
|
||||
node.fields().forEachRemaining(e -> out.set(e.getKey(), resolveNode(e.getValue())));
|
||||
return out;
|
||||
}
|
||||
if (node.isArray()) {
|
||||
ArrayNode out = mapper.createArrayNode();
|
||||
node.forEach(child -> out.add(resolveNode(child)));
|
||||
return out;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private StackResource resource(String type, String logicalId) {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId(logicalId);
|
||||
r.setResourceType(type);
|
||||
r.setAttributes(new HashMap<>());
|
||||
return r;
|
||||
}
|
||||
|
||||
private ObjectNode targetProps() {
|
||||
return mapper.createObjectNode()
|
||||
.put("ServiceNamespace", "ecs")
|
||||
.put("ResourceId", "service/my-cluster/my-service")
|
||||
.put("ScalableDimension", "ecs:service:DesiredCount")
|
||||
.put("MinCapacity", 1)
|
||||
.put("MaxCapacity", 4);
|
||||
}
|
||||
|
||||
private ScalingPolicy aPolicy(String arn) {
|
||||
ScalingPolicy policy = new ScalingPolicy();
|
||||
policy.setPolicyArn(arn);
|
||||
policy.setPolicyName("cpu-target-tracking");
|
||||
policy.setServiceNamespace("ecs");
|
||||
policy.setResourceId("service/my-cluster/my-service");
|
||||
policy.setScalableDimension("ecs:service:DesiredCount");
|
||||
return policy;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aScalableTargetRegistersAndRefsAsTheCompositeId() {
|
||||
StackResource r = resource(ApplicationAutoScalingCfnProvisioner.SCALABLE_TARGET, "Target");
|
||||
|
||||
provisioner.provision(r, targetProps(), ctx());
|
||||
|
||||
verify(service).registerScalableTarget("ecs", "service/my-cluster/my-service",
|
||||
"ecs:service:DesiredCount", 1, 4, null, null, java.util.Map.of(), "us-east-1");
|
||||
// CloudFormation's Ref for a scalable target is resourceId|scalableDimension|serviceNamespace.
|
||||
assertEquals(TARGET_ID, r.getPhysicalId());
|
||||
assertEquals(TARGET_ID, r.getAttributes().get("Id"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPolicyFollowsScalingTargetIdBackToItsTargetsTriple() {
|
||||
when(service.putScalingPolicy(any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(aPolicy("arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:abc"));
|
||||
StackResource r = resource(ApplicationAutoScalingCfnProvisioner.SCALING_POLICY, "Policy");
|
||||
ObjectNode props = mapper.createObjectNode()
|
||||
.put("PolicyName", "cpu-target-tracking")
|
||||
.put("PolicyType", "TargetTrackingScaling")
|
||||
// What `Ref: ServerpublicapiScalableTarget` resolves to.
|
||||
.put("ScalingTargetId", TARGET_ID);
|
||||
props.putObject("TargetTrackingScalingPolicyConfiguration")
|
||||
.put("TargetValue", 60)
|
||||
.putObject("PredefinedMetricSpecification")
|
||||
.put("PredefinedMetricType", "ECSServiceAverageCPUUtilization");
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
|
||||
verify(service).putScalingPolicy(eq("cpu-target-tracking"), eq("TargetTrackingScaling"),
|
||||
eq("ecs"), eq("service/my-cluster/my-service"), eq("ecs:service:DesiredCount"),
|
||||
any(), isNull(), eq("us-east-1"));
|
||||
// Ref on a scaling policy is its ARN, not its name.
|
||||
assertEquals("arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:abc", r.getPhysicalId());
|
||||
assertEquals("arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:abc", r.getAttributes().get("Arn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTargetTrackingConfigurationReachesTheServiceIntact() {
|
||||
when(service.putScalingPolicy(any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(aPolicy("arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:abc"));
|
||||
StackResource r = resource(ApplicationAutoScalingCfnProvisioner.SCALING_POLICY, "Policy");
|
||||
ObjectNode props = mapper.createObjectNode()
|
||||
.put("PolicyName", "cpu")
|
||||
.put("PolicyType", "TargetTrackingScaling")
|
||||
.put("ScalingTargetId", TARGET_ID);
|
||||
props.putObject("TargetTrackingScalingPolicyConfiguration")
|
||||
.put("TargetValue", 60)
|
||||
.put("ScaleInCooldown", 300)
|
||||
.putObject("PredefinedMetricSpecification")
|
||||
.put("PredefinedMetricType", "ECSServiceAverageCPUUtilization");
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
|
||||
ArgumentCaptor<TargetTrackingConfiguration> captor =
|
||||
ArgumentCaptor.forClass(TargetTrackingConfiguration.class);
|
||||
verify(service).putScalingPolicy(any(), any(), any(), any(), any(), captor.capture(), isNull(), any());
|
||||
assertEquals(60.0, captor.getValue().getTargetValue());
|
||||
assertEquals(300, captor.getValue().getScaleInCooldown());
|
||||
assertEquals("ECSServiceAverageCPUUtilization",
|
||||
captor.getValue().getPredefinedMetricSpecification().getPredefinedMetricType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPolicyMayNameItsTargetDirectlyInsteadOfReferencingIt() {
|
||||
when(service.putScalingPolicy(any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(aPolicy("arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:abc"));
|
||||
StackResource r = resource(ApplicationAutoScalingCfnProvisioner.SCALING_POLICY, "Policy");
|
||||
ObjectNode props = targetProps().put("PolicyName", "step").put("PolicyType", "StepScaling");
|
||||
props.putObject("StepScalingPolicyConfiguration").put("AdjustmentType", "ChangeInCapacity");
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
|
||||
verify(service).putScalingPolicy(eq("step"), eq("StepScaling"), eq("ecs"),
|
||||
eq("service/my-cluster/my-service"), eq("ecs:service:DesiredCount"),
|
||||
isNull(), any(), eq("us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aScalingTargetIdThatIsNotTheCompositeIsRefused() {
|
||||
StackResource r = resource(ApplicationAutoScalingCfnProvisioner.SCALING_POLICY, "Policy");
|
||||
ObjectNode props = mapper.createObjectNode()
|
||||
.put("PolicyName", "cpu")
|
||||
.put("PolicyType", "TargetTrackingScaling")
|
||||
.put("ScalingTargetId", "just-a-service-name");
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
|
||||
assertTrue(e.getMessage().contains("resourceId|scalableDimension|serviceNamespace"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingTheTargetDeregistersItsTriple() {
|
||||
provisioner.delete(ApplicationAutoScalingCfnProvisioner.SCALABLE_TARGET, TARGET_ID, "us-east-1");
|
||||
|
||||
// Order matters: the composite is resourceId|dimension|namespace, the call is (namespace, id, dimension).
|
||||
verify(service).deregisterScalableTarget("ecs", "service/my-cluster/my-service",
|
||||
"ecs:service:DesiredCount", "us-east-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingAPolicyResolvesItsArnBackToTheNameAndTriple() {
|
||||
String arn = "arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:abc";
|
||||
when(service.findPolicyByArn(arn, "us-east-1")).thenReturn(Optional.of(aPolicy(arn)));
|
||||
|
||||
provisioner.delete(ApplicationAutoScalingCfnProvisioner.SCALING_POLICY, arn, "us-east-1");
|
||||
|
||||
verify(service).deleteScalingPolicy("cpu-target-tracking", "ecs",
|
||||
"service/my-cluster/my-service", "ecs:service:DesiredCount", "us-east-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPolicyAlreadyGoneIsNotAnError() {
|
||||
String arn = "arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:gone";
|
||||
when(service.findPolicyByArn(arn, "us-east-1")).thenReturn(Optional.empty());
|
||||
|
||||
// Deregistering a target takes its policies with it, so the stack's own policy delete that
|
||||
// follows finds nothing. That is a normal teardown ordering, not a failure.
|
||||
provisioner.delete(ApplicationAutoScalingCfnProvisioner.SCALING_POLICY, arn, "us-east-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTargetWithoutItsCapacityBoundsIsRefused() {
|
||||
// MinCapacity and MaxCapacity are required by the resource schema. Registering without them
|
||||
// would leave a target that never scales, which is worse than refusing the template.
|
||||
for (String missing : new String[] {"MinCapacity", "MaxCapacity"}) {
|
||||
ObjectNode props = targetProps();
|
||||
props.remove(missing);
|
||||
StackResource r = resource(ApplicationAutoScalingCfnProvisioner.SCALABLE_TARGET, "Target");
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
|
||||
assertTrue(e.getMessage().contains(missing), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPolicyWithoutItsNameOrTypeIsRefused() {
|
||||
for (String missing : new String[] {"PolicyName", "PolicyType"}) {
|
||||
ObjectNode props = mapper.createObjectNode()
|
||||
.put("PolicyName", "cpu")
|
||||
.put("PolicyType", "TargetTrackingScaling")
|
||||
.put("ScalingTargetId", TARGET_ID);
|
||||
props.remove(missing);
|
||||
StackResource r = resource(ApplicationAutoScalingCfnProvisioner.SCALING_POLICY, "Policy");
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
|
||||
assertTrue(e.getMessage().contains(missing), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTargetAlreadyDeregisteredIsNotAnError() {
|
||||
doThrow(new AwsException("ObjectNotFoundException", "No scalable target found", 400))
|
||||
.when(service).deregisterScalableTarget(any(), any(), any(), any());
|
||||
|
||||
// Its own policies deregister with it, so a stack teardown can reach this twice.
|
||||
provisioner.delete(ApplicationAutoScalingCfnProvisioner.SCALABLE_TARGET, TARGET_ID, "us-east-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIntrinsicInsideTheTargetTrackingBlockIsResolvedRatherThanReadRaw() {
|
||||
when(service.putScalingPolicy(any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(aPolicy("arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:abc"));
|
||||
StackResource r = resource(ApplicationAutoScalingCfnProvisioner.SCALING_POLICY, "Policy");
|
||||
ObjectNode props = mapper.createObjectNode()
|
||||
.put("PolicyName", "cpu")
|
||||
.put("PolicyType", "TargetTrackingScaling")
|
||||
.put("ScalingTargetId", TARGET_ID);
|
||||
ObjectNode config = props.putObject("TargetTrackingScalingPolicyConfiguration");
|
||||
config.putObject("TargetValue").put("Ref", "TargetCpu");
|
||||
config.putObject("PredefinedMetricSpecification")
|
||||
.put("PredefinedMetricType", "ECSServiceAverageCPUUtilization");
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
|
||||
ArgumentCaptor<TargetTrackingConfiguration> captor =
|
||||
ArgumentCaptor.forClass(TargetTrackingConfiguration.class);
|
||||
verify(service).putScalingPolicy(any(), any(), any(), any(), any(), captor.capture(), isNull(), any());
|
||||
// Read raw, {"Ref": "TargetCpu"} is a non-null node whose asDouble() is 0, so the guard
|
||||
// passes and the policy silently targets 0% rather than failing.
|
||||
assertEquals(70.0, captor.getValue().getTargetValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIntrinsicInsideSuspendedStateIsResolvedToo() {
|
||||
StackResource r = resource(ApplicationAutoScalingCfnProvisioner.SCALABLE_TARGET, "Target");
|
||||
ObjectNode props = targetProps();
|
||||
props.putObject("SuspendedState").putObject("DynamicScalingInSuspended").put("Ref", "Suspend");
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
|
||||
ArgumentCaptor<SuspendedState> captor = ArgumentCaptor.forClass(SuspendedState.class);
|
||||
verify(service).registerScalableTarget(any(), any(), any(), any(), any(), any(),
|
||||
captor.capture(), any(), any());
|
||||
// The flag itself, not just that a block arrived: read raw, {"Ref": "Suspend"} is an
|
||||
// object whose asBoolean() is false, and the block is an object either way.
|
||||
assertTrue(captor.getValue().isDynamicScalingInSuspended());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTargetsTagsAreRegisteredRatherThanDropped() {
|
||||
StackResource r = resource(ApplicationAutoScalingCfnProvisioner.SCALABLE_TARGET, "Target");
|
||||
ObjectNode props = targetProps();
|
||||
ArrayNode tags = props.putArray("Tags");
|
||||
tags.addObject().put("Key", "Owner").put("Value", "platform");
|
||||
tags.addObject().put("Key", "Env").putObject("Value").put("Ref", "Env");
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
|
||||
verify(service).registerScalableTarget(any(), any(), any(), any(), any(), any(), any(),
|
||||
eq(Map.of("Owner", "platform", "Env", "prod")), any());
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,8 @@ AWS::AppSync::FunctionConfiguration AppSyncCfnProvisioner
|
||||
AWS::AppSync::GraphQLApi AppSyncCfnProvisioner
|
||||
AWS::AppSync::GraphQLSchema AppSyncCfnProvisioner
|
||||
AWS::AppSync::Resolver AppSyncCfnProvisioner
|
||||
AWS::ApplicationAutoScaling::ScalableTarget ApplicationAutoScalingCfnProvisioner
|
||||
AWS::ApplicationAutoScaling::ScalingPolicy ApplicationAutoScalingCfnProvisioner
|
||||
AWS::AutoScaling::AutoScalingGroup AutoScalingGroupCfnProvisioner
|
||||
AWS::AutoScaling::LaunchConfiguration AutoScalingGroupCfnProvisioner
|
||||
AWS::AutoScaling::LifecycleHook AutoScalingLifecycleHookCfnProvisioner
|
||||
|
||||
|
@@ -30,6 +30,7 @@ order:
|
||||
- AWS::EC2
|
||||
- AWS::ElasticLoadBalancingV2
|
||||
- AWS::AutoScaling
|
||||
- AWS::ApplicationAutoScaling
|
||||
- AWS::Route53
|
||||
- AWS::ServiceDiscovery
|
||||
- AWS::ApiGateway
|
||||
@@ -97,6 +98,7 @@ type_order:
|
||||
VPCGatewayAttachment, VPCEndpoint, NetworkAcl, NetworkAclEntry, SubnetNetworkAclAssociation,
|
||||
FlowLog]
|
||||
AWS::ElasticLoadBalancingV2: [LoadBalancer, TargetGroup, Listener, ListenerRule]
|
||||
AWS::ApplicationAutoScaling: [ScalableTarget, ScalingPolicy]
|
||||
AWS::AutoScaling: [LaunchConfiguration, AutoScalingGroup, LifecycleHook]
|
||||
AWS::Route53: [HostedZone, RecordSet]
|
||||
AWS::ApiGateway: [RestApi, Resource, Authorizer, Method, Deployment, Stage, Account, DomainName, BasePathMapping, GatewayResponse]
|
||||
@@ -113,6 +115,7 @@ service_labels:
|
||||
AWS::ApiGateway: API Gateway (v1)
|
||||
AWS::ApiGatewayV2: API Gateway v2
|
||||
AWS::AppSync: AppSync
|
||||
AWS::ApplicationAutoScaling: Application Auto Scaling
|
||||
AWS::AutoScaling: Auto Scaling
|
||||
AWS::Batch: Batch
|
||||
AWS::Backup: Backup
|
||||
@@ -167,6 +170,7 @@ notes:
|
||||
AWS::Lambda::EventSourceMapping: 'SQS, Kinesis, DynamoDB Streams; `ParallelizationFactor` and `TumblingWindowInSeconds` are ignored'
|
||||
AWS::Lambda::Alias: also what SAM's `AutoPublishAlias` expands into
|
||||
AWS::EC2::SecurityGroup: inline `SecurityGroupIngress`/`SecurityGroupEgress` supported
|
||||
AWS::ApplicationAutoScaling::ScalableTarget: '`ScheduledActions` are accepted and not run; Floci has no scheduled scaling'
|
||||
AWS::RDS::DBInstance: starts a real container
|
||||
AWS::RDS::DBCluster: starts a real container
|
||||
AWS::ElastiCache::CacheCluster: 'starts a real container; modifying an existing cluster in place is not supported'
|
||||
|
||||
Reference in new issue
Block a user