diff --git a/docs/services/autoscaling.md b/docs/services/autoscaling.md index a1adfc0e37..beb2f20077 100644 --- a/docs/services/autoscaling.md +++ b/docs/services/autoscaling.md @@ -127,10 +127,37 @@ Auto Scaling groups preserve either a launch configuration, a top-level launch t - `LaunchTemplate.LaunchTemplateSpecification.LaunchTemplateName` - `LaunchTemplate.LaunchTemplateSpecification.Version` - `LaunchTemplate.Overrides.member.N.InstanceType` +- `LaunchTemplate.Overrides.member.N.InstanceRequirements` - `InstancesDistribution.OnDemandBaseCapacity` - `InstancesDistribution.OnDemandPercentageAboveBaseCapacity` - `InstancesDistribution.SpotAllocationStrategy` +An override selects instance types either by name or by attribute. Setting both `InstanceType` and +`InstanceRequirements` on the same override raises `ValidationError`, matching AWS. An override that +specifies `InstanceRequirements` must specify both `VCpuCount` and `MemoryMiB`, the two members the +AWS model marks required on that shape, and raises `ValidationError` otherwise. Every member of the +`InstanceRequirements` shape round-trips except `BaselinePerformanceFactors`, which is accepted and +dropped. + +A group uses attribute-based instance type selection when the mixed instances policy left in effect +by the request carries at least one launch template override with `InstanceRequirements`. On create +that is the policy the request supplies. On update it is the policy the request supplies, the stored +policy when the request names no launch source, or none when the request switches the group to a +launch configuration or a plain launch template. + +## Optional Group Fields + +`CreateAutoScalingGroup` and `UpdateAutoScalingGroup` both accept the fields below, and +`DescribeAutoScalingGroups` returns each one only when the group has a value for it. A group that +never set a field omits it from the response rather than reporting a default. + +| Field | Notes | +|---|---| +| `DesiredCapacityType` | One of `units`, `vcpu`, `memory-mib`. Any other value raises `ValidationError`. AWS supports it for attribute-based instance type selection only, so `vcpu` and `memory-mib` raise `ValidationError` unless the effective mixed instances policy uses `InstanceRequirements`. `units` is the documented default and is always accepted | +| `CapacityRebalance` | Stored and echoed as a boolean | +| `MaxInstanceLifetime` | Seconds. Must be `0` or at least `86400`. `0` means no maximum and is echoed back as `0` | +| `DefaultInstanceWarmup` | Seconds. Pass `-1` to remove a value already set, after which the field is omitted again | + ## Scaling Policy Compatibility Target tracking policies preserve `TargetTrackingConfiguration` for predefined metrics. `DescribePolicies` returns `PredefinedMetricSpecification.PredefinedMetricType`, `TargetValue`, and `EstimatedInstanceWarmup` when present. diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandler.java index 9360bcf346..910fe69573 100644 --- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandler.java @@ -200,7 +200,8 @@ public class AutoScalingQueryHandler { intParam(p, "HealthCheckGracePeriod", 0), memberList(p, "TerminationPolicies"), parsedTags.tags(), - parsedTags.propagateAtLaunch()); + parsedTags.propagateAtLaunch(), + parseAsgOptionalFields(p)); return ok(new XmlBuilder() .start("CreateAutoScalingGroupResponse", NS) .raw(AwsQueryResponse.responseMetadata()) @@ -226,7 +227,8 @@ public class AutoScalingQueryHandler { subnetIds.isEmpty() ? null : subnetIds, p.getFirst("HealthCheckType"), p.getFirst("HealthCheckGracePeriod") != null ? Integer.parseInt(p.getFirst("HealthCheckGracePeriod")) : null, - tps.isEmpty() ? null : tps); + tps.isEmpty() ? null : tps, + parseAsgOptionalFields(p)); return ok(new XmlBuilder() .start("UpdateAutoScalingGroupResponse", NS) .raw(AwsQueryResponse.responseMetadata()) @@ -273,6 +275,18 @@ public class AutoScalingQueryHandler { .elem("HealthCheckGracePeriod", String.valueOf(asg.getHealthCheckGracePeriod())) .elem("CreatedTime", ISO_FMT.format(asg.getCreatedTime())); + if (asg.getDesiredCapacityType() != null) { + xml.elem("DesiredCapacityType", asg.getDesiredCapacityType()); + } + if (asg.getCapacityRebalance() != null) { + xml.elem("CapacityRebalance", String.valueOf(asg.getCapacityRebalance())); + } + if (asg.getMaxInstanceLifetime() != null) { + xml.elem("MaxInstanceLifetime", String.valueOf(asg.getMaxInstanceLifetime())); + } + if (asg.getDefaultInstanceWarmup() != null) { + xml.elem("DefaultInstanceWarmup", String.valueOf(asg.getDefaultInstanceWarmup())); + } if (asg.getLaunchConfigurationName() != null) { xml.elem("LaunchConfigurationName", asg.getLaunchConfigurationName()); } @@ -567,6 +581,7 @@ public class AutoScalingQueryHandler { if (override.getInstanceType() != null) { xml.elem("InstanceType", override.getInstanceType()); } + appendInstanceRequirementsXml(xml, override.getInstanceRequirements()); xml.end("member"); } xml.end("Overrides"); @@ -591,6 +606,89 @@ public class AutoScalingQueryHandler { xml.end("MixedInstancesPolicy"); } + // LaunchTemplateOverrides.InstanceRequirements from botocore's autoscaling model. Every member + // of that shape is echoed back except BaselinePerformanceFactors, whose nested Reference/item + // wire names are not covered here. + private static void appendInstanceRequirementsXml( + XmlBuilder xml, MixedInstancesPolicy.InstanceRequirements requirements) { + if (requirements == null || requirements.isEmpty()) { + return; + } + xml.start("InstanceRequirements"); + appendIntRangeXml(xml, "VCpuCount", requirements.getVCpuCount()); + appendIntRangeXml(xml, "MemoryMiB", requirements.getMemoryMiB()); + appendIntRangeXml(xml, "NetworkInterfaceCount", requirements.getNetworkInterfaceCount()); + appendIntRangeXml(xml, "AcceleratorCount", requirements.getAcceleratorCount()); + appendIntRangeXml(xml, "AcceleratorTotalMemoryMiB", requirements.getAcceleratorTotalMemoryMiB()); + appendIntRangeXml(xml, "BaselineEbsBandwidthMbps", requirements.getBaselineEbsBandwidthMbps()); + appendDoubleRangeXml(xml, "MemoryGiBPerVCpu", requirements.getMemoryGiBPerVCpu()); + appendDoubleRangeXml(xml, "TotalLocalStorageGB", requirements.getTotalLocalStorageGB()); + appendDoubleRangeXml(xml, "NetworkBandwidthGbps", requirements.getNetworkBandwidthGbps()); + appendStringMemberListXml(xml, "CpuManufacturers", requirements.getCpuManufacturers()); + appendStringMemberListXml(xml, "ExcludedInstanceTypes", requirements.getExcludedInstanceTypes()); + appendStringMemberListXml(xml, "InstanceGenerations", requirements.getInstanceGenerations()); + appendStringMemberListXml(xml, "LocalStorageTypes", requirements.getLocalStorageTypes()); + appendStringMemberListXml(xml, "AcceleratorTypes", requirements.getAcceleratorTypes()); + appendStringMemberListXml(xml, "AcceleratorManufacturers", requirements.getAcceleratorManufacturers()); + appendStringMemberListXml(xml, "AcceleratorNames", requirements.getAcceleratorNames()); + appendStringMemberListXml(xml, "AllowedInstanceTypes", requirements.getAllowedInstanceTypes()); + if (requirements.getSpotMaxPricePercentageOverLowestPrice() != null) { + xml.elem("SpotMaxPricePercentageOverLowestPrice", String.valueOf(requirements.getSpotMaxPricePercentageOverLowestPrice())); + } + if (requirements.getMaxSpotPriceAsPercentageOfOptimalOnDemandPrice() != null) { + xml.elem("MaxSpotPriceAsPercentageOfOptimalOnDemandPrice", String.valueOf(requirements.getMaxSpotPriceAsPercentageOfOptimalOnDemandPrice())); + } + if (requirements.getOnDemandMaxPricePercentageOverLowestPrice() != null) { + xml.elem("OnDemandMaxPricePercentageOverLowestPrice", String.valueOf(requirements.getOnDemandMaxPricePercentageOverLowestPrice())); + } + if (requirements.getRequireHibernateSupport() != null) { + xml.elem("RequireHibernateSupport", String.valueOf(requirements.getRequireHibernateSupport())); + } + xml.elem("BareMetal", requirements.getBareMetal()); + xml.elem("BurstablePerformance", requirements.getBurstablePerformance()); + xml.elem("LocalStorage", requirements.getLocalStorage()); + xml.end("InstanceRequirements"); + } + + private static void appendIntRangeXml(XmlBuilder xml, String element, MixedInstancesPolicy.IntRange range) { + if (range == null) { + return; + } + xml.start(element); + if (range.getMin() != null) { + xml.elem("Min", String.valueOf(range.getMin())); + } + if (range.getMax() != null) { + xml.elem("Max", String.valueOf(range.getMax())); + } + xml.end(element); + } + + private static void appendDoubleRangeXml(XmlBuilder xml, String element, MixedInstancesPolicy.DoubleRange range) { + if (range == null) { + return; + } + xml.start(element); + if (range.getMin() != null) { + xml.elem("Min", String.valueOf(range.getMin())); + } + if (range.getMax() != null) { + xml.elem("Max", String.valueOf(range.getMax())); + } + xml.end(element); + } + + private static void appendStringMemberListXml(XmlBuilder xml, String element, List values) { + if (values == null || values.isEmpty()) { + return; + } + xml.start(element); + for (String value : values) { + xml.elem("member", value); + } + xml.end(element); + } + private static void appendMixedLaunchTemplateSpecificationXml( XmlBuilder xml, MixedInstancesPolicy.LaunchTemplateSpecification specification) { if (specification == null) { @@ -1094,21 +1192,92 @@ public class AutoScalingQueryHandler { return false; } + // An override that sets only InstanceRequirements is legal, and mutually exclusive with + // InstanceType, so InstanceType's presence cannot be the loop's "is there another override" + // signal. Using it as one dropped the whole Overrides list rather than one member of it. private List parseMixedLaunchTemplateOverrides( MultivaluedMap p) { List result = new ArrayList<>(); for (int i = 1; ; i++) { - String instanceType = p.getFirst("MixedInstancesPolicy.LaunchTemplate.Overrides.member." - + i + ".InstanceType"); - if (instanceType == null) { break; } + String prefix = "MixedInstancesPolicy.LaunchTemplate.Overrides.member." + i; + if (!hasAnyPrefix(p, prefix + ".")) { + break; + } MixedInstancesPolicy.LaunchTemplateOverride override = new MixedInstancesPolicy.LaunchTemplateOverride(); - override.setInstanceType(instanceType); + override.setInstanceType(p.getFirst(prefix + ".InstanceType")); + override.setInstanceRequirements(parseInstanceRequirements(p, prefix + ".InstanceRequirements")); result.add(override); } return result; } + private MixedInstancesPolicy.InstanceRequirements parseInstanceRequirements( + MultivaluedMap p, String prefix) { + if (!hasAnyPrefix(p, prefix + ".")) { + return null; + } + MixedInstancesPolicy.InstanceRequirements requirements = + new MixedInstancesPolicy.InstanceRequirements(); + requirements.setVCpuCount(parseIntRange(p, prefix + ".VCpuCount")); + requirements.setMemoryMiB(parseIntRange(p, prefix + ".MemoryMiB")); + requirements.setNetworkInterfaceCount(parseIntRange(p, prefix + ".NetworkInterfaceCount")); + requirements.setAcceleratorCount(parseIntRange(p, prefix + ".AcceleratorCount")); + requirements.setAcceleratorTotalMemoryMiB(parseIntRange(p, prefix + ".AcceleratorTotalMemoryMiB")); + requirements.setBaselineEbsBandwidthMbps(parseIntRange(p, prefix + ".BaselineEbsBandwidthMbps")); + requirements.setMemoryGiBPerVCpu(parseDoubleRange(p, prefix + ".MemoryGiBPerVCpu")); + requirements.setTotalLocalStorageGB(parseDoubleRange(p, prefix + ".TotalLocalStorageGB")); + requirements.setNetworkBandwidthGbps(parseDoubleRange(p, prefix + ".NetworkBandwidthGbps")); + requirements.setCpuManufacturers(memberList(p, prefix + ".CpuManufacturers")); + requirements.setExcludedInstanceTypes(memberList(p, prefix + ".ExcludedInstanceTypes")); + requirements.setInstanceGenerations(memberList(p, prefix + ".InstanceGenerations")); + requirements.setLocalStorageTypes(memberList(p, prefix + ".LocalStorageTypes")); + requirements.setAcceleratorTypes(memberList(p, prefix + ".AcceleratorTypes")); + requirements.setAcceleratorManufacturers(memberList(p, prefix + ".AcceleratorManufacturers")); + requirements.setAcceleratorNames(memberList(p, prefix + ".AcceleratorNames")); + requirements.setAllowedInstanceTypes(memberList(p, prefix + ".AllowedInstanceTypes")); + requirements.setSpotMaxPricePercentageOverLowestPrice(parseOptionalInt(p.getFirst(prefix + ".SpotMaxPricePercentageOverLowestPrice"), prefix + ".SpotMaxPricePercentageOverLowestPrice")); + requirements.setMaxSpotPriceAsPercentageOfOptimalOnDemandPrice(parseOptionalInt(p.getFirst(prefix + ".MaxSpotPriceAsPercentageOfOptimalOnDemandPrice"), prefix + ".MaxSpotPriceAsPercentageOfOptimalOnDemandPrice")); + requirements.setOnDemandMaxPricePercentageOverLowestPrice(parseOptionalInt(p.getFirst(prefix + ".OnDemandMaxPricePercentageOverLowestPrice"), prefix + ".OnDemandMaxPricePercentageOverLowestPrice")); + requirements.setBareMetal(p.getFirst(prefix + ".BareMetal")); + requirements.setBurstablePerformance(p.getFirst(prefix + ".BurstablePerformance")); + requirements.setLocalStorage(p.getFirst(prefix + ".LocalStorage")); + requirements.setRequireHibernateSupport(parseOptionalBoolean(p.getFirst(prefix + ".RequireHibernateSupport"), prefix + ".RequireHibernateSupport")); + return requirements.isEmpty() ? null : requirements; + } + + private MixedInstancesPolicy.IntRange parseIntRange(MultivaluedMap p, String prefix) { + Integer min = parseOptionalInt(p.getFirst(prefix + ".Min"), prefix + ".Min"); + Integer max = parseOptionalInt(p.getFirst(prefix + ".Max"), prefix + ".Max"); + if (min == null && max == null) { + return null; + } + MixedInstancesPolicy.IntRange range = new MixedInstancesPolicy.IntRange(); + range.setMin(min); + range.setMax(max); + return range; + } + + private MixedInstancesPolicy.DoubleRange parseDoubleRange(MultivaluedMap p, String prefix) { + Double min = nullableDoubleParam(p, prefix + ".Min"); + Double max = nullableDoubleParam(p, prefix + ".Max"); + if (min == null && max == null) { + return null; + } + MixedInstancesPolicy.DoubleRange range = new MixedInstancesPolicy.DoubleRange(); + range.setMin(min); + range.setMax(max); + return range; + } + + private AsgOptionalFields parseAsgOptionalFields(MultivaluedMap p) { + return new AsgOptionalFields( + p.getFirst("DesiredCapacityType"), + nullableBoolParam(p, "CapacityRebalance"), + parseOptionalInt(p.getFirst("MaxInstanceLifetime"), "MaxInstanceLifetime"), + parseOptionalInt(p.getFirst("DefaultInstanceWarmup"), "DefaultInstanceWarmup")); + } + private ParsedTags parseTags(MultivaluedMap p) { Map tags = new LinkedHashMap<>(); Map propagateAtLaunch = new LinkedHashMap<>(); diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java index d0312102a9..4d99d32948 100644 --- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java +++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java @@ -30,6 +30,24 @@ public class AutoScalingService { static final String INVALID_LAUNCH_CONFIGURATION_PARAMETERS_MESSAGE = "Valid requests must contain either the InstanceID parameter " + "or both the ImageId and InstanceType parameters."; + static final Set DESIRED_CAPACITY_TYPES = Set.of("units", "vcpu", "memory-mib"); + static final int MIN_MAX_INSTANCE_LIFETIME_SECONDS = 86400; + static final String INVALID_DESIRED_CAPACITY_TYPE_MESSAGE = + "The specified value for DesiredCapacityType is not valid. Valid values are: units, vcpu, memory-mib."; + static final String INVALID_MAX_INSTANCE_LIFETIME_MESSAGE = + "MaxInstanceLifetime must be equal to 0 or a value greater than or equal to 86400 seconds."; + static final String INVALID_DEFAULT_INSTANCE_WARMUP_MESSAGE = + "DefaultInstanceWarmup must be greater than or equal to 0, or -1 to remove a previously set value."; + static final String INSTANCE_REQUIREMENTS_AND_INSTANCE_TYPE_MESSAGE = + "A launch template override must not specify both InstanceType and InstanceRequirements."; + static final String DEFAULT_DESIRED_CAPACITY_TYPE = "units"; + static final String INSTANCE_REQUIREMENTS_MISSING_RANGES_MESSAGE = + "You must specify VCpuCount and MemoryMiB when you specify InstanceRequirements " + + "on a launch template override."; + static final String DESIRED_CAPACITY_TYPE_NEEDS_INSTANCE_REQUIREMENTS_MESSAGE = + "Amazon EC2 Auto Scaling supports DesiredCapacityType for attribute-based instance type " + + "selection only. Specify InstanceRequirements on a MixedInstancesPolicy launch " + + "template override, or use the default DesiredCapacityType of units."; static final String ACTIVE_INSTANCE_REFRESH_DESIRED_CONFIGURATION_MESSAGE = "An active instance refresh with a desired configuration exists. All configuration options derived from the desired configuration are not available for update while the instance refresh is active."; @@ -185,7 +203,8 @@ public class AutoScalingService { String healthCheckType, int healthCheckGracePeriod, List terminationPolicies, Map tags, - Map tagPropagateAtLaunch) { + Map tagPropagateAtLaunch, + AsgOptionalFields optionalFields) { String key = asgKey(region, name); if (groups.containsKey(key)) { throw new AwsException("AlreadyExists", @@ -200,6 +219,10 @@ public class AutoScalingService { } validateEffectiveLaunchImage(region, launchConfigName, launchTemplateId, launchTemplateName, launchTemplateVersion, mixedInstancesPolicy); + validateOptionalFields(optionalFields); + validateDesiredCapacityType( + optionalFields != null ? optionalFields.desiredCapacityType() : null, + mixedInstancesPolicy); AutoScalingGroup asg = new AutoScalingGroup(); asg.setAutoScalingGroupName(name); @@ -230,6 +253,9 @@ public class AutoScalingService { if (tagPropagateAtLaunch != null) { asg.getTagPropagateAtLaunch().putAll(tagPropagateAtLaunch); } + if (optionalFields != null) { + optionalFields.applyToNewGroup(asg); + } groups.put(key, asg); return asg; } @@ -243,13 +269,15 @@ public class AutoScalingService { Integer defaultCooldown, List availabilityZones, List subnetIds, String healthCheckType, Integer healthCheckGracePeriod, - List terminationPolicies) { + List terminationPolicies, + AsgOptionalFields optionalFields) { AutoScalingGroup asg = requireGroup(region, name); validateLaunchSource(launchConfigName, launchTemplateId, launchTemplateName, mixedInstancesPolicy); if (launchTemplateVersion != null && launchTemplateId == null && launchTemplateName == null) { throw new AwsException("ValidationError", "LaunchTemplateVersion requires a LaunchTemplateId or LaunchTemplateName.", 400); } + validateOptionalFields(optionalFields); rejectDesiredConfigurationUpdateDuringActiveRefresh(region, name, launchConfigName, launchTemplateId, launchTemplateName, launchTemplateVersion, mixedInstancesPolicy); LaunchIdentity effectiveIdentity = effectiveLaunchIdentity(asg, launchConfigName, @@ -260,6 +288,9 @@ public class AutoScalingService { effectiveIdentity.launchTemplateName(), effectiveIdentity.launchTemplateVersion(), effectiveIdentity.mixedInstancesPolicy()); + validateDesiredCapacityType( + effectiveDesiredCapacityType(asg, optionalFields), + effectiveIdentity.mixedInstancesPolicy()); if (launchConfigName != null) { asg.setLaunchConfigurationName(launchConfigName); asg.setLaunchTemplateId(null); @@ -290,6 +321,9 @@ public class AutoScalingService { if (healthCheckType != null) { asg.setHealthCheckType(healthCheckType); } if (healthCheckGracePeriod != null) { asg.setHealthCheckGracePeriod(healthCheckGracePeriod); } if (terminationPolicies != null) { asg.setTerminationPolicies(new ArrayList<>(terminationPolicies)); } + if (optionalFields != null) { + optionalFields.applyToExistingGroup(asg); + } groups.put(asgKey(region, name), asg); } @@ -1040,6 +1074,97 @@ public class AutoScalingService { "A MixedInstancesPolicy must specify a LaunchTemplate with a LaunchTemplateId " + "or LaunchTemplateName.", 400); } + validateLaunchTemplateOverrides(mixedInstancesPolicy); + } + + private static void validateLaunchTemplateOverrides(MixedInstancesPolicy mixedInstancesPolicy) { + for (MixedInstancesPolicy.LaunchTemplateOverride override : overridesOf(mixedInstancesPolicy)) { + MixedInstancesPolicy.InstanceRequirements requirements = override.getInstanceRequirements(); + if (requirements == null || requirements.isEmpty()) { + continue; + } + if (override.getInstanceType() != null) { + throw new AwsException("ValidationError", + INSTANCE_REQUIREMENTS_AND_INSTANCE_TYPE_MESSAGE, 400); + } + if (requirements.getVCpuCount() == null || requirements.getMemoryMiB() == null) { + throw new AwsException("ValidationError", + INSTANCE_REQUIREMENTS_MISSING_RANGES_MESSAGE, 400); + } + } + } + + /** + * Botocore documents {@code DesiredCapacityType} as supported "for attribute-based instance type + * selection only", and it types the member as a plain string rather than an enum, so the rule + * lives in prose and not in the model constraints. + * + *

Attribute-based selection here means the mixed instances policy that the request leaves in + * effect carries at least one launch template override holding a non-empty + * {@code InstanceRequirements}. On create that is the policy the request supplies. On update it + * is the policy the request supplies, or the stored one when the request names no launch source + * at all, or none when the request switches the group to a launch configuration or a plain + * launch template. + * + *

{@code units} is the documented default and stays legal for every group. + */ + private static void validateDesiredCapacityType(String desiredCapacityType, + MixedInstancesPolicy effectivePolicy) { + if (desiredCapacityType == null || DEFAULT_DESIRED_CAPACITY_TYPE.equals(desiredCapacityType)) { + return; + } + if (!usesInstanceRequirements(effectivePolicy)) { + throw new AwsException("ValidationError", + DESIRED_CAPACITY_TYPE_NEEDS_INSTANCE_REQUIREMENTS_MESSAGE, 400); + } + } + + private static String effectiveDesiredCapacityType(AutoScalingGroup asg, + AsgOptionalFields optionalFields) { + if (optionalFields != null && optionalFields.desiredCapacityType() != null) { + return optionalFields.desiredCapacityType(); + } + return asg.getDesiredCapacityType(); + } + + private static boolean usesInstanceRequirements(MixedInstancesPolicy mixedInstancesPolicy) { + for (MixedInstancesPolicy.LaunchTemplateOverride override : overridesOf(mixedInstancesPolicy)) { + MixedInstancesPolicy.InstanceRequirements requirements = override.getInstanceRequirements(); + if (requirements != null && !requirements.isEmpty()) { + return true; + } + } + return false; + } + + private static List overridesOf( + MixedInstancesPolicy mixedInstancesPolicy) { + if (mixedInstancesPolicy == null || mixedInstancesPolicy.getLaunchTemplate() == null) { + return List.of(); + } + List overrides = + mixedInstancesPolicy.getLaunchTemplate().getOverrides(); + return overrides != null ? overrides : List.of(); + } + + private static void validateOptionalFields(AsgOptionalFields optionalFields) { + if (optionalFields == null) { + return; + } + String desiredCapacityType = optionalFields.desiredCapacityType(); + if (desiredCapacityType != null && !DESIRED_CAPACITY_TYPES.contains(desiredCapacityType)) { + throw new AwsException("ValidationError", INVALID_DESIRED_CAPACITY_TYPE_MESSAGE, 400); + } + Integer maxInstanceLifetime = optionalFields.maxInstanceLifetime(); + if (maxInstanceLifetime != null && maxInstanceLifetime != 0 + && maxInstanceLifetime < MIN_MAX_INSTANCE_LIFETIME_SECONDS) { + throw new AwsException("ValidationError", INVALID_MAX_INSTANCE_LIFETIME_MESSAGE, 400); + } + Integer defaultInstanceWarmup = optionalFields.defaultInstanceWarmup(); + if (defaultInstanceWarmup != null + && defaultInstanceWarmup < AsgOptionalFields.DEFAULT_INSTANCE_WARMUP_REMOVAL_SENTINEL) { + throw new AwsException("ValidationError", INVALID_DEFAULT_INSTANCE_WARMUP_MESSAGE, 400); + } } private static boolean hasUsableLaunchTemplate(MixedInstancesPolicy mixedInstancesPolicy) { diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/AsgOptionalFields.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/AsgOptionalFields.java new file mode 100644 index 0000000000..b746c453a8 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/AsgOptionalFields.java @@ -0,0 +1,61 @@ +package io.github.hectorvent.floci.services.autoscaling.model; + +/** + * The optional scalar members that {@code CreateAutoScalingGroup} and + * {@code UpdateAutoScalingGroup} share and that {@code DescribeAutoScalingGroups} echoes back. + * + *

Carried as one object rather than four more positional parameters on + * {@code AutoScalingService.createAutoScalingGroup}, whose argument list is already long. + * + *

A {@code null} component means the request did not set the member. On update that means + * "leave the stored value alone", which is UpdateAutoScalingGroup's partial-update behaviour for + * every other member. + * + *

{@code DefaultInstanceWarmup} carries a sentinel: botocore documents {@code -1} as the value + * that removes a previously set warmup, so it clears the stored value instead of storing -1. + */ +public record AsgOptionalFields(String desiredCapacityType, + Boolean capacityRebalance, + Integer maxInstanceLifetime, + Integer defaultInstanceWarmup) { + + public static final int DEFAULT_INSTANCE_WARMUP_REMOVAL_SENTINEL = -1; + + private static final AsgOptionalFields NONE = new AsgOptionalFields(null, null, null, null); + + public static AsgOptionalFields none() { + return NONE; + } + + /** Applies onto a freshly created group, where every absent member simply stays unset. */ + public void applyToNewGroup(AutoScalingGroup asg) { + asg.setDesiredCapacityType(desiredCapacityType); + asg.setCapacityRebalance(capacityRebalance); + asg.setMaxInstanceLifetime(maxInstanceLifetime); + asg.setDefaultInstanceWarmup(resolvedDefaultInstanceWarmup()); + } + + /** Applies onto an existing group, overwriting only the members this request set. */ + public void applyToExistingGroup(AutoScalingGroup asg) { + if (desiredCapacityType != null) { + asg.setDesiredCapacityType(desiredCapacityType); + } + if (capacityRebalance != null) { + asg.setCapacityRebalance(capacityRebalance); + } + if (maxInstanceLifetime != null) { + asg.setMaxInstanceLifetime(maxInstanceLifetime); + } + if (defaultInstanceWarmup != null) { + asg.setDefaultInstanceWarmup(resolvedDefaultInstanceWarmup()); + } + } + + private Integer resolvedDefaultInstanceWarmup() { + if (defaultInstanceWarmup != null + && defaultInstanceWarmup == DEFAULT_INSTANCE_WARMUP_REMOVAL_SENTINEL) { + return null; + } + return defaultInstanceWarmup; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/AutoScalingGroup.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/AutoScalingGroup.java index 06be420a52..93c89697a1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/AutoScalingGroup.java +++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/AutoScalingGroup.java @@ -42,6 +42,14 @@ public class AutoScalingGroup { private Map tags = new ConcurrentHashMap<>(); private Map tagPropagateAtLaunch = new ConcurrentHashMap<>(); private String status; // null = active, "Delete in progress" = deleting + // The four optional CreateAutoScalingGroup/UpdateAutoScalingGroup members below are boxed and + // left null on purpose. DescribeAutoScalingGroups omits an unset optional member, so a + // primitive field with an initialiser would leak that initialiser into the wire response for + // every group that never set it. + private String desiredCapacityType; + private Boolean capacityRebalance; + private Integer maxInstanceLifetime; + private Integer defaultInstanceWarmup; public AutoScalingGroup() {} @@ -122,4 +130,16 @@ public class AutoScalingGroup { public String getStatus() { return status; } public void setStatus(String v) { this.status = v; } + + public String getDesiredCapacityType() { return desiredCapacityType; } + public void setDesiredCapacityType(String v) { this.desiredCapacityType = v; } + + public Boolean getCapacityRebalance() { return capacityRebalance; } + public void setCapacityRebalance(Boolean v) { this.capacityRebalance = v; } + + public Integer getMaxInstanceLifetime() { return maxInstanceLifetime; } + public void setMaxInstanceLifetime(Integer v) { this.maxInstanceLifetime = v; } + + public Integer getDefaultInstanceWarmup() { return defaultInstanceWarmup; } + public void setDefaultInstanceWarmup(Integer v) { this.defaultInstanceWarmup = v; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/MixedInstancesPolicy.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/MixedInstancesPolicy.java index c4077a2f68..912474fc42 100644 --- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/MixedInstancesPolicy.java +++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/MixedInstancesPolicy.java @@ -58,11 +58,171 @@ public class MixedInstancesPolicy { @JsonIgnoreProperties(ignoreUnknown = true) public static class LaunchTemplateOverride { private String instanceType; + private InstanceRequirements instanceRequirements; public LaunchTemplateOverride() {} public String getInstanceType() { return instanceType; } public void setInstanceType(String v) { this.instanceType = v; } + + public InstanceRequirements getInstanceRequirements() { return instanceRequirements; } + public void setInstanceRequirements(InstanceRequirements v) { this.instanceRequirements = v; } + } + + /** + * Attribute-based instance type selection for one launch template override, the alternative + * to naming an explicit {@code InstanceType}. AWS rejects a request that sets both. + * + *

Covers every member of botocore's {@code InstanceRequirements} shape except + * {@code BaselinePerformanceFactors}. + */ + @RegisterForReflection + @JsonIgnoreProperties(ignoreUnknown = true) + public static class InstanceRequirements { + private IntRange vCpuCount; + private IntRange memoryMiB; + private IntRange networkInterfaceCount; + private IntRange acceleratorCount; + private IntRange acceleratorTotalMemoryMiB; + private IntRange baselineEbsBandwidthMbps; + private DoubleRange memoryGiBPerVCpu; + private DoubleRange totalLocalStorageGB; + private DoubleRange networkBandwidthGbps; + private List cpuManufacturers = new ArrayList<>(); + private List excludedInstanceTypes = new ArrayList<>(); + private List instanceGenerations = new ArrayList<>(); + private List localStorageTypes = new ArrayList<>(); + private List acceleratorTypes = new ArrayList<>(); + private List acceleratorManufacturers = new ArrayList<>(); + private List acceleratorNames = new ArrayList<>(); + private List allowedInstanceTypes = new ArrayList<>(); + private Integer spotMaxPricePercentageOverLowestPrice; + private Integer maxSpotPriceAsPercentageOfOptimalOnDemandPrice; + private Integer onDemandMaxPricePercentageOverLowestPrice; + private String bareMetal; + private String burstablePerformance; + private String localStorage; + private Boolean requireHibernateSupport; + + public InstanceRequirements() {} + + public IntRange getVCpuCount() { return vCpuCount; } + public void setVCpuCount(IntRange v) { this.vCpuCount = v; } + + public IntRange getMemoryMiB() { return memoryMiB; } + public void setMemoryMiB(IntRange v) { this.memoryMiB = v; } + + public IntRange getNetworkInterfaceCount() { return networkInterfaceCount; } + public void setNetworkInterfaceCount(IntRange v) { this.networkInterfaceCount = v; } + + public IntRange getAcceleratorCount() { return acceleratorCount; } + public void setAcceleratorCount(IntRange v) { this.acceleratorCount = v; } + + public IntRange getAcceleratorTotalMemoryMiB() { return acceleratorTotalMemoryMiB; } + public void setAcceleratorTotalMemoryMiB(IntRange v) { this.acceleratorTotalMemoryMiB = v; } + + public IntRange getBaselineEbsBandwidthMbps() { return baselineEbsBandwidthMbps; } + public void setBaselineEbsBandwidthMbps(IntRange v) { this.baselineEbsBandwidthMbps = v; } + + public DoubleRange getMemoryGiBPerVCpu() { return memoryGiBPerVCpu; } + public void setMemoryGiBPerVCpu(DoubleRange v) { this.memoryGiBPerVCpu = v; } + + public DoubleRange getTotalLocalStorageGB() { return totalLocalStorageGB; } + public void setTotalLocalStorageGB(DoubleRange v) { this.totalLocalStorageGB = v; } + + public DoubleRange getNetworkBandwidthGbps() { return networkBandwidthGbps; } + public void setNetworkBandwidthGbps(DoubleRange v) { this.networkBandwidthGbps = v; } + + public List getCpuManufacturers() { return cpuManufacturers; } + public void setCpuManufacturers(List v) { this.cpuManufacturers = v != null ? new ArrayList<>(v) : new ArrayList<>(); } + + public List getExcludedInstanceTypes() { return excludedInstanceTypes; } + public void setExcludedInstanceTypes(List v) { this.excludedInstanceTypes = v != null ? new ArrayList<>(v) : new ArrayList<>(); } + + public List getInstanceGenerations() { return instanceGenerations; } + public void setInstanceGenerations(List v) { this.instanceGenerations = v != null ? new ArrayList<>(v) : new ArrayList<>(); } + + public List getLocalStorageTypes() { return localStorageTypes; } + public void setLocalStorageTypes(List v) { this.localStorageTypes = v != null ? new ArrayList<>(v) : new ArrayList<>(); } + + public List getAcceleratorTypes() { return acceleratorTypes; } + public void setAcceleratorTypes(List v) { this.acceleratorTypes = v != null ? new ArrayList<>(v) : new ArrayList<>(); } + + public List getAcceleratorManufacturers() { return acceleratorManufacturers; } + public void setAcceleratorManufacturers(List v) { this.acceleratorManufacturers = v != null ? new ArrayList<>(v) : new ArrayList<>(); } + + public List getAcceleratorNames() { return acceleratorNames; } + public void setAcceleratorNames(List v) { this.acceleratorNames = v != null ? new ArrayList<>(v) : new ArrayList<>(); } + + public List getAllowedInstanceTypes() { return allowedInstanceTypes; } + public void setAllowedInstanceTypes(List v) { this.allowedInstanceTypes = v != null ? new ArrayList<>(v) : new ArrayList<>(); } + + public Integer getSpotMaxPricePercentageOverLowestPrice() { return spotMaxPricePercentageOverLowestPrice; } + public void setSpotMaxPricePercentageOverLowestPrice(Integer v) { this.spotMaxPricePercentageOverLowestPrice = v; } + + public Integer getMaxSpotPriceAsPercentageOfOptimalOnDemandPrice() { return maxSpotPriceAsPercentageOfOptimalOnDemandPrice; } + public void setMaxSpotPriceAsPercentageOfOptimalOnDemandPrice(Integer v) { this.maxSpotPriceAsPercentageOfOptimalOnDemandPrice = v; } + + public Integer getOnDemandMaxPricePercentageOverLowestPrice() { return onDemandMaxPricePercentageOverLowestPrice; } + public void setOnDemandMaxPricePercentageOverLowestPrice(Integer v) { this.onDemandMaxPricePercentageOverLowestPrice = v; } + + public String getBareMetal() { return bareMetal; } + public void setBareMetal(String v) { this.bareMetal = v; } + + public String getBurstablePerformance() { return burstablePerformance; } + public void setBurstablePerformance(String v) { this.burstablePerformance = v; } + + public String getLocalStorage() { return localStorage; } + public void setLocalStorage(String v) { this.localStorage = v; } + + public Boolean getRequireHibernateSupport() { return requireHibernateSupport; } + public void setRequireHibernateSupport(Boolean v) { this.requireHibernateSupport = v; } + + public boolean isEmpty() { + return vCpuCount == null && memoryMiB == null && networkInterfaceCount == null + && acceleratorCount == null && acceleratorTotalMemoryMiB == null + && baselineEbsBandwidthMbps == null && memoryGiBPerVCpu == null + && totalLocalStorageGB == null && networkBandwidthGbps == null + && cpuManufacturers.isEmpty() && excludedInstanceTypes.isEmpty() + && instanceGenerations.isEmpty() && localStorageTypes.isEmpty() + && acceleratorTypes.isEmpty() && acceleratorManufacturers.isEmpty() + && acceleratorNames.isEmpty() && allowedInstanceTypes.isEmpty() + && spotMaxPricePercentageOverLowestPrice == null + && maxSpotPriceAsPercentageOfOptimalOnDemandPrice == null + && onDemandMaxPricePercentageOverLowestPrice == null && bareMetal == null + && burstablePerformance == null && localStorage == null + && requireHibernateSupport == null; + } + } + + @RegisterForReflection + @JsonIgnoreProperties(ignoreUnknown = true) + public static class IntRange { + private Integer min; + private Integer max; + + public IntRange() {} + + public Integer getMin() { return min; } + public void setMin(Integer v) { this.min = v; } + + public Integer getMax() { return max; } + public void setMax(Integer v) { this.max = v; } + } + + @RegisterForReflection + @JsonIgnoreProperties(ignoreUnknown = true) + public static class DoubleRange { + private Double min; + private Double max; + + public DoubleRange() {} + + public Double getMin() { return min; } + public void setMin(Double v) { this.min = v; } + + public Double getMax() { return max; } + public void setMax(Double v) { this.max = v; } } @RegisterForReflection diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java index 770aac56b3..c66e93224c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java @@ -36,6 +36,7 @@ import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService; import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension; import io.github.hectorvent.floci.services.autoscaling.AutoScalingService; +import io.github.hectorvent.floci.services.autoscaling.model.AsgOptionalFields; import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup; import io.github.hectorvent.floci.services.autoscaling.model.LaunchConfiguration; import io.github.hectorvent.floci.services.autoscaling.model.MixedInstancesPolicy; @@ -854,7 +855,8 @@ public class CloudFormationResourceProvisioner { blankToNull(launchConfigName), blankToNull(launchTemplateId), blankToNull(launchTemplateName), blankToNull(launchTemplateVersion), mixedInstancesPolicy, minSize, maxSize, desiredCapacity, cooldown, - availabilityZones, subnetIds, healthCheckType, healthCheckGracePeriod, terminationPolicies); + availabilityZones, subnetIds, healthCheckType, healthCheckGracePeriod, terminationPolicies, + AsgOptionalFields.none()); asg = requireAutoScalingGroup(region, name); } else { asg = autoScalingService.createAutoScalingGroup(region, name, @@ -866,7 +868,8 @@ public class CloudFormationResourceProvisioner { resolveStringList(props, "LoadBalancerNames", engine), healthCheckType, healthCheckGracePeriod, terminationPolicies, resolveAsgTags(props, engine), - resolveAsgTagPropagation(props, engine)); + resolveAsgTagPropagation(props, engine), + AsgOptionalFields.none()); deleteRenamedResource(priorPhysicalId, name, n -> autoScalingService.deleteAutoScalingGroup(region, n, true), "Auto Scaling group"); } diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingGroupOptionalFieldsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingGroupOptionalFieldsIntegrationTest.java new file mode 100644 index 0000000000..f5ca1e3694 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingGroupOptionalFieldsIntegrationTest.java @@ -0,0 +1,454 @@ +package io.github.hectorvent.floci.services.autoscaling; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; + +/** + * Wire-level coverage for the optional CreateAutoScalingGroup/UpdateAutoScalingGroup members that + * DescribeAutoScalingGroups echoes back: DesiredCapacityType, CapacityRebalance, + * MaxInstanceLifetime, DefaultInstanceWarmup, and a mixed instances policy launch template + * override that selects instance types by requirements instead of by name. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class AutoScalingGroupOptionalFieldsIntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260501/us-east-1/autoscaling/aws4_request"; + private static final String EC2_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260501/us-east-1/ec2/aws4_request"; + + private static final String GROUP = "opt-fields-asg"; + private static final String BARE_GROUP = "opt-fields-bare-asg"; + private static final String REQUIREMENTS_GROUP = "opt-fields-requirements-asg"; + + private static final String OVERRIDE_REQUIREMENTS = + "MixedInstancesPolicy.LaunchTemplate.Overrides.member.1.InstanceRequirements"; + + private static String launchTemplateId; + + // DesiredCapacityType is legal only for attribute-based instance type selection, so the group the + // later ordered tests build on is created from a mixed instances policy whose override selects + // instance types by InstanceRequirements rather than from a launch template naming t3.micro. + @Test + @Order(1) + void createGroupCarryingEveryOptionalField() { + launchTemplateId = createLaunchTemplate("opt-fields-lt"); + + given() + .formParam("Action", "CreateAutoScalingGroup") + .formParam("AutoScalingGroupName", GROUP) + .formParam("MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.LaunchTemplateId", + launchTemplateId) + .formParam("MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.Version", "1") + .formParam(OVERRIDE_REQUIREMENTS + ".VCpuCount.Min", "2") + .formParam(OVERRIDE_REQUIREMENTS + ".VCpuCount.Max", "8") + .formParam(OVERRIDE_REQUIREMENTS + ".MemoryMiB.Min", "2048") + .formParam(OVERRIDE_REQUIREMENTS + ".MemoryMiB.Max", "16384") + .formParam("MinSize", "0") + .formParam("MaxSize", "4") + .formParam("DesiredCapacity", "0") + .formParam("AvailabilityZones.member.1", "us-east-1a") + .formParam("DesiredCapacityType", "vcpu") + .formParam("CapacityRebalance", "true") + .formParam("MaxInstanceLifetime", "604800") + .formParam("DefaultInstanceWarmup", "120") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("CreateAutoScalingGroupResponse")); + + describe(GROUP) + .body(containsString("vcpu")) + .body(containsString("true")) + .body(containsString("604800")) + .body(containsString("120")) + .body(containsString("28")) + .body(containsString("204816384")); + } + + @Test + @Order(2) + void groupThatSetsNoneOfThemOmitsThemFromDescribe() { + given() + .formParam("Action", "CreateAutoScalingGroup") + .formParam("AutoScalingGroupName", BARE_GROUP) + .formParam("LaunchTemplate.LaunchTemplateId", launchTemplateId) + .formParam("LaunchTemplate.Version", "1") + .formParam("MinSize", "0") + .formParam("MaxSize", "2") + .formParam("DesiredCapacity", "0") + .formParam("AvailabilityZones.member.1", "us-east-1a") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200); + + describe(BARE_GROUP) + .body(not(containsString(""))) + .body(not(containsString(""))) + .body(not(containsString(""))) + .body(not(containsString(""))); + } + + // The request names no launch source, so the stored attribute-based policy stays in effect and + // memory-mib remains legal. + @Test + @Order(3) + void updateOverwritesOnlyTheOptionalFieldsTheRequestCarries() { + given() + .formParam("Action", "UpdateAutoScalingGroup") + .formParam("AutoScalingGroupName", GROUP) + .formParam("MaxInstanceLifetime", "86400") + .formParam("DesiredCapacityType", "memory-mib") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("UpdateAutoScalingGroupResponse")); + + describe(GROUP) + .body(containsString("86400")) + .body(containsString("memory-mib")) + .body(containsString("true")) + .body(containsString("120")); + } + + @Test + @Order(4) + void maxInstanceLifetimeAcceptsTheZeroSentinel() { + given() + .formParam("Action", "UpdateAutoScalingGroup") + .formParam("AutoScalingGroupName", GROUP) + .formParam("MaxInstanceLifetime", "0") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200); + + describe(GROUP).body(containsString("0")); + } + + @Test + @Order(5) + void defaultInstanceWarmupMinusOneRemovesThePreviouslySetValue() { + given() + .formParam("Action", "UpdateAutoScalingGroup") + .formParam("AutoScalingGroupName", GROUP) + .formParam("DefaultInstanceWarmup", "-1") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200); + + describe(GROUP) + .body(not(containsString(""))) + .body(containsString("true")); + } + + @Test + @Order(6) + void createRejectsAnUnknownDesiredCapacityType() { + given() + .formParam("Action", "CreateAutoScalingGroup") + .formParam("AutoScalingGroupName", "opt-fields-bad-capacity-type") + .formParam("LaunchTemplate.LaunchTemplateId", launchTemplateId) + .formParam("MinSize", "0") + .formParam("MaxSize", "1") + .formParam("AvailabilityZones.member.1", "us-east-1a") + .formParam("DesiredCapacityType", "gpu") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("units, vcpu, memory-mib")); + } + + @Test + @Order(7) + void createRejectsAMaxInstanceLifetimeUnderOneDay() { + given() + .formParam("Action", "CreateAutoScalingGroup") + .formParam("AutoScalingGroupName", "opt-fields-bad-lifetime") + .formParam("LaunchTemplate.LaunchTemplateId", launchTemplateId) + .formParam("MinSize", "0") + .formParam("MaxSize", "1") + .formParam("AvailabilityZones.member.1", "us-east-1a") + .formParam("MaxInstanceLifetime", "3600") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("MaxInstanceLifetime")); + } + + @Test + @Order(8) + void mixedInstancesPolicyOverrideRoundTripsInstanceRequirements() { + String prefix = OVERRIDE_REQUIREMENTS; + + given() + .formParam("Action", "CreateAutoScalingGroup") + .formParam("AutoScalingGroupName", REQUIREMENTS_GROUP) + .formParam("MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.LaunchTemplateId", + launchTemplateId) + .formParam("MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.Version", "1") + .formParam(prefix + ".VCpuCount.Min", "2") + .formParam(prefix + ".VCpuCount.Max", "8") + .formParam(prefix + ".MemoryMiB.Min", "2048") + .formParam(prefix + ".MemoryMiB.Max", "16384") + .formParam(prefix + ".MemoryGiBPerVCpu.Min", "2.0") + .formParam(prefix + ".NetworkInterfaceCount.Min", "1") + .formParam(prefix + ".NetworkInterfaceCount.Max", "4") + .formParam(prefix + ".AcceleratorCount.Max", "2") + .formParam(prefix + ".AcceleratorTotalMemoryMiB.Min", "1024") + .formParam(prefix + ".BaselineEbsBandwidthMbps.Min", "125") + .formParam(prefix + ".TotalLocalStorageGB.Max", "500.0") + .formParam(prefix + ".NetworkBandwidthGbps.Min", "1.5") + .formParam(prefix + ".CpuManufacturers.member.1", "intel") + .formParam(prefix + ".CpuManufacturers.member.2", "amd") + .formParam(prefix + ".ExcludedInstanceTypes.member.1", "m1.*") + .formParam(prefix + ".InstanceGenerations.member.1", "current") + .formParam(prefix + ".LocalStorageTypes.member.1", "ssd") + .formParam(prefix + ".AcceleratorTypes.member.1", "gpu") + .formParam(prefix + ".AcceleratorManufacturers.member.1", "nvidia") + .formParam(prefix + ".AcceleratorNames.member.1", "t4") + .formParam(prefix + ".AllowedInstanceTypes.member.1", "m6i.*") + .formParam(prefix + ".BareMetal", "excluded") + .formParam(prefix + ".BurstablePerformance", "included") + .formParam(prefix + ".LocalStorage", "required") + .formParam(prefix + ".RequireHibernateSupport", "false") + .formParam(prefix + ".SpotMaxPricePercentageOverLowestPrice", "100") + .formParam(prefix + ".MaxSpotPriceAsPercentageOfOptimalOnDemandPrice", "90") + .formParam(prefix + ".OnDemandMaxPricePercentageOverLowestPrice", "20") + .formParam("MinSize", "0") + .formParam("MaxSize", "4") + .formParam("DesiredCapacity", "0") + .formParam("DesiredCapacityType", "units") + .formParam("AvailabilityZones.member.1", "us-east-1a") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("CreateAutoScalingGroupResponse")); + + describe(REQUIREMENTS_GROUP) + .body(containsString("")) + .body(containsString("28")) + .body(containsString("204816384")) + .body(containsString("2.0")) + .body(containsString("14")) + .body(containsString("2")) + .body(containsString("1024")) + .body(containsString("125")) + .body(containsString("500.0")) + .body(containsString("1.5")) + .body(containsString("intelamd")) + .body(containsString("m1.*")) + .body(containsString("current")) + .body(containsString("ssd")) + .body(containsString("gpu")) + .body(containsString("nvidia")) + .body(containsString("t4")) + .body(containsString("m6i.*")) + .body(containsString("excluded")) + .body(containsString("included")) + .body(containsString("required")) + .body(containsString("false")) + .body(containsString("100")) + .body(containsString("90" + + "")) + .body(containsString("20" + + "")) + .body(containsString("units")); + } + + @Test + @Order(9) + void overrideRejectsInstanceTypeAlongsideInstanceRequirements() { + given() + .formParam("Action", "CreateAutoScalingGroup") + .formParam("AutoScalingGroupName", "opt-fields-conflicting-override") + .formParam("MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.LaunchTemplateId", + launchTemplateId) + .formParam("MixedInstancesPolicy.LaunchTemplate.Overrides.member.1.InstanceType", "m6i.large") + .formParam("MixedInstancesPolicy.LaunchTemplate.Overrides.member.1." + + "InstanceRequirements.VCpuCount.Min", "2") + .formParam("MinSize", "0") + .formParam("MaxSize", "1") + .formParam("AvailabilityZones.member.1", "us-east-1a") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("InstanceRequirements")); + } + + @Test + @Order(10) + void createRejectsVcpuDesiredCapacityTypeWithoutAttributeBasedSelection() { + given() + .formParam("Action", "CreateAutoScalingGroup") + .formParam("AutoScalingGroupName", "opt-fields-fixed-type-vcpu") + .formParam("LaunchTemplate.LaunchTemplateId", launchTemplateId) + .formParam("LaunchTemplate.Version", "1") + .formParam("MinSize", "0") + .formParam("MaxSize", "1") + .formParam("AvailabilityZones.member.1", "us-east-1a") + .formParam("DesiredCapacityType", "vcpu") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("attribute-based instance type selection only")); + } + + @Test + @Order(11) + void updateRejectsMemoryMibDesiredCapacityTypeWithoutAttributeBasedSelection() { + given() + .formParam("Action", "UpdateAutoScalingGroup") + .formParam("AutoScalingGroupName", BARE_GROUP) + .formParam("DesiredCapacityType", "memory-mib") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("attribute-based instance type selection only")); + + describe(BARE_GROUP).body(not(containsString(""))); + } + + @Test + @Order(12) + void updateAcceptsVcpuOnceTheSameRequestSuppliesInstanceRequirements() { + given() + .formParam("Action", "UpdateAutoScalingGroup") + .formParam("AutoScalingGroupName", BARE_GROUP) + .formParam("MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.LaunchTemplateId", + launchTemplateId) + .formParam("MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.Version", "1") + .formParam(OVERRIDE_REQUIREMENTS + ".VCpuCount.Min", "4") + .formParam(OVERRIDE_REQUIREMENTS + ".MemoryMiB.Min", "8192") + .formParam("DesiredCapacityType", "vcpu") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200); + + describe(BARE_GROUP) + .body(containsString("vcpu")) + .body(containsString("4")) + .body(containsString("8192")); + } + + @Test + @Order(13) + void createRejectsAnInstanceRequirementsOverrideMissingMemoryMiB() { + given() + .formParam("Action", "CreateAutoScalingGroup") + .formParam("AutoScalingGroupName", "opt-fields-partial-requirements") + .formParam("MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.LaunchTemplateId", + launchTemplateId) + .formParam("MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.Version", "1") + .formParam(OVERRIDE_REQUIREMENTS + ".VCpuCount.Min", "2") + .formParam("MinSize", "0") + .formParam("MaxSize", "1") + .formParam("AvailabilityZones.member.1", "us-east-1a") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("VCpuCount and MemoryMiB")); + } + + @Test + @Order(14) + void updateRejectsAnInstanceRequirementsOverrideMissingVCpuCount() { + given() + .formParam("Action", "UpdateAutoScalingGroup") + .formParam("AutoScalingGroupName", REQUIREMENTS_GROUP) + .formParam("MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.LaunchTemplateId", + launchTemplateId) + .formParam("MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.Version", "1") + .formParam(OVERRIDE_REQUIREMENTS + ".MemoryMiB.Min", "2048") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("VCpuCount and MemoryMiB")); + + describe(REQUIREMENTS_GROUP).body(containsString("28")); + } + + @Test + @Order(15) + void cleanUp() { + for (String name : new String[] {GROUP, BARE_GROUP, REQUIREMENTS_GROUP}) { + given() + .formParam("Action", "DeleteAutoScalingGroup") + .formParam("AutoScalingGroupName", name) + .formParam("ForceDelete", "true") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200); + } + } + + private static ValidatableResponse describe(String name) { + return given() + .formParam("Action", "DescribeAutoScalingGroups") + .formParam("AutoScalingGroupNames.member.1", name) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200); + } + + private static String createLaunchTemplate(String name) { + return given() + .formParam("Action", "CreateLaunchTemplate") + .formParam("LaunchTemplateName", name) + .formParam("LaunchTemplateData.ImageId", "ami-12345678") + .formParam("LaunchTemplateData.InstanceType", "t3.micro") + .header("Authorization", EC2_AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .extract().path("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandlerTest.java index f03321ecf6..0423f4408e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandlerTest.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.autoscaling; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.services.autoscaling.model.AsgInstance; +import io.github.hectorvent.floci.services.autoscaling.model.AsgOptionalFields; import jakarta.ws.rs.core.MultivaluedHashMap; import jakarta.ws.rs.core.Response; import org.junit.jupiter.api.Test; @@ -9,6 +10,7 @@ import org.junit.jupiter.api.Test; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class AutoScalingQueryHandlerTest { @@ -37,7 +39,7 @@ class AutoScalingQueryHandlerTest { "EC2", 0, List.of("Default"), - java.util.Map.of(), java.util.Map.of()); + java.util.Map.of(), java.util.Map.of(), AsgOptionalFields.none()); AutoScalingQueryHandler handler = new AutoScalingQueryHandler(service); MultivaluedHashMap startParams = new MultivaluedHashMap<>(); @@ -103,7 +105,7 @@ class AutoScalingQueryHandlerTest { 0, List.of("Default"), java.util.Map.of(), - java.util.Map.of()); + java.util.Map.of(), AsgOptionalFields.none()); AsgInstance instance = new AsgInstance(); instance.setInstanceId("i-original"); instance.setAvailabilityZone("us-east-1a"); @@ -158,7 +160,7 @@ class AutoScalingQueryHandlerTest { "EC2", 0, List.of("Default"), - java.util.Map.of(), java.util.Map.of()); + java.util.Map.of(), java.util.Map.of(), AsgOptionalFields.none()); AsgInstance instance = new AsgInstance(); instance.setInstanceId("i-current"); instance.setAvailabilityZone("us-east-1a"); @@ -191,7 +193,7 @@ class AutoScalingQueryHandlerTest { service.regionResolver = new RegionResolver(REGION, "000000000000"); service.createAutoScalingGroup(REGION, "protected-asg", null, "lt", null, "1", null, 0, 2, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), - "EC2", 0, List.of("Default"), java.util.Map.of(), java.util.Map.of()); + "EC2", 0, List.of("Default"), java.util.Map.of(), java.util.Map.of(), AsgOptionalFields.none()); AsgInstance instance = new AsgInstance(); instance.setInstanceId("i-protected"); instance.setLifecycleState("InService"); @@ -218,7 +220,7 @@ class AutoScalingQueryHandlerTest { service.regionResolver = new RegionResolver(REGION, "000000000000"); service.createAutoScalingGroup(REGION, "health-asg", null, "lt", null, "1", null, 0, 2, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), - "EC2", 0, List.of("Default"), java.util.Map.of(), java.util.Map.of()); + "EC2", 0, List.of("Default"), java.util.Map.of(), java.util.Map.of(), AsgOptionalFields.none()); AsgInstance instance = new AsgInstance(); instance.setInstanceId("i-unhealthy"); instance.setLifecycleState("InService"); @@ -244,7 +246,7 @@ class AutoScalingQueryHandlerTest { service.regionResolver = new RegionResolver(REGION, "000000000000"); service.createAutoScalingGroup(REGION, "no-protection-flag-asg", null, "lt", null, "1", null, 0, 2, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), - "EC2", 0, List.of("Default"), java.util.Map.of(), java.util.Map.of()); + "EC2", 0, List.of("Default"), java.util.Map.of(), java.util.Map.of(), AsgOptionalFields.none()); AsgInstance instance = new AsgInstance(); instance.setInstanceId("i-flagless"); instance.setLifecycleState("InService"); @@ -273,7 +275,7 @@ class AutoScalingQueryHandlerTest { service.regionResolver = new RegionResolver(REGION, "000000000000"); service.createAutoScalingGroup(REGION, "malformed-flag-asg", null, "lt", null, "1", null, 0, 2, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), - "EC2", 0, List.of("Default"), java.util.Map.of(), java.util.Map.of()); + "EC2", 0, List.of("Default"), java.util.Map.of(), java.util.Map.of(), AsgOptionalFields.none()); AsgInstance instance = new AsgInstance(); instance.setInstanceId("i-malformed"); instance.setLifecycleState("InService"); @@ -301,7 +303,7 @@ class AutoScalingQueryHandlerTest { service.regionResolver = new RegionResolver(REGION, "000000000000"); service.createAutoScalingGroup(REGION, "grace-asg", null, "lt", null, "1", null, 0, 2, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), - "EC2", 0, List.of("Default"), java.util.Map.of(), java.util.Map.of()); + "EC2", 0, List.of("Default"), java.util.Map.of(), java.util.Map.of(), AsgOptionalFields.none()); AsgInstance instance = new AsgInstance(); instance.setInstanceId("i-grace"); instance.setLifecycleState("InService"); @@ -342,7 +344,7 @@ class AutoScalingQueryHandlerTest { "EC2", 0, List.of("Default"), - java.util.Map.of(), java.util.Map.of()); + java.util.Map.of(), java.util.Map.of(), AsgOptionalFields.none()); AutoScalingQueryHandler handler = new AutoScalingQueryHandler(service); MultivaluedHashMap putParams = new MultivaluedHashMap<>(); @@ -419,4 +421,62 @@ class AutoScalingQueryHandlerTest { assertTrue(xml.contains("25")); assertTrue(xml.contains("capacity-optimized")); } + + @Test + void overrideThatSetsOnlyInstanceRequirementsSurvivesCreateAndDescribe() { + AutoScalingService service = new AutoScalingService(); + service.regionResolver = new RegionResolver(REGION, "000000000000"); + AutoScalingQueryHandler handler = new AutoScalingQueryHandler(service); + + String overrides = "MixedInstancesPolicy.LaunchTemplate.Overrides.member."; + MultivaluedHashMap createParams = new MultivaluedHashMap<>(); + createParams.add("AutoScalingGroupName", "requirements-asg"); + createParams.add("MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.LaunchTemplateId", "lt-1"); + createParams.add(overrides + "1.InstanceRequirements.VCpuCount.Min", "2"); + createParams.add(overrides + "1.InstanceRequirements.VCpuCount.Max", "8"); + createParams.add(overrides + "1.InstanceRequirements.MemoryMiB.Min", "2048"); + createParams.add(overrides + "1.InstanceRequirements.CpuManufacturers.member.1", "intel"); + createParams.add(overrides + "2.InstanceType", "m6i.large"); + createParams.add("MinSize", "0"); + createParams.add("MaxSize", "3"); + createParams.add("AvailabilityZones.member.1", "us-east-1a"); + + assertEquals(200, handler.handle("CreateAutoScalingGroup", createParams, REGION).getStatus()); + + MultivaluedHashMap describeParams = new MultivaluedHashMap<>(); + describeParams.add("AutoScalingGroupNames.member.1", "requirements-asg"); + Response describeResponse = handler.handle("DescribeAutoScalingGroups", describeParams, REGION); + + assertEquals(200, describeResponse.getStatus()); + String xml = (String) describeResponse.getEntity(); + assertTrue(xml.contains("28")); + assertTrue(xml.contains("2048")); + assertTrue(xml.contains("intel")); + assertTrue(xml.contains("m6i.large")); + } + + @Test + void describeOmitsTheOptionalGroupFieldsTheCreateRequestNeverSet() { + AutoScalingService service = new AutoScalingService(); + service.regionResolver = new RegionResolver(REGION, "000000000000"); + AutoScalingQueryHandler handler = new AutoScalingQueryHandler(service); + + MultivaluedHashMap createParams = new MultivaluedHashMap<>(); + createParams.add("AutoScalingGroupName", "bare-asg"); + createParams.add("LaunchTemplate.LaunchTemplateId", "lt-1"); + createParams.add("MinSize", "0"); + createParams.add("MaxSize", "1"); + createParams.add("AvailabilityZones.member.1", "us-east-1a"); + + assertEquals(200, handler.handle("CreateAutoScalingGroup", createParams, REGION).getStatus()); + + MultivaluedHashMap describeParams = new MultivaluedHashMap<>(); + describeParams.add("AutoScalingGroupNames.member.1", "bare-asg"); + String xml = (String) handler.handle("DescribeAutoScalingGroups", describeParams, REGION).getEntity(); + + assertFalse(xml.contains("")); + assertFalse(xml.contains("")); + assertFalse(xml.contains("")); + assertFalse(xml.contains("")); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingServiceTest.java index e856764ab2..06513dd9c4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingServiceTest.java @@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.autoscaling; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.services.autoscaling.model.AsgInstance; +import io.github.hectorvent.floci.services.autoscaling.model.AsgOptionalFields; +import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup; import io.github.hectorvent.floci.services.autoscaling.model.InstanceRefresh; import io.github.hectorvent.floci.services.autoscaling.model.LaunchConfigurationBlockDeviceMapping; import io.github.hectorvent.floci.services.autoscaling.model.MixedInstancesPolicy; @@ -50,7 +52,7 @@ class AutoScalingServiceTest { "EC2", 0, List.of("Default"), - java.util.Map.of(), java.util.Map.of()); + java.util.Map.of(), java.util.Map.of(), AsgOptionalFields.none()); } @Test @@ -122,7 +124,7 @@ class AutoScalingServiceTest { "EC2", 0, List.of("Default"), - java.util.Map.of(), java.util.Map.of())); + java.util.Map.of(), java.util.Map.of(), AsgOptionalFields.none())); assertEquals("ValidationError", error.getErrorCode()); assertEquals(AutoScalingService.MISSING_LAUNCH_TEMPLATE_IMAGE_ID_MESSAGE, error.getMessage()); @@ -280,7 +282,7 @@ class AutoScalingServiceTest { "EC2", 0, List.of("Default"), - java.util.Map.of(), java.util.Map.of())); + java.util.Map.of(), java.util.Map.of(), AsgOptionalFields.none())); assertEquals("ValidationError", error.getErrorCode()); assertEquals(AutoScalingService.INVALID_LAUNCH_TEMPLATE_MESSAGE, error.getMessage()); @@ -313,7 +315,7 @@ class AutoScalingServiceTest { null, null, null, - null)); + null, AsgOptionalFields.none())); assertEquals("ValidationError", error.getErrorCode()); assertEquals(AutoScalingService.MISSING_LAUNCH_TEMPLATE_IMAGE_ID_MESSAGE, error.getMessage()); @@ -340,7 +342,7 @@ class AutoScalingServiceTest { null, null, null, - null)); + null, AsgOptionalFields.none())); assertEquals("ValidationError", error.getErrorCode()); assertEquals("LaunchTemplateVersion requires a LaunchTemplateId or LaunchTemplateName.", error.getMessage()); @@ -373,7 +375,7 @@ class AutoScalingServiceTest { null, null, null, - null)); + null, AsgOptionalFields.none())); assertEquals("ValidationError", error.getErrorCode()); assertEquals(AutoScalingService.ACTIVE_INSTANCE_REFRESH_DESIRED_CONFIGURATION_MESSAGE, error.getMessage()); @@ -684,7 +686,7 @@ class AutoScalingServiceTest { "EC2", 0, List.of("Default"), - java.util.Map.of(), java.util.Map.of()); + java.util.Map.of(), java.util.Map.of(), AsgOptionalFields.none()); } @Test @@ -937,7 +939,7 @@ class AutoScalingServiceTest { service.putWarmPool(REGION, "test-asg", null, 1, "Stopped", false); service.createAutoScalingGroup("eu-west-1", "test-asg", null, "lt-original", null, "1", null, 0, 3, 1, 300, List.of("eu-west-1a"), List.of("subnet-12345678"), List.of(), List.of(), - "EC2", 0, List.of("Default"), Map.of(), Map.of()); + "EC2", 0, List.of("Default"), Map.of(), Map.of(), AsgOptionalFields.none()); service.putScheduledUpdateGroupAction("eu-west-1", "test-asg", "morning", null, null, "0 7 * * 1-5", null, 0, 1, 1); @@ -947,4 +949,286 @@ class AutoScalingServiceTest { assertThrows(AwsException.class, () -> service.describeWarmPool(REGION, "test-asg")); assertEquals(1, service.describeScheduledActions("eu-west-1", "test-asg", List.of()).size()); } + + @Test + void createAutoScalingGroupStoresTheOptionalFieldsAndLeavesUnsetOnesNull() { + service.createAutoScalingGroup(REGION, "optional-asg", null, null, null, null, + attributeBasedPolicy(2, 2048), + 0, 3, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), "EC2", 0, + List.of("Default"), Map.of(), Map.of(), + new AsgOptionalFields("vcpu", true, 604800, 120)); + + AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("optional-asg")).getFirst(); + + assertEquals("vcpu", group.getDesiredCapacityType()); + assertEquals(Boolean.TRUE, group.getCapacityRebalance()); + assertEquals(604800, group.getMaxInstanceLifetime()); + assertEquals(120, group.getDefaultInstanceWarmup()); + } + + @Test + void aFreshAutoScalingGroupCarriesNoInitialiserForTheOptionalFields() { + AutoScalingGroup group = new AutoScalingGroup(); + + assertNull(group.getDesiredCapacityType()); + assertNull(group.getCapacityRebalance()); + assertNull(group.getMaxInstanceLifetime()); + assertNull(group.getDefaultInstanceWarmup()); + } + + @Test + void createAutoScalingGroupLeavesEveryOptionalFieldNullWhenTheRequestOmitsThem() { + AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst(); + + assertNull(group.getDesiredCapacityType()); + assertNull(group.getCapacityRebalance()); + assertNull(group.getMaxInstanceLifetime()); + assertNull(group.getDefaultInstanceWarmup()); + } + + @Test + void updateAutoScalingGroupOverwritesOnlyTheOptionalFieldsTheRequestCarries() { + service.createAutoScalingGroup(REGION, "partial-update-asg", null, null, null, null, + attributeBasedPolicy(2, 2048), + 0, 3, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), "EC2", 0, + List.of("Default"), Map.of(), Map.of(), + new AsgOptionalFields("vcpu", true, 604800, 120)); + + service.updateAutoScalingGroup(REGION, "partial-update-asg", null, null, null, null, null, + null, null, null, null, null, null, null, null, null, + new AsgOptionalFields(null, null, 86400, null)); + + AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("partial-update-asg")).getFirst(); + + assertEquals(86400, group.getMaxInstanceLifetime()); + assertEquals("vcpu", group.getDesiredCapacityType()); + assertEquals(Boolean.TRUE, group.getCapacityRebalance()); + assertEquals(120, group.getDefaultInstanceWarmup()); + } + + @Test + void updateAutoScalingGroupClearsDefaultInstanceWarmupOnTheRemovalSentinel() { + service.createAutoScalingGroup(REGION, "warmup-asg", null, "lt-original", null, "1", null, + 0, 3, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), "EC2", 0, + List.of("Default"), Map.of(), Map.of(), + new AsgOptionalFields(null, null, null, 300)); + + service.updateAutoScalingGroup(REGION, "warmup-asg", null, null, null, null, null, + null, null, null, null, null, null, null, null, null, + new AsgOptionalFields(null, null, null, -1)); + + AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("warmup-asg")).getFirst(); + + assertNull(group.getDefaultInstanceWarmup()); + } + + @Test + void createAutoScalingGroupRejectsAnUnknownDesiredCapacityType() { + AwsException error = assertThrows(AwsException.class, () -> service.createAutoScalingGroup(REGION, + "bad-capacity-type-asg", null, "lt-original", null, "1", null, + 0, 3, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), "EC2", 0, + List.of("Default"), Map.of(), Map.of(), + new AsgOptionalFields("gpu", null, null, null))); + + assertEquals("ValidationError", error.getErrorCode()); + assertEquals(AutoScalingService.INVALID_DESIRED_CAPACITY_TYPE_MESSAGE, error.getMessage()); + assertEquals(400, error.getHttpStatus()); + } + + @Test + void createAutoScalingGroupRejectsAMaxInstanceLifetimeUnderOneDayButAcceptsZero() { + AwsException error = assertThrows(AwsException.class, () -> service.createAutoScalingGroup(REGION, + "short-lifetime-asg", null, "lt-original", null, "1", null, + 0, 3, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), "EC2", 0, + List.of("Default"), Map.of(), Map.of(), + new AsgOptionalFields(null, null, 3600, null))); + + assertEquals(AutoScalingService.INVALID_MAX_INSTANCE_LIFETIME_MESSAGE, error.getMessage()); + + service.createAutoScalingGroup(REGION, "unbounded-lifetime-asg", null, "lt-original", null, "1", null, + 0, 3, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), "EC2", 0, + List.of("Default"), Map.of(), Map.of(), + new AsgOptionalFields(null, null, 0, null)); + + assertEquals(0, service.describeAutoScalingGroups(REGION, List.of("unbounded-lifetime-asg")) + .getFirst().getMaxInstanceLifetime()); + } + + @Test + void createAutoScalingGroupRejectsADefaultInstanceWarmupBelowTheRemovalSentinel() { + AwsException error = assertThrows(AwsException.class, () -> service.createAutoScalingGroup(REGION, + "bad-warmup-asg", null, "lt-original", null, "1", null, + 0, 3, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), "EC2", 0, + List.of("Default"), Map.of(), Map.of(), + new AsgOptionalFields(null, null, null, -2))); + + assertEquals(AutoScalingService.INVALID_DEFAULT_INSTANCE_WARMUP_MESSAGE, error.getMessage()); + } + + @Test + void createAutoScalingGroupRejectsAnOverrideSettingBothInstanceTypeAndInstanceRequirements() { + MixedInstancesPolicy.InstanceRequirements requirements = new MixedInstancesPolicy.InstanceRequirements(); + MixedInstancesPolicy.IntRange vCpuCount = new MixedInstancesPolicy.IntRange(); + vCpuCount.setMin(2); + requirements.setVCpuCount(vCpuCount); + MixedInstancesPolicy.LaunchTemplateOverride override = new MixedInstancesPolicy.LaunchTemplateOverride(); + override.setInstanceType("m6i.large"); + override.setInstanceRequirements(requirements); + MixedInstancesPolicy.LaunchTemplateSpecification specification = + new MixedInstancesPolicy.LaunchTemplateSpecification(); + specification.setLaunchTemplateId("lt-original"); + MixedInstancesPolicy.LaunchTemplate launchTemplate = new MixedInstancesPolicy.LaunchTemplate(); + launchTemplate.setLaunchTemplateSpecification(specification); + launchTemplate.setOverrides(List.of(override)); + MixedInstancesPolicy policy = new MixedInstancesPolicy(); + policy.setLaunchTemplate(launchTemplate); + + AwsException error = assertThrows(AwsException.class, () -> service.createAutoScalingGroup(REGION, + "conflicting-override-asg", null, null, null, null, policy, + 0, 3, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), "EC2", 0, + List.of("Default"), Map.of(), Map.of(), AsgOptionalFields.none())); + + assertEquals("ValidationError", error.getErrorCode()); + assertEquals(AutoScalingService.INSTANCE_REQUIREMENTS_AND_INSTANCE_TYPE_MESSAGE, error.getMessage()); + } + + @Test + void createAutoScalingGroupRejectsVcpuDesiredCapacityTypeWhenInstanceTypesAreNamed() { + AwsException error = assertThrows(AwsException.class, () -> service.createAutoScalingGroup(REGION, + "fixed-type-vcpu-asg", null, "lt-original", null, "1", null, + 0, 3, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), "EC2", 0, + List.of("Default"), Map.of(), Map.of(), + new AsgOptionalFields("vcpu", null, null, null))); + + assertEquals("ValidationError", error.getErrorCode()); + assertEquals(AutoScalingService.DESIRED_CAPACITY_TYPE_NEEDS_INSTANCE_REQUIREMENTS_MESSAGE, + error.getMessage()); + assertEquals(400, error.getHttpStatus()); + } + + @Test + void createAutoScalingGroupRejectsMemoryMibDesiredCapacityTypeForOverridesNamingInstanceTypes() { + MixedInstancesPolicy.LaunchTemplateOverride override = new MixedInstancesPolicy.LaunchTemplateOverride(); + override.setInstanceType("m6i.large"); + + AwsException error = assertThrows(AwsException.class, () -> service.createAutoScalingGroup(REGION, + "named-override-memory-asg", null, null, null, null, policyWithOverrides(List.of(override)), + 0, 3, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), "EC2", 0, + List.of("Default"), Map.of(), Map.of(), + new AsgOptionalFields("memory-mib", null, null, null))); + + assertEquals(AutoScalingService.DESIRED_CAPACITY_TYPE_NEEDS_INSTANCE_REQUIREMENTS_MESSAGE, + error.getMessage()); + } + + @Test + void createAutoScalingGroupAcceptsUnitsDesiredCapacityTypeWithoutInstanceRequirements() { + service.createAutoScalingGroup(REGION, "units-asg", null, "lt-original", null, "1", null, + 0, 3, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), "EC2", 0, + List.of("Default"), Map.of(), Map.of(), + new AsgOptionalFields("units", null, null, null)); + + assertEquals("units", service.describeAutoScalingGroups(REGION, List.of("units-asg")) + .getFirst().getDesiredCapacityType()); + } + + @Test + void updateAutoScalingGroupRejectsVcpuDesiredCapacityTypeWhenInstanceTypesAreNamed() { + AwsException error = assertThrows(AwsException.class, () -> service.updateAutoScalingGroup(REGION, + "test-asg", null, null, null, null, null, + null, null, null, null, null, null, null, null, null, + new AsgOptionalFields("vcpu", null, null, null))); + + assertEquals(AutoScalingService.DESIRED_CAPACITY_TYPE_NEEDS_INSTANCE_REQUIREMENTS_MESSAGE, + error.getMessage()); + assertNull(service.describeAutoScalingGroups(REGION, List.of("test-asg")) + .getFirst().getDesiredCapacityType()); + } + + @Test + void updateAutoScalingGroupAcceptsVcpuWhenTheSameRequestSuppliesInstanceRequirements() { + service.updateAutoScalingGroup(REGION, "test-asg", null, null, null, null, + attributeBasedPolicy(4, 8192), + null, null, null, null, null, null, null, null, null, + new AsgOptionalFields("vcpu", null, null, null)); + + assertEquals("vcpu", service.describeAutoScalingGroups(REGION, List.of("test-asg")) + .getFirst().getDesiredCapacityType()); + } + + @Test + void updateAutoScalingGroupRejectsDroppingInstanceRequirementsWhileVcpuStaysInEffect() { + service.createAutoScalingGroup(REGION, "drop-requirements-asg", null, null, null, null, + attributeBasedPolicy(2, 2048), + 0, 3, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), "EC2", 0, + List.of("Default"), Map.of(), Map.of(), + new AsgOptionalFields("vcpu", null, null, null)); + + AwsException error = assertThrows(AwsException.class, () -> service.updateAutoScalingGroup(REGION, + "drop-requirements-asg", null, "lt-replacement", null, "1", null, + null, null, null, null, null, null, null, null, null, + AsgOptionalFields.none())); + + assertEquals(AutoScalingService.DESIRED_CAPACITY_TYPE_NEEDS_INSTANCE_REQUIREMENTS_MESSAGE, + error.getMessage()); + } + + @Test + void createAutoScalingGroupRejectsAnOverrideMissingMemoryMiB() { + MixedInstancesPolicy.InstanceRequirements requirements = new MixedInstancesPolicy.InstanceRequirements(); + requirements.setVCpuCount(intRange(2)); + MixedInstancesPolicy.LaunchTemplateOverride override = new MixedInstancesPolicy.LaunchTemplateOverride(); + override.setInstanceRequirements(requirements); + + AwsException error = assertThrows(AwsException.class, () -> service.createAutoScalingGroup(REGION, + "partial-requirements-asg", null, null, null, null, policyWithOverrides(List.of(override)), + 0, 3, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), "EC2", 0, + List.of("Default"), Map.of(), Map.of(), AsgOptionalFields.none())); + + assertEquals("ValidationError", error.getErrorCode()); + assertEquals(AutoScalingService.INSTANCE_REQUIREMENTS_MISSING_RANGES_MESSAGE, error.getMessage()); + assertEquals(400, error.getHttpStatus()); + } + + @Test + void updateAutoScalingGroupRejectsAnOverrideMissingVCpuCount() { + MixedInstancesPolicy.InstanceRequirements requirements = new MixedInstancesPolicy.InstanceRequirements(); + requirements.setMemoryMiB(intRange(2048)); + MixedInstancesPolicy.LaunchTemplateOverride override = new MixedInstancesPolicy.LaunchTemplateOverride(); + override.setInstanceRequirements(requirements); + + AwsException error = assertThrows(AwsException.class, () -> service.updateAutoScalingGroup(REGION, + "test-asg", null, null, null, null, policyWithOverrides(List.of(override)), + null, null, null, null, null, null, null, null, null, AsgOptionalFields.none())); + + assertEquals(AutoScalingService.INSTANCE_REQUIREMENTS_MISSING_RANGES_MESSAGE, error.getMessage()); + } + + private static MixedInstancesPolicy attributeBasedPolicy(int minVCpuCount, int minMemoryMiB) { + MixedInstancesPolicy.InstanceRequirements requirements = new MixedInstancesPolicy.InstanceRequirements(); + requirements.setVCpuCount(intRange(minVCpuCount)); + requirements.setMemoryMiB(intRange(minMemoryMiB)); + MixedInstancesPolicy.LaunchTemplateOverride override = new MixedInstancesPolicy.LaunchTemplateOverride(); + override.setInstanceRequirements(requirements); + return policyWithOverrides(List.of(override)); + } + + private static MixedInstancesPolicy policyWithOverrides( + List overrides) { + MixedInstancesPolicy.LaunchTemplateSpecification specification = + new MixedInstancesPolicy.LaunchTemplateSpecification(); + specification.setLaunchTemplateId("lt-original"); + MixedInstancesPolicy.LaunchTemplate launchTemplate = new MixedInstancesPolicy.LaunchTemplate(); + launchTemplate.setLaunchTemplateSpecification(specification); + launchTemplate.setOverrides(overrides); + MixedInstancesPolicy policy = new MixedInstancesPolicy(); + policy.setLaunchTemplate(launchTemplate); + return policy; + } + + private static MixedInstancesPolicy.IntRange intRange(int min) { + MixedInstancesPolicy.IntRange range = new MixedInstancesPolicy.IntRange(); + range.setMin(min); + return range; + } }