mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(cloudformation): provision AWS::AutoScaling::ScalingPolicy (#3124)
* feat(cloudformation): provision AWS::AutoScaling::ScalingPolicy Per-service provisioner over AutoScalingService. Ref and Fn::GetAtt Arn are the policy ARN and Fn::GetAtt PolicyName the generated name, since the type has no PolicyName property. PutScalingPolicy is an upsert keyed by group and name, so an update reuses the name recorded at create time and rewrites the policy in place. AutoScalingGroupName is createOnly, so moving the policy to another group is refused as a replacement rather than left behind on the old group. Omitted ScalingAdjustment and Cooldown take the Query handler's defaults. Ported from lex00/floci#118. Tracked in lex00/floci#192. * fix(cloudformation): scope the scaling policy lookup to its group Policy names are unique only within a group. The update path now looks for the recorded name on the template's group first and treats a same-named policy on another group as a move only when it is not there, so an unrelated group's policy cannot block a valid update. * fix(cloudformation): take a scaling policy's identity from its recorded group Finding the recorded name on the group the template asks for read the destination group's own same-named policy as this resource, so a move overwrote that policy and orphaned the original. The group is recorded on the resource at create time and compared directly instead, which drops both DescribePolicies lookups. A resource provisioned before the attribute existed has no prior group and keeps the previous behaviour.
This commit is contained in:
1 parent
cbde58f238
commit
17af9590c7
6 files changed
+571
-1
No files matched your search
@@ -82,7 +82,7 @@ cross-resource references.
|
||||
| RDS | `DBInstance` (starts a real container), `DBCluster` (starts a real container), `DBSubnetGroup`, `DBParameterGroup`, `DBClusterParameterGroup`, `DBProxy`, `DBProxyTargetGroup` |
|
||||
| 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` |
|
||||
| Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup`, `LifecycleHook`, `ScalingPolicy` |
|
||||
| Route 53 | `HostedZone`, `RecordSet` |
|
||||
| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer`, `Method`, `Deployment`, `Stage`, `Account`, `DomainName`, `BasePathMapping`, `ApiKey` |
|
||||
| API Gateway v2 | `Api`, `Authorizer`, `Route`, `Integration`, `Stage`, `Deployment` |
|
||||
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.ScalingPolicy;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* CloudFormation provisioning for {@code AWS::AutoScaling::ScalingPolicy}, backed by
|
||||
* {@link AutoScalingService}. {@code Ref} and {@code Fn::GetAtt Arn} are the policy ARN and
|
||||
* {@code Fn::GetAtt PolicyName} the generated name, matching AWS, which offers no PolicyName
|
||||
* property and names the policy after the stack and logical id.
|
||||
*
|
||||
* <p>PutScalingPolicy is an upsert keyed by group and name, so an update reuses the name recorded
|
||||
* at create time and rewrites the policy in place. AutoScalingGroupName is createOnly: moving the
|
||||
* policy to another group is refused as a replacement rather than left behind on the old group.
|
||||
* StepAdjustments, MinAdjustmentMagnitude, MetricAggregationType, PredictiveScalingConfiguration
|
||||
* and the customized-metric and DisableScaleIn parts of TargetTrackingConfiguration have no
|
||||
* counterpart in {@link ScalingPolicy} and are accepted without effect.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class AutoScalingScalingPolicyCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private static final String TYPE = "AWS::AutoScaling::ScalingPolicy";
|
||||
/** The Auto Scaling API's limit on a policy name. */
|
||||
private static final int POLICY_NAME_MAX = 255;
|
||||
/** The defaults the Query handler applies when PutScalingPolicy omits these, kept in step with it. */
|
||||
private static final int DEFAULT_SCALING_ADJUSTMENT = 0;
|
||||
private static final int DEFAULT_COOLDOWN = 300;
|
||||
|
||||
private final AutoScalingService autoScalingService;
|
||||
|
||||
@Inject
|
||||
public AutoScalingScalingPolicyCfnProvisioner(AutoScalingService autoScalingService) {
|
||||
this.autoScalingService = autoScalingService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of(TYPE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String asgName = ctx.resolveOptional(props, "AutoScalingGroupName");
|
||||
String policyName = priorAttribute(r, ctx, "PolicyName");
|
||||
if (policyName != null) {
|
||||
// Identity comes from the group recorded at create time, not from finding the name on
|
||||
// the group the template now asks for. A same-named policy already on the destination
|
||||
// group is somebody else's: reading it as this resource would overwrite it and orphan
|
||||
// the original. A resource provisioned before this attribute existed has no prior group
|
||||
// and keeps the old behaviour of trusting the template.
|
||||
String priorAsgName = priorAttribute(r, ctx, "AutoScalingGroupName");
|
||||
if (priorAsgName != null && !priorAsgName.equals(asgName)) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Updating AutoScalingGroupName requires resource replacement, which is not supported.", 400);
|
||||
}
|
||||
} else {
|
||||
policyName = ctx.generatePhysicalName(r.getLogicalId(), POLICY_NAME_MAX, false);
|
||||
}
|
||||
|
||||
ScalingPolicy policy = autoScalingService.putScalingPolicy(ctx.region(), asgName, policyName,
|
||||
ctx.resolveOptional(props, "PolicyType"),
|
||||
ctx.resolveOptional(props, "AdjustmentType"),
|
||||
intOrDefault(ctx.resolveOptional(props, "ScalingAdjustment"), DEFAULT_SCALING_ADJUSTMENT),
|
||||
intOrDefault(ctx.resolveOptional(props, "Cooldown"), DEFAULT_COOLDOWN),
|
||||
nullableInt(ctx.resolveOptional(props, "EstimatedInstanceWarmup")),
|
||||
targetTracking(props, ctx));
|
||||
|
||||
r.setPhysicalId(policy.getPolicyArn());
|
||||
r.getAttributes().put("Arn", policy.getPolicyArn());
|
||||
r.getAttributes().put("PolicyName", policyName);
|
||||
// Not a Fn::GetAtt attribute of the type. It is the record of which group owns this policy,
|
||||
// which the next update needs to tell a rewrite from a move.
|
||||
r.getAttributes().put("AutoScalingGroupName", asgName);
|
||||
}
|
||||
|
||||
/**
|
||||
* An attribute this resource recorded on an earlier provision, or null on a first create. The
|
||||
* name and the group are read from here rather than parsed out of the ARN, so the ARN's shape
|
||||
* stays the service's business. Generating a fresh name on every UpdateStack would put a second
|
||||
* policy on the group and orphan the first, which then outlives the stack.
|
||||
*/
|
||||
private static String priorAttribute(StackResource r, ProvisionContext ctx, String name) {
|
||||
if (!ctx.isUpdate() || r.getAttributes() == null) {
|
||||
return null;
|
||||
}
|
||||
String prior = r.getAttributes().get(name);
|
||||
return prior == null || prior.isBlank() ? null : prior;
|
||||
}
|
||||
|
||||
private static ScalingPolicy.TargetTrackingConfiguration targetTracking(JsonNode props, ProvisionContext ctx) {
|
||||
if (props == null || !props.hasNonNull("TargetTrackingConfiguration")) {
|
||||
return null;
|
||||
}
|
||||
JsonNode node = ctx.engine().resolveNode(props.get("TargetTrackingConfiguration"));
|
||||
if (node == null || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
ScalingPolicy.TargetTrackingConfiguration configuration = new ScalingPolicy.TargetTrackingConfiguration();
|
||||
String targetValue = ctx.engine().resolve(node.path("TargetValue"));
|
||||
if (targetValue != null && !targetValue.isBlank()) {
|
||||
configuration.setTargetValue(Double.parseDouble(targetValue));
|
||||
}
|
||||
JsonNode predefined = node.get("PredefinedMetricSpecification");
|
||||
if (predefined != null && !predefined.isNull()) {
|
||||
ScalingPolicy.PredefinedMetricSpecification specification = new ScalingPolicy.PredefinedMetricSpecification();
|
||||
specification.setPredefinedMetricType(ctx.engine().resolve(predefined.path("PredefinedMetricType")));
|
||||
configuration.setPredefinedMetricSpecification(specification);
|
||||
}
|
||||
return configuration;
|
||||
}
|
||||
|
||||
private static int intOrDefault(String value, int fallback) {
|
||||
return value == null || value.isBlank() ? fallback : Integer.parseInt(value.trim());
|
||||
}
|
||||
|
||||
private static Integer nullableInt(String value) {
|
||||
return value == null || value.isBlank() ? null : Integer.valueOf(value.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* Without this the policy outlives its stack and keeps showing up in DescribePolicies. The
|
||||
* service matches by name or ARN and already treats a missing policy as nothing to do.
|
||||
*/
|
||||
@Override
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
if (physicalId == null || physicalId.isBlank()) {
|
||||
return;
|
||||
}
|
||||
autoScalingService.deletePolicy(region, null, physicalId);
|
||||
}
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.ScalingPolicy;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* Provisions two {@code AWS::AutoScaling::ScalingPolicy} resources on a group the same stack
|
||||
* creates: a target-tracking policy and a simple-scaling one. Asserts that {@code Ref} and
|
||||
* {@code Fn::GetAtt Arn} are the ARN {@code DescribePolicies} reports and {@code Fn::GetAtt
|
||||
* PolicyName} the generated name, that an update rewrites both policies in place under the same
|
||||
* name and ARN, and that deleting the stack removes them from the group.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class AutoScalingScalingPolicyCfnIntegrationTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/cloudformation/aws4_request";
|
||||
private static final String ASG_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/autoscaling/aws4_request";
|
||||
private static final String STACK = "asg-policy-cfn-it";
|
||||
private static final String ASG = "asg-policy-cfn-it-group";
|
||||
|
||||
private static final String TEMPLATE = """
|
||||
{
|
||||
"Parameters": {
|
||||
"TargetValue": {"Type": "String"},
|
||||
"Cooldown": {"Type": "String"}
|
||||
},
|
||||
"Resources": {
|
||||
"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.81.0.0/16"}},
|
||||
"Subnet": {
|
||||
"Type": "AWS::EC2::Subnet",
|
||||
"Properties": {"VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.81.1.0/24"}
|
||||
},
|
||||
"Lc": {
|
||||
"Type": "AWS::AutoScaling::LaunchConfiguration",
|
||||
"Properties": {"ImageId": "ami-11111111", "InstanceType": "t3.micro"}
|
||||
},
|
||||
"Asg": {
|
||||
"Type": "AWS::AutoScaling::AutoScalingGroup",
|
||||
"Properties": {
|
||||
"AutoScalingGroupName": "%s",
|
||||
"MinSize": "0", "MaxSize": "0", "DesiredCapacity": "0",
|
||||
"LaunchConfigurationName": {"Ref": "Lc"},
|
||||
"VPCZoneIdentifier": [{"Ref": "Subnet"}]
|
||||
}
|
||||
},
|
||||
"Tracking": {
|
||||
"Type": "AWS::AutoScaling::ScalingPolicy",
|
||||
"Properties": {
|
||||
"AutoScalingGroupName": {"Ref": "Asg"},
|
||||
"PolicyType": "TargetTrackingScaling",
|
||||
"EstimatedInstanceWarmup": 120,
|
||||
"TargetTrackingConfiguration": {
|
||||
"PredefinedMetricSpecification": {"PredefinedMetricType": "ASGAverageCPUUtilization"},
|
||||
"TargetValue": {"Ref": "TargetValue"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Simple": {
|
||||
"Type": "AWS::AutoScaling::ScalingPolicy",
|
||||
"Properties": {
|
||||
"AutoScalingGroupName": {"Ref": "Asg"},
|
||||
"AdjustmentType": "ChangeInCapacity",
|
||||
"ScalingAdjustment": 1,
|
||||
"Cooldown": {"Ref": "Cooldown"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"TrackingRef": {"Value": {"Ref": "Tracking"}},
|
||||
"TrackingArn": {"Value": {"Fn::GetAtt": ["Tracking", "Arn"]}},
|
||||
"TrackingName": {"Value": {"Fn::GetAtt": ["Tracking", "PolicyName"]}},
|
||||
"SimpleRef": {"Value": {"Ref": "Simple"}},
|
||||
"SimpleName": {"Value": {"Fn::GetAtt": ["Simple", "PolicyName"]}}
|
||||
}
|
||||
}
|
||||
""".formatted(ASG);
|
||||
|
||||
@Inject
|
||||
AutoScalingService autoScalingService;
|
||||
|
||||
@Test
|
||||
void createUpdateAndDeleteScalingPolicies() throws InterruptedException {
|
||||
cloudFormation("CreateStack", Map.of("TargetValue", "50", "Cooldown", "60"));
|
||||
String created = describeStacks("CREATE_COMPLETE");
|
||||
String trackingArn = outputValue(created, "TrackingRef");
|
||||
String trackingName = outputValue(created, "TrackingName");
|
||||
String simpleArn = outputValue(created, "SimpleRef");
|
||||
String simpleName = outputValue(created, "SimpleName");
|
||||
|
||||
// Ref and Fn::GetAtt Arn agree, and the name is CloudFormation-style, not a template property.
|
||||
assertEquals(trackingArn, outputValue(created, "TrackingArn"));
|
||||
assertTrue(trackingName.startsWith(STACK + "-Tracking-"), trackingName);
|
||||
assertTrue(simpleName.startsWith(STACK + "-Simple-"), simpleName);
|
||||
assertTrue(trackingArn.endsWith(":scalingPolicy:" + ASG + ":" + trackingName), trackingArn);
|
||||
|
||||
// Both policies are live on the group, with the values the template asked for.
|
||||
describePolicies()
|
||||
.body(containsString("<PolicyName>" + trackingName + "</PolicyName>"))
|
||||
.body(containsString("<PolicyARN>" + simpleArn + "</PolicyARN>"))
|
||||
.body(containsString("<PolicyType>TargetTrackingScaling</PolicyType>"))
|
||||
.body(containsString("<Cooldown>60</Cooldown>"))
|
||||
.body(containsString("<EstimatedInstanceWarmup>120</EstimatedInstanceWarmup>"));
|
||||
assertEquals(50.0, tracking(trackingName).getTargetTrackingConfiguration().getTargetValue());
|
||||
assertEquals("ASGAverageCPUUtilization",
|
||||
tracking(trackingName).getTargetTrackingConfiguration().getPredefinedMetricSpecification()
|
||||
.getPredefinedMetricType());
|
||||
|
||||
cloudFormation("UpdateStack", Map.of("TargetValue", "70", "Cooldown", "120"));
|
||||
String updated = describeStacks("UPDATE_COMPLETE");
|
||||
|
||||
// Same names and ARNs, new values: the policies were rewritten, not replaced.
|
||||
assertEquals(trackingArn, outputValue(updated, "TrackingRef"));
|
||||
assertEquals(trackingName, outputValue(updated, "TrackingName"));
|
||||
assertEquals(simpleArn, outputValue(updated, "SimpleRef"));
|
||||
describePolicies()
|
||||
.body(containsString("<Cooldown>120</Cooldown>"))
|
||||
.body(not(containsString("<Cooldown>60</Cooldown>")));
|
||||
assertEquals(70.0, tracking(trackingName).getTargetTrackingConfiguration().getTargetValue());
|
||||
assertEquals(2, autoScalingService.describePolicies(REGION, ASG, null).size());
|
||||
|
||||
cloudFormation("DeleteStack", Map.of());
|
||||
awaitStackDeleted();
|
||||
|
||||
assertEquals(List.of(), autoScalingService.describePolicies(REGION, null, List.of(trackingName, simpleName)));
|
||||
}
|
||||
|
||||
private ScalingPolicy tracking(String name) {
|
||||
return autoScalingService.describePolicies(REGION, ASG, List.of(name)).get(0);
|
||||
}
|
||||
|
||||
private static void cloudFormation(String action, Map<String, String> parameters) {
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", action)
|
||||
.formParam("StackName", STACK);
|
||||
if (!"DeleteStack".equals(action)) {
|
||||
request.formParam("TemplateBody", TEMPLATE);
|
||||
}
|
||||
int index = 1;
|
||||
for (Map.Entry<String, String> parameter : parameters.entrySet()) {
|
||||
request.formParam("Parameters.member." + index + ".ParameterKey", parameter.getKey());
|
||||
request.formParam("Parameters.member." + index + ".ParameterValue", parameter.getValue());
|
||||
index++;
|
||||
}
|
||||
request.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static String describeStacks(String expectedStatus) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", STACK)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
|
||||
.extract().asString();
|
||||
}
|
||||
|
||||
/** DeleteStack runs asynchronously; a successful delete removes the stack entirely. */
|
||||
private static void awaitStackDeleted() throws InterruptedException {
|
||||
for (int i = 0; i < 100; i++) {
|
||||
String body = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", STACK)
|
||||
.when().post("/").then().extract().asString();
|
||||
if (body.contains("does not exist")) {
|
||||
return;
|
||||
}
|
||||
if (body.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {
|
||||
fail("stack delete failed: " + body);
|
||||
}
|
||||
Thread.sleep(50);
|
||||
}
|
||||
fail("stack " + STACK + " was not deleted within the timeout");
|
||||
}
|
||||
|
||||
private static String outputValue(String xml, String key) {
|
||||
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
|
||||
}
|
||||
|
||||
private static ValidatableResponse describePolicies() {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", ASG_AUTH)
|
||||
.formParam("Action", "DescribePolicies")
|
||||
.formParam("AutoScalingGroupName", ASG)
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
+2
@@ -26,6 +26,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewa
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayApiKeyCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayDomainCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingLifecycleHookCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingScalingPolicyCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CdkMetadataCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatchCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoCfnProvisioner;
|
||||
@@ -248,6 +249,7 @@ final class CfnProvisionerFixture {
|
||||
}
|
||||
if (autoScalingService != null) {
|
||||
discovered.add(new AutoScalingLifecycleHookCfnProvisioner(autoScalingService));
|
||||
discovered.add(new AutoScalingScalingPolicyCfnProvisioner(autoScalingService));
|
||||
}
|
||||
if (acmService != null) {
|
||||
discovered.add(new AcmCfnProvisioner(acmService));
|
||||
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
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.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.ScalingPolicy;
|
||||
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.List;
|
||||
|
||||
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.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** The Auto Scaling policy CFN provisioner in isolation, against a mocked {@link AutoScalingService}. */
|
||||
class AutoScalingScalingPolicyCfnProvisionerTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String TYPE = "AWS::AutoScaling::ScalingPolicy";
|
||||
private static final String ARN =
|
||||
"arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:my-asg:my-stack-MyPolicy-abc";
|
||||
|
||||
private final AutoScalingService autoScaling = mock(AutoScalingService.class);
|
||||
private final AutoScalingScalingPolicyCfnProvisioner provisioner =
|
||||
new AutoScalingScalingPolicyCfnProvisioner(autoScaling);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private ProvisionContext ctx() {
|
||||
return ctx(null);
|
||||
}
|
||||
|
||||
private ProvisionContext ctx(String priorPhysicalId) {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId);
|
||||
}
|
||||
|
||||
private static StackResource resource(String priorPhysicalId, String priorPolicyName) {
|
||||
return resource(priorPhysicalId, priorPolicyName, priorPolicyName == null ? null : "my-asg");
|
||||
}
|
||||
|
||||
private static StackResource resource(String priorPhysicalId, String priorPolicyName, String priorAsgName) {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("MyPolicy");
|
||||
r.setResourceType(TYPE);
|
||||
r.setPhysicalId(priorPhysicalId);
|
||||
r.setAttributes(new HashMap<>());
|
||||
if (priorPolicyName != null) {
|
||||
r.getAttributes().put("PolicyName", priorPolicyName);
|
||||
}
|
||||
if (priorAsgName != null) {
|
||||
r.getAttributes().put("AutoScalingGroupName", priorAsgName);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
private static ScalingPolicy policy(String asgName, String name) {
|
||||
ScalingPolicy policy = new ScalingPolicy();
|
||||
policy.setAutoScalingGroupName(asgName);
|
||||
policy.setPolicyName(name);
|
||||
policy.setPolicyArn(ARN);
|
||||
return policy;
|
||||
}
|
||||
|
||||
@Test
|
||||
void createSendsThePropertiesAndRecordsArnAndName() {
|
||||
when(autoScaling.putScalingPolicy(eq(REGION), eq("my-asg"), anyString(), eq("SimpleScaling"),
|
||||
eq("ChangeInCapacity"), eq(1), eq(60), eq(120), isNull()))
|
||||
.thenReturn(policy("my-asg", "generated"));
|
||||
ObjectNode props = mapper.createObjectNode()
|
||||
.put("AutoScalingGroupName", "my-asg")
|
||||
.put("PolicyType", "SimpleScaling")
|
||||
.put("AdjustmentType", "ChangeInCapacity")
|
||||
.put("ScalingAdjustment", 1)
|
||||
.put("Cooldown", 60)
|
||||
.put("EstimatedInstanceWarmup", 120);
|
||||
StackResource r = resource(null, null);
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
|
||||
ArgumentCaptor<String> name = ArgumentCaptor.forClass(String.class);
|
||||
verify(autoScaling).putScalingPolicy(eq(REGION), eq("my-asg"), name.capture(), eq("SimpleScaling"),
|
||||
eq("ChangeInCapacity"), eq(1), eq(60), eq(120), isNull());
|
||||
assertTrue(name.getValue().startsWith("my-stack-MyPolicy-"), name.getValue());
|
||||
assertEquals(ARN, r.getPhysicalId());
|
||||
assertEquals(ARN, r.getAttributes().get("Arn"));
|
||||
assertEquals(name.getValue(), r.getAttributes().get("PolicyName"));
|
||||
assertEquals("my-asg", r.getAttributes().get("AutoScalingGroupName"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void omittedAdjustmentAndCooldownDefaultLikeTheQueryApi() {
|
||||
when(autoScaling.putScalingPolicy(any(), any(), any(), any(), any(), anyInt(), anyInt(), any(), any()))
|
||||
.thenReturn(policy("my-asg", "generated"));
|
||||
|
||||
provisioner.provision(resource(null, null), mapper.createObjectNode().put("AutoScalingGroupName", "my-asg"), ctx());
|
||||
|
||||
verify(autoScaling).putScalingPolicy(eq(REGION), eq("my-asg"), anyString(), isNull(), isNull(),
|
||||
eq(0), eq(300), isNull(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void targetTrackingConfigurationIsParsed() {
|
||||
when(autoScaling.putScalingPolicy(any(), any(), any(), any(), any(), anyInt(), anyInt(), any(), any()))
|
||||
.thenReturn(policy("my-asg", "generated"));
|
||||
ObjectNode props = mapper.createObjectNode()
|
||||
.put("AutoScalingGroupName", "my-asg")
|
||||
.put("PolicyType", "TargetTrackingScaling");
|
||||
ObjectNode tracking = props.putObject("TargetTrackingConfiguration").put("TargetValue", 50.0);
|
||||
tracking.putObject("PredefinedMetricSpecification").put("PredefinedMetricType", "ASGAverageCPUUtilization");
|
||||
|
||||
provisioner.provision(resource(null, null), props, ctx());
|
||||
|
||||
ArgumentCaptor<ScalingPolicy.TargetTrackingConfiguration> captor =
|
||||
ArgumentCaptor.forClass(ScalingPolicy.TargetTrackingConfiguration.class);
|
||||
verify(autoScaling).putScalingPolicy(eq(REGION), eq("my-asg"), anyString(), eq("TargetTrackingScaling"),
|
||||
isNull(), eq(0), eq(300), isNull(), captor.capture());
|
||||
assertEquals(50.0, captor.getValue().getTargetValue());
|
||||
assertEquals("ASGAverageCPUUtilization",
|
||||
captor.getValue().getPredefinedMetricSpecification().getPredefinedMetricType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateReusesTheRecordedNameOnTheSameGroup() {
|
||||
when(autoScaling.putScalingPolicy(any(), any(), any(), any(), any(), anyInt(), anyInt(), any(), any()))
|
||||
.thenReturn(policy("my-asg", "my-stack-MyPolicy-abc"));
|
||||
StackResource r = resource(ARN, "my-stack-MyPolicy-abc");
|
||||
ObjectNode props = mapper.createObjectNode().put("AutoScalingGroupName", "my-asg").put("Cooldown", 120);
|
||||
|
||||
provisioner.provision(r, props, ctx(ARN));
|
||||
|
||||
verify(autoScaling).putScalingPolicy(eq(REGION), eq("my-asg"), eq("my-stack-MyPolicy-abc"), isNull(),
|
||||
isNull(), eq(0), eq(120), isNull(), isNull());
|
||||
// Identity comes from the recorded group, so no lookup is needed at all.
|
||||
verify(autoScaling, never()).describePolicies(any(), any(), anyList());
|
||||
assertEquals(ARN, r.getPhysicalId());
|
||||
assertEquals("my-stack-MyPolicy-abc", r.getAttributes().get("PolicyName"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMoveOntoAGroupThatAlreadyHasThatNameDoesNotOverwriteIt() {
|
||||
// The destination group's own policy shares the name. Reading it as this resource would
|
||||
// rewrite somebody else's policy and orphan the original.
|
||||
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(
|
||||
resource(ARN, "my-stack-MyPolicy-abc", "my-asg"),
|
||||
mapper.createObjectNode().put("AutoScalingGroupName", "other-asg"), ctx(ARN)));
|
||||
|
||||
assertTrue(e.getMessage().contains("AutoScalingGroupName"), e.getMessage());
|
||||
verify(autoScaling, never()).putScalingPolicy(any(), any(), any(), any(), any(), anyInt(), anyInt(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUpdateOfAResourceProvisionedBeforeTheGroupWasRecordedStillWorks() {
|
||||
when(autoScaling.putScalingPolicy(any(), any(), any(), any(), any(), anyInt(), anyInt(), any(), any()))
|
||||
.thenReturn(policy("my-asg", "my-stack-MyPolicy-abc"));
|
||||
|
||||
provisioner.provision(resource(ARN, "my-stack-MyPolicy-abc", null),
|
||||
mapper.createObjectNode().put("AutoScalingGroupName", "my-asg"), ctx(ARN));
|
||||
|
||||
verify(autoScaling).putScalingPolicy(eq(REGION), eq("my-asg"), eq("my-stack-MyPolicy-abc"), isNull(),
|
||||
isNull(), eq(0), eq(300), isNull(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateOfAPolicyGoneFromTheGroupRecreatesItUnderTheSameName() {
|
||||
when(autoScaling.putScalingPolicy(any(), any(), any(), any(), any(), anyInt(), anyInt(), any(), any()))
|
||||
.thenReturn(policy("my-asg", "my-stack-MyPolicy-abc"));
|
||||
|
||||
provisioner.provision(resource(ARN, "my-stack-MyPolicy-abc"),
|
||||
mapper.createObjectNode().put("AutoScalingGroupName", "my-asg"), ctx(ARN));
|
||||
|
||||
verify(autoScaling).putScalingPolicy(eq(REGION), eq("my-asg"), eq("my-stack-MyPolicy-abc"), isNull(),
|
||||
isNull(), eq(0), eq(300), isNull(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void movingThePolicyToAnotherGroupIsRefusedAsReplacementWorthy() {
|
||||
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(
|
||||
resource(ARN, "my-stack-MyPolicy-abc", "old-asg"),
|
||||
mapper.createObjectNode().put("AutoScalingGroupName", "new-asg"), ctx(ARN)));
|
||||
|
||||
assertEquals("ValidationError", e.getErrorCode());
|
||||
assertTrue(e.getMessage().contains("AutoScalingGroupName"), e.getMessage());
|
||||
verify(autoScaling, never()).putScalingPolicy(any(), any(), any(), any(), any(), anyInt(), anyInt(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteDelegatesByArn() {
|
||||
provisioner.delete(TYPE, ARN, REGION);
|
||||
verify(autoScaling).deletePolicy(REGION, null, ARN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteWithoutAPhysicalIdTouchesNothing() {
|
||||
provisioner.delete(TYPE, null, REGION);
|
||||
verify(autoScaling, never()).deletePolicy(any(), any(), any());
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ AWS::ApiGatewayV2::Stage LEGACY_SWITCH
|
||||
AWS::AutoScaling::AutoScalingGroup LEGACY_SWITCH
|
||||
AWS::AutoScaling::LaunchConfiguration LEGACY_SWITCH
|
||||
AWS::AutoScaling::LifecycleHook AutoScalingLifecycleHookCfnProvisioner
|
||||
AWS::AutoScaling::ScalingPolicy AutoScalingScalingPolicyCfnProvisioner
|
||||
AWS::Batch::ComputeEnvironment LEGACY_SWITCH
|
||||
AWS::Batch::JobDefinition LEGACY_SWITCH
|
||||
AWS::Batch::JobQueue LEGACY_SWITCH
|
||||
|
||||
|
Reference in new issue
Block a user