Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(ec2): carry the remaining launch template data fields (#3493)

lex00043167793b73
diff --git a/docs/services/ec2.md b/docs/services/ec2.md
index 0346059d6c..d0eaa60a2d 100644
--- a/docs/services/ec2.md
+++ b/docs/services/ec2.md
@@ -554,9 +554,37 @@ These members of `RequestLaunchTemplateData` are stored and read back unchanged
`IamInstanceProfile`, `BlockDeviceMappings`, `NetworkInterfaces`, `TagSpecifications`,
`MetadataOptions`, `Monitoring`, `Placement`, `CpuOptions`, `CreditSpecification`,
`EnclaveOptions`, `HibernationOptions`, `MaintenanceOptions`, `PrivateDnsNameOptions`,
-`CapacityReservationSpecification`, `EbsOptimized`, `DisableApiTermination`, `DisableApiStop`,
+`CapacityReservationSpecification`, `InstanceMarketOptions`, `InstanceRequirements`,
+`EbsOptimized`, `DisableApiTermination`, `DisableApiStop`,
`InstanceInitiatedShutdownBehavior`.
+`InstanceRequirements` carries every member of the service model's
+`InstanceRequirementsRequest`, including the nested `BaselinePerformanceFactors.Cpu.References`.
+Within `NetworkInterfaces`, `ConnectionTrackingSpecification` is stored and read back with all
+three of its timeout members.
+
+Both blocks are validated by `CreateLaunchTemplate` and `CreateLaunchTemplateVersion` before
+anything is stored. An `InstanceRequirements` block must carry `VCpuCount` and `MemoryMiB`, each
+with its `Min`, which the service model declares required; a request missing either fails with
+`MissingParameter`. A connection tracking timeout outside the range its member documents fails
+with `InvalidParameterValue`: `TcpEstablishedTimeout` runs from 60 to 432000 seconds,
+`UdpTimeout` from 30 to 60, and `UdpStreamTimeout` from 60 to 180.
+
+Three combinations the service model documents in prose rather than in its constraints are
+rejected with `InvalidParameterCombination`:
+
+- `InstanceRequirements` and `InstanceType` together. A launch template selects instance types by
+ attribute or by name, not by both.
+- `AllowedInstanceTypes` and `ExcludedInstanceTypes` together inside `InstanceRequirements`.
+- `SpotMaxPricePercentageOverLowestPrice` and `MaxSpotPriceAsPercentageOfOptimalOnDemandPrice`
+ together inside `InstanceRequirements`.
+
+`CreateLaunchTemplateVersion` applies these three to the merged version as well as to the request
+it received, because the merged data is what the version stores. A version that names only
+`InstanceType` against a source version carrying `InstanceRequirements` is therefore rejected: the
+merge inherits the requirements block and cannot express its removal. Omitting `SourceVersion`
+starts from empty data and is how a template moves between the two selection modes.
+
Two behaviours worth calling out, because they are what Terraform reads back:
- **`IamInstanceProfile` keeps the form it was given.** A profile submitted as `Name` reads back as
@@ -583,13 +611,12 @@ Two behaviours worth calling out, because they are what Terraform reads back:
the same field for the initial version it creates.
Members the service model declares that are accepted and ignored rather than stored:
-`InstanceMarketOptions`, `InstanceRequirements`, `LicenseSpecifications`, `ElasticGpuSpecifications`,
-`ElasticInferenceAccelerators`, `NetworkPerformanceOptions`, `Operator`, `SecondaryInterfaces` and
-`SecurityGroups` (security groups by name — resolving names to IDs would need lookup machinery,
+`LicenseSpecifications`, `ElasticGpuSpecifications`, `ElasticInferenceAccelerators`,
+`NetworkPerformanceOptions`, `Operator`, `SecondaryInterfaces` and
+`SecurityGroups` (security groups by name, where resolving names to IDs would need lookup machinery,
including ambiguity handling across VPCs, that no other EC2 action here has either; `RunInstances`
itself only accepts `SecurityGroupId`). Within `NetworkInterfaces`, the IPv4/IPv6 address and
-prefix lists, `EnaSrdSpecification`, `ConnectionTrackingSpecification`, `PrimaryIpv6` and
-`EnaQueueCount` are likewise ignored.
+prefix lists, `EnaSrdSpecification`, `PrimaryIpv6` and `EnaQueueCount` are likewise ignored.
### IAM Instance Profiles
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
index ca25b7e492..d3b3fe4e0d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
@@ -4769,6 +4769,15 @@ public class Ec2QueryHandler {
}
xml.end("groupSet");
}
+ LaunchTemplateData.ConnectionTrackingSpecification tracking =
+ networkInterface.getConnectionTrackingSpecification();
+ if (tracking != null) {
+ xml.start("connectionTrackingSpecification")
+ .elem("tcpEstablishedTimeout", str(tracking.getTcpEstablishedTimeout()))
+ .elem("udpTimeout", str(tracking.getUdpTimeout()))
+ .elem("udpStreamTimeout", str(tracking.getUdpStreamTimeout()))
+ .end("connectionTrackingSpecification");
+ }
xml.end("item");
}
xml.end("networkInterfaceSet");
@@ -4816,6 +4825,23 @@ public class Ec2QueryHandler {
.end("cpuOptions");
}
+ LaunchTemplateData.InstanceMarketOptions marketOptions = data.getInstanceMarketOptions();
+ if (marketOptions != null) {
+ xml.start("instanceMarketOptions")
+ .elem("marketType", marketOptions.getMarketType());
+ LaunchTemplateData.SpotOptions spotOptions = marketOptions.getSpotOptions();
+ if (spotOptions != null) {
+ xml.start("spotOptions")
+ .elem("maxPrice", spotOptions.getMaxPrice())
+ .elem("spotInstanceType", spotOptions.getSpotInstanceType())
+ .elem("blockDurationMinutes", str(spotOptions.getBlockDurationMinutes()))
+ .elem("validUntil", spotOptions.getValidUntil())
+ .elem("instanceInterruptionBehavior", spotOptions.getInstanceInterruptionBehavior())
+ .end("spotOptions");
+ }
+ xml.end("instanceMarketOptions");
+ }
+
LaunchTemplateData.CreditSpecification creditSpecification = data.getCreditSpecification();
if (creditSpecification != null) {
xml.start("creditSpecification")
@@ -4866,6 +4892,10 @@ public class Ec2QueryHandler {
xml.end("capacityReservationSpecification");
}
+ if (data.getInstanceRequirements() != null) {
+ appendInstanceRequirements(xml, data.getInstanceRequirements());
+ }
+
if (!data.getSecurityGroupIds().isEmpty()) {
xml.start("securityGroupIdSet");
for (String securityGroupId : data.getSecurityGroupIds()) {
@@ -4887,6 +4917,79 @@ public class Ec2QueryHandler {
return xml.build();
}
+ /** Renders {@code InstanceRequirements}, whose element names differ from the request's. */
+ private void appendInstanceRequirements(XmlBuilder xml, LaunchTemplateData.InstanceRequirements requirements) {
+ xml.start("instanceRequirements");
+ appendIntRange(xml, "vCpuCount", requirements.getVCpuCount());
+ appendIntRange(xml, "memoryMiB", requirements.getMemoryMiB());
+ appendStringSet(xml, "cpuManufacturerSet", requirements.getCpuManufacturers());
+ appendDoubleRange(xml, "memoryGiBPerVCpu", requirements.getMemoryGiBPerVCpu());
+ appendStringSet(xml, "excludedInstanceTypeSet", requirements.getExcludedInstanceTypes());
+ appendStringSet(xml, "instanceGenerationSet", requirements.getInstanceGenerations());
+ xml.elem("spotMaxPricePercentageOverLowestPrice",
+ str(requirements.getSpotMaxPricePercentageOverLowestPrice()))
+ .elem("onDemandMaxPricePercentageOverLowestPrice",
+ str(requirements.getOnDemandMaxPricePercentageOverLowestPrice()))
+ .elem("bareMetal", requirements.getBareMetal())
+ .elem("burstablePerformance", requirements.getBurstablePerformance())
+ .elem("requireHibernateSupport", str(requirements.getRequireHibernateSupport()));
+ appendIntRange(xml, "networkInterfaceCount", requirements.getNetworkInterfaceCount());
+ xml.elem("localStorage", requirements.getLocalStorage());
+ appendStringSet(xml, "localStorageTypeSet", requirements.getLocalStorageTypes());
+ appendDoubleRange(xml, "totalLocalStorageGB", requirements.getTotalLocalStorageGB());
+ appendIntRange(xml, "baselineEbsBandwidthMbps", requirements.getBaselineEbsBandwidthMbps());
+ appendStringSet(xml, "acceleratorTypeSet", requirements.getAcceleratorTypes());
+ appendIntRange(xml, "acceleratorCount", requirements.getAcceleratorCount());
+ appendStringSet(xml, "acceleratorManufacturerSet", requirements.getAcceleratorManufacturers());
+ appendStringSet(xml, "acceleratorNameSet", requirements.getAcceleratorNames());
+ appendIntRange(xml, "acceleratorTotalMemoryMiB", requirements.getAcceleratorTotalMemoryMiB());
+ appendDoubleRange(xml, "networkBandwidthGbps", requirements.getNetworkBandwidthGbps());
+ appendStringSet(xml, "allowedInstanceTypeSet", requirements.getAllowedInstanceTypes());
+ xml.elem("maxSpotPriceAsPercentageOfOptimalOnDemandPrice",
+ str(requirements.getMaxSpotPriceAsPercentageOfOptimalOnDemandPrice()));
+ LaunchTemplateData.BaselinePerformanceFactors factors = requirements.getBaselinePerformanceFactors();
+ if (factors != null && factors.getCpu() != null) {
+ xml.start("baselinePerformanceFactors").start("cpu").start("referenceSet");
+ for (LaunchTemplateData.PerformanceFactorReference reference : factors.getCpu().getReferences()) {
+ xml.start("item").elem("instanceFamily", reference.getInstanceFamily()).end("item");
+ }
+ xml.end("referenceSet").end("cpu").end("baselinePerformanceFactors");
+ }
+ xml.elem("requireEncryptionInTransit", str(requirements.getRequireEncryptionInTransit()))
+ .end("instanceRequirements");
+ }
+
+ private void appendIntRange(XmlBuilder xml, String element, LaunchTemplateData.IntRange range) {
+ if (range == null) {
+ return;
+ }
+ xml.start(element)
+ .elem("min", str(range.getMin()))
+ .elem("max", str(range.getMax()))
+ .end(element);
+ }
+
+ private void appendDoubleRange(XmlBuilder xml, String element, LaunchTemplateData.DoubleRange range) {
+ if (range == null) {
+ return;
+ }
+ xml.start(element)
+ .elem("min", str(range.getMin()))
+ .elem("max", str(range.getMax()))
+ .end(element);
+ }
+
+ private void appendStringSet(XmlBuilder xml, String element, List<String> values) {
+ if (values.isEmpty()) {
+ return;
+ }
+ xml.start(element);
+ for (String value : values) {
+ xml.elem("item", value);
+ }
+ xml.end(element);
+ }
+
/**
* Parses {@code RequestLaunchTemplateData} from the EC2 query wire format. Parameter names are
* the ones botocore's EC2 serializer emits — list members carry the model's singular
@@ -5015,9 +5118,111 @@ public class Ec2QueryHandler {
}
data.setCapacityReservationSpecification(spec);
}
+
+ if (anyParamStartsWith(p, prefix + ".InstanceMarketOptions.")) {
+ data.setInstanceMarketOptions(parseLaunchTemplateInstanceMarketOptions(
+ p, prefix + ".InstanceMarketOptions."));
+ }
+
+ if (anyParamStartsWith(p, prefix + ".InstanceRequirements.")) {
+ data.setInstanceRequirements(parseLaunchTemplateInstanceRequirements(
+ p, prefix + ".InstanceRequirements."));
+ }
return data;
}
+ private LaunchTemplateData.InstanceMarketOptions parseLaunchTemplateInstanceMarketOptions(
+ MultivaluedMap<String, String> p, String prefix) {
+ LaunchTemplateData.InstanceMarketOptions options = new LaunchTemplateData.InstanceMarketOptions();
+ options.setMarketType(p.getFirst(prefix + "MarketType"));
+ String spotPrefix = prefix + "SpotOptions.";
+ if (anyParamStartsWith(p, spotPrefix)) {
+ LaunchTemplateData.SpotOptions spotOptions = new LaunchTemplateData.SpotOptions();
+ spotOptions.setMaxPrice(p.getFirst(spotPrefix + "MaxPrice"));
+ spotOptions.setSpotInstanceType(p.getFirst(spotPrefix + "SpotInstanceType"));
+ spotOptions.setBlockDurationMinutes(intParam(p, spotPrefix + "BlockDurationMinutes"));
+ spotOptions.setValidUntil(p.getFirst(spotPrefix + "ValidUntil"));
+ spotOptions.setInstanceInterruptionBehavior(p.getFirst(spotPrefix + "InstanceInterruptionBehavior"));
+ options.setSpotOptions(spotOptions);
+ }
+ return options;
+ }
+
+ /**
+ * Parses {@code InstanceRequirementsRequest}. Its scalar-list members carry a singular
+ * {@code locationName}, so the wire names are {@code CpuManufacturer.N} rather than
+ * {@code CpuManufacturers.N}, and the nested performance-factor references arrive as
+ * {@code BaselinePerformanceFactors.Cpu.Reference.N.InstanceFamily}.
+ */
+ private LaunchTemplateData.InstanceRequirements parseLaunchTemplateInstanceRequirements(
+ MultivaluedMap<String, String> p, String prefix) {
+ LaunchTemplateData.InstanceRequirements requirements = new LaunchTemplateData.InstanceRequirements();
+ requirements.setVCpuCount(parseIntRange(p, prefix + "VCpuCount."));
+ requirements.setMemoryMiB(parseIntRange(p, prefix + "MemoryMiB."));
+ requirements.setCpuManufacturers(getList(p, prefix + "CpuManufacturer"));
+ requirements.setMemoryGiBPerVCpu(parseDoubleRange(p, prefix + "MemoryGiBPerVCpu."));
+ requirements.setExcludedInstanceTypes(getList(p, prefix + "ExcludedInstanceType"));
+ requirements.setInstanceGenerations(getList(p, prefix + "InstanceGeneration"));
+ requirements.setSpotMaxPricePercentageOverLowestPrice(
+ intParam(p, prefix + "SpotMaxPricePercentageOverLowestPrice"));
+ requirements.setOnDemandMaxPricePercentageOverLowestPrice(
+ intParam(p, prefix + "OnDemandMaxPricePercentageOverLowestPrice"));
+ requirements.setBareMetal(p.getFirst(prefix + "BareMetal"));
+ requirements.setBurstablePerformance(p.getFirst(prefix + "BurstablePerformance"));
+ requirements.setRequireHibernateSupport(boolParam(p, prefix + "RequireHibernateSupport"));
+ requirements.setNetworkInterfaceCount(parseIntRange(p, prefix + "NetworkInterfaceCount."));
+ requirements.setLocalStorage(p.getFirst(prefix + "LocalStorage"));
+ requirements.setLocalStorageTypes(getList(p, prefix + "LocalStorageType"));
+ requirements.setTotalLocalStorageGB(parseDoubleRange(p, prefix + "TotalLocalStorageGB."));
+ requirements.setBaselineEbsBandwidthMbps(parseIntRange(p, prefix + "BaselineEbsBandwidthMbps."));
+ requirements.setAcceleratorTypes(getList(p, prefix + "AcceleratorType"));
+ requirements.setAcceleratorCount(parseIntRange(p, prefix + "AcceleratorCount."));
+ requirements.setAcceleratorManufacturers(getList(p, prefix + "AcceleratorManufacturer"));
+ requirements.setAcceleratorNames(getList(p, prefix + "AcceleratorName"));
+ requirements.setAcceleratorTotalMemoryMiB(parseIntRange(p, prefix + "AcceleratorTotalMemoryMiB."));
+ requirements.setNetworkBandwidthGbps(parseDoubleRange(p, prefix + "NetworkBandwidthGbps."));
+ requirements.setAllowedInstanceTypes(getList(p, prefix + "AllowedInstanceType"));
+ requirements.setMaxSpotPriceAsPercentageOfOptimalOnDemandPrice(
+ intParam(p, prefix + "MaxSpotPriceAsPercentageOfOptimalOnDemandPrice"));
+ requirements.setRequireEncryptionInTransit(boolParam(p, prefix + "RequireEncryptionInTransit"));
+ String cpuPrefix = prefix + "BaselinePerformanceFactors.Cpu.";
+ if (anyParamStartsWith(p, cpuPrefix)) {
+ LaunchTemplateData.CpuPerformanceFactor cpu = new LaunchTemplateData.CpuPerformanceFactor();
+ List<LaunchTemplateData.PerformanceFactorReference> references = new ArrayList<>();
+ for (int i = 1; ; i++) {
+ String instanceFamily = p.getFirst(cpuPrefix + "Reference." + i + ".InstanceFamily");
+ if (instanceFamily == null) {
+ break;
+ }
+ references.add(new LaunchTemplateData.PerformanceFactorReference(instanceFamily));
+ }
+ cpu.setReferences(references);
+ LaunchTemplateData.BaselinePerformanceFactors factors =
+ new LaunchTemplateData.BaselinePerformanceFactors();
+ factors.setCpu(cpu);
+ requirements.setBaselinePerformanceFactors(factors);
+ }
+ return requirements;
+ }
+
+ private LaunchTemplateData.IntRange parseIntRange(MultivaluedMap<String, String> p, String prefix) {
+ Integer min = intParam(p, prefix + "Min");
+ Integer max = intParam(p, prefix + "Max");
+ if (min == null && max == null) {
+ return null;
+ }
+ return new LaunchTemplateData.IntRange(min, max);
+ }
+
+ private LaunchTemplateData.DoubleRange parseDoubleRange(MultivaluedMap<String, String> p, String prefix) {
+ Double min = doubleParam(p, prefix + "Min");
+ Double max = doubleParam(p, prefix + "Max");
+ if (min == null && max == null) {
+ return null;
+ }
+ return new LaunchTemplateData.DoubleRange(min, max);
+ }
+
private List<LaunchTemplateData.BlockDeviceMapping> parseLaunchTemplateBlockDeviceMappings(
MultivaluedMap<String, String> p, String prefix) {
List<LaunchTemplateData.BlockDeviceMapping> mappings = new ArrayList<>();
@@ -5068,6 +5273,15 @@ public class Ec2QueryHandler {
networkInterface.setSecondaryPrivateIpAddressCount(intParam(p, base + ".SecondaryPrivateIpAddressCount"));
networkInterface.setSubnetId(p.getFirst(base + ".SubnetId"));
networkInterface.setNetworkCardIndex(intParam(p, base + ".NetworkCardIndex"));
+ String trackingPrefix = base + ".ConnectionTrackingSpecification.";
+ if (anyParamStartsWith(p, trackingPrefix)) {
+ LaunchTemplateData.ConnectionTrackingSpecification tracking =
+ new LaunchTemplateData.ConnectionTrackingSpecification();
+ tracking.setTcpEstablishedTimeout(intParam(p, trackingPrefix + "TcpEstablishedTimeout"));
+ tracking.setUdpTimeout(intParam(p, trackingPrefix + "UdpTimeout"));
+ tracking.setUdpStreamTimeout(intParam(p, trackingPrefix + "UdpStreamTimeout"));
+ networkInterface.setConnectionTrackingSpecification(tracking);
+ }
networkInterface.setGroups(getList(p, base + ".SecurityGroupId", base + ".Groups", base + ".GroupId"));
interfaces.add(networkInterface);
}
@@ -5126,6 +5340,18 @@ public class Ec2QueryHandler {
}
}
+ private Double doubleParam(MultivaluedMap<String, String> p, String name) {
+ String value = p.getFirst(name);
+ if (!isSet(value)) {
+ return null;
+ }
+ try {
+ return Double.valueOf(value);
+ } catch (NumberFormatException e) {
+ throw new AwsException("InvalidParameterValue", name + " is not a valid number.", 400);
+ }
+ }
+
private static String str(Object value) {
return value != null ? String.valueOf(value) : null;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
index 57cd5147f5..1b76ecf5ed 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
@@ -5155,6 +5155,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
if (name == null || name.isBlank()) {
throw new AwsException("MissingParameter", "The request must contain the parameter LaunchTemplateName", 400);
}
+ validateLaunchTemplateData(data);
boolean exists = launchTemplates.scan(k -> true).stream()
.anyMatch(lt -> lt.getRegion().equals(region) && name.equals(lt.getLaunchTemplateName()));
if (exists) {
@@ -5182,6 +5183,89 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
return launchTemplate;
}
+ /**
+ * Request-side constraints EC2 applies to {@code RequestLaunchTemplateData} before a template
+ * or a version is stored. {@code InstanceRequirementsRequest} declares {@code VCpuCount} and
+ * {@code MemoryMiB} as required members, each of which in turn requires its {@code Min}, and
+ * the connection tracking timeouts carry the ranges documented on
+ * {@code ConnectionTrackingSpecificationRequest}. The remaining rules live only in the member
+ * documentation rather than in the model constraints: "If you specify InstanceRequirements,
+ * you can't specify InstanceType", "If you specify AllowedInstanceTypes, you can't specify
+ * ExcludedInstanceTypes", and "Only one of SpotMaxPricePercentageOverLowestPrice or
+ * MaxSpotPriceAsPercentageOfOptimalOnDemandPrice can be specified".
+ */
+ private static void validateLaunchTemplateData(LaunchTemplateData data) {
+ if (data == null) {
+ return;
+ }
+ requireInstanceTypeOrInstanceRequirements(data);
+ validateInstanceRequirements(data.getInstanceRequirements());
+ for (LaunchTemplateData.NetworkInterface networkInterface : data.getNetworkInterfaces()) {
+ validateConnectionTracking(networkInterface.getConnectionTrackingSpecification());
+ }
+ }
+
+ private static void requireInstanceTypeOrInstanceRequirements(LaunchTemplateData data) {
+ if (data.getInstanceRequirements() == null || !isSet(data.getInstanceType())) {
+ return;
+ }
+ throw new AwsException("InvalidParameterCombination",
+ "InstanceRequirements cannot be combined with InstanceType. A launch template "
+ + "selects instance types by attribute or by name, not by both.", 400);
+ }
+
+ private static void validateInstanceRequirements(LaunchTemplateData.InstanceRequirements requirements) {
+ if (requirements == null) {
+ return;
+ }
+ requireInstanceRequirementsRange("VCpuCount", requirements.getVCpuCount());
+ requireInstanceRequirementsRange("MemoryMiB", requirements.getMemoryMiB());
+ requireOnlyOneOf("AllowedInstanceTypes", !requirements.getAllowedInstanceTypes().isEmpty(),
+ "ExcludedInstanceTypes", !requirements.getExcludedInstanceTypes().isEmpty());
+ requireOnlyOneOf("SpotMaxPricePercentageOverLowestPrice",
+ requirements.getSpotMaxPricePercentageOverLowestPrice() != null,
+ "MaxSpotPriceAsPercentageOfOptimalOnDemandPrice",
+ requirements.getMaxSpotPriceAsPercentageOfOptimalOnDemandPrice() != null);
+ }
+
+ private static void requireOnlyOneOf(String parameter, boolean present, String other, boolean otherPresent) {
+ if (!present || !otherPresent) {
+ return;
+ }
+ throw new AwsException("InvalidParameterCombination",
+ "Only one of InstanceRequirements." + parameter + " or InstanceRequirements." + other
+ + " can be specified.", 400);
+ }
+
+ private static void requireInstanceRequirementsRange(String parameter, LaunchTemplateData.IntRange range) {
+ if (range == null) {
+ throw new AwsException("MissingParameter",
+ "The request must contain the parameter InstanceRequirements." + parameter, 400);
+ }
+ if (range.getMin() == null) {
+ throw new AwsException("MissingParameter",
+ "The request must contain the parameter InstanceRequirements." + parameter + ".Min", 400);
+ }
+ }
+
+ private static void validateConnectionTracking(LaunchTemplateData.ConnectionTrackingSpecification tracking) {
+ if (tracking == null) {
+ return;
+ }
+ requireTimeoutInRange("TcpEstablishedTimeout", tracking.getTcpEstablishedTimeout(), 60, 432000);
+ requireTimeoutInRange("UdpTimeout", tracking.getUdpTimeout(), 30, 60);
+ requireTimeoutInRange("UdpStreamTimeout", tracking.getUdpStreamTimeout(), 60, 180);
+ }
+
+ private static void requireTimeoutInRange(String parameter, Integer value, int min, int max) {
+ if (value == null || (value >= min && value <= max)) {
+ return;
+ }
+ throw new AwsException("InvalidParameterValue",
+ "Value (" + value + ") for parameter " + parameter + " is invalid. Valid values are between "
+ + min + " and " + max + ".", 400);
+ }
+
public LaunchTemplate createLaunchTemplateVersion(String region, String id, String name,
String sourceVersion, LaunchTemplateData data) {
return createLaunchTemplateVersion(region, id, name, sourceVersion, data, null);
@@ -5193,11 +5277,21 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
* {@link LaunchTemplateData}, populated only by whatever fields this request itself supplies.
* Only an explicit {@code SourceVersion} (including {@code $Latest} / {@code $Default}) causes
* inheritance.
+ *
+ * <p>The request is validated twice, and both passes matter. The first pass covers what the
+ * caller actually sent. The second covers the merged result, because that is the data the
+ * version stores and the data AutoScaling and the fleet APIs later read. {@link
+ * LaunchTemplateData#mergedWith} has no way to express removal, so a version that names only
+ * {@code InstanceType} against a source carrying {@code InstanceRequirements} merges into a
+ * version holding both, which EC2 does not allow. That merged version is rejected rather than
+ * stored. A caller moving a template between attribute-based and named instance type selection
+ * omits {@code SourceVersion}, which starts the new version from empty data.</p>
*/
public LaunchTemplate createLaunchTemplateVersion(String region, String id, String name,
String sourceVersion, LaunchTemplateData data,
String versionDescription) {
ensureDefaultResources(region);
+ validateLaunchTemplateData(data);
LaunchTemplate launchTemplate = findLaunchTemplate(region, id, name);
ensureLaunchTemplateVersions(launchTemplate);
int latestVersion = parseLaunchTemplateVersion(launchTemplate.getLatestVersionNumber()) + 1;
@@ -5209,6 +5303,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
resolveLaunchTemplateVersion(launchTemplate, sourceVersion, launchTemplate.getLatestVersionNumber()));
}
LaunchTemplateData merged = source.mergedWith(data != null ? data : new LaunchTemplateData());
+ validateLaunchTemplateData(merged);
launchTemplate.setLatestVersionNumber(String.valueOf(latestVersion));
launchTemplate.getVersions().put(String.valueOf(latestVersion), merged);
launchTemplate.setData(new LaunchTemplateData(merged));
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/LaunchTemplateData.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/LaunchTemplateData.java
index 478b714473..a7646bc379 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/model/LaunchTemplateData.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/LaunchTemplateData.java
@@ -45,6 +45,8 @@ public class LaunchTemplateData {
private MaintenanceOptions maintenanceOptions;
private PrivateDnsNameOptions privateDnsNameOptions;
private CapacityReservationSpecification capacityReservationSpecification;
+ private InstanceMarketOptions instanceMarketOptions;
+ private InstanceRequirements instanceRequirements;
private List<String> securityGroupIds = new ArrayList<>();
private List<BlockDeviceMapping> blockDeviceMappings = new ArrayList<>();
private List<NetworkInterface> networkInterfaces = new ArrayList<>();
@@ -75,6 +77,8 @@ public class LaunchTemplateData {
this.maintenanceOptions = source.maintenanceOptions;
this.privateDnsNameOptions = source.privateDnsNameOptions;
this.capacityReservationSpecification = source.capacityReservationSpecification;
+ this.instanceMarketOptions = source.instanceMarketOptions;
+ this.instanceRequirements = source.instanceRequirements;
this.securityGroupIds = new ArrayList<>(source.securityGroupIds);
this.blockDeviceMappings = new ArrayList<>(source.blockDeviceMappings);
this.networkInterfaces = new ArrayList<>(source.networkInterfaces);
@@ -151,6 +155,12 @@ public class LaunchTemplateData {
if (override.capacityReservationSpecification != null) {
merged.capacityReservationSpecification = override.capacityReservationSpecification;
}
+ if (override.instanceMarketOptions != null) {
+ merged.instanceMarketOptions = override.instanceMarketOptions;
+ }
+ if (override.instanceRequirements != null) {
+ merged.instanceRequirements = override.instanceRequirements;
+ }
if (!override.securityGroupIds.isEmpty()) {
merged.securityGroupIds = new ArrayList<>(override.securityGroupIds);
}
@@ -244,6 +254,16 @@ public class LaunchTemplateData {
this.capacityReservationSpecification = capacityReservationSpecification;
}
+ public InstanceMarketOptions getInstanceMarketOptions() { return instanceMarketOptions; }
+ public void setInstanceMarketOptions(InstanceMarketOptions instanceMarketOptions) {
+ this.instanceMarketOptions = instanceMarketOptions;
+ }
+
+ public InstanceRequirements getInstanceRequirements() { return instanceRequirements; }
+ public void setInstanceRequirements(InstanceRequirements instanceRequirements) {
+ this.instanceRequirements = instanceRequirements;
+ }
+
public List<String> getSecurityGroupIds() { return securityGroupIds; }
public void setSecurityGroupIds(List<String> securityGroupIds) {
this.securityGroupIds = securityGroupIds != null ? new ArrayList<>(securityGroupIds) : new ArrayList<>();
@@ -497,6 +517,7 @@ public class LaunchTemplateData {
private Integer secondaryPrivateIpAddressCount;
private String subnetId;
private Integer networkCardIndex;
+ private ConnectionTrackingSpecification connectionTrackingSpecification;
private List<String> groups = new ArrayList<>();
public Boolean getAssociatePublicIpAddress() { return associatePublicIpAddress; }
@@ -541,12 +562,43 @@ public class LaunchTemplateData {
public Integer getNetworkCardIndex() { return networkCardIndex; }
public void setNetworkCardIndex(Integer networkCardIndex) { this.networkCardIndex = networkCardIndex; }
+ public ConnectionTrackingSpecification getConnectionTrackingSpecification() {
+ return connectionTrackingSpecification;
+ }
+ public void setConnectionTrackingSpecification(ConnectionTrackingSpecification spec) {
+ this.connectionTrackingSpecification = spec;
+ }
+
public List<String> getGroups() { return groups; }
public void setGroups(List<String> groups) {
this.groups = groups != null ? new ArrayList<>(groups) : new ArrayList<>();
}
}
+ /**
+ * The idle-timeout overrides EC2 applies to an interface's connection tracking. Sent as
+ * {@code ConnectionTrackingSpecificationRequest} and read back as
+ * {@code ConnectionTrackingSpecification}; both carry the same three members.
+ */
+ @RegisterForReflection
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ public static class ConnectionTrackingSpecification {
+ private Integer tcpEstablishedTimeout;
+ private Integer udpTimeout;
+ private Integer udpStreamTimeout;
+
+ public Integer getTcpEstablishedTimeout() { return tcpEstablishedTimeout; }
+ public void setTcpEstablishedTimeout(Integer tcpEstablishedTimeout) {
+ this.tcpEstablishedTimeout = tcpEstablishedTimeout;
+ }
+
+ public Integer getUdpTimeout() { return udpTimeout; }
+ public void setUdpTimeout(Integer udpTimeout) { this.udpTimeout = udpTimeout; }
+
+ public Integer getUdpStreamTimeout() { return udpStreamTimeout; }
+ public void setUdpStreamTimeout(Integer udpStreamTimeout) { this.udpStreamTimeout = udpStreamTimeout; }
+ }
+
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public static class TagSpecification {
@@ -730,4 +782,254 @@ public class LaunchTemplateData {
this.capacityReservationResourceGroupArn = capacityReservationResourceGroupArn;
}
}
+
+ /**
+ * Attribute-based instance type selection. Every member of the service model's
+ * {@code InstanceRequirementsRequest} is carried, including the nested
+ * {@code BaselinePerformanceFactors}.
+ */
+ @RegisterForReflection
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ public static class InstanceRequirements {
+ private IntRange vCpuCount;
+ private IntRange memoryMiB;
+ private List<String> cpuManufacturers = new ArrayList<>();
+ private DoubleRange memoryGiBPerVCpu;
+ private List<String> excludedInstanceTypes = new ArrayList<>();
+ private List<String> instanceGenerations = new ArrayList<>();
+ private Integer spotMaxPricePercentageOverLowestPrice;
+ private Integer onDemandMaxPricePercentageOverLowestPrice;
+ private String bareMetal;
+ private String burstablePerformance;
+ private Boolean requireHibernateSupport;
+ private IntRange networkInterfaceCount;
+ private String localStorage;
+ private List<String> localStorageTypes = new ArrayList<>();
+ private DoubleRange totalLocalStorageGB;
+ private IntRange baselineEbsBandwidthMbps;
+ private List<String> acceleratorTypes = new ArrayList<>();
+ private IntRange acceleratorCount;
+ private List<String> acceleratorManufacturers = new ArrayList<>();
+ private List<String> acceleratorNames = new ArrayList<>();
+ private IntRange acceleratorTotalMemoryMiB;
+ private DoubleRange networkBandwidthGbps;
+ private List<String> allowedInstanceTypes = new ArrayList<>();
+ private Integer maxSpotPriceAsPercentageOfOptimalOnDemandPrice;
+ private BaselinePerformanceFactors baselinePerformanceFactors;
+ private Boolean requireEncryptionInTransit;
+
+ public IntRange getVCpuCount() { return vCpuCount; }
+ public void setVCpuCount(IntRange vCpuCount) { this.vCpuCount = vCpuCount; }
+
+ public IntRange getMemoryMiB() { return memoryMiB; }
+ public void setMemoryMiB(IntRange memoryMiB) { this.memoryMiB = memoryMiB; }
+
+ public List<String> getCpuManufacturers() { return cpuManufacturers; }
+ public void setCpuManufacturers(List<String> cpuManufacturers) {
+ this.cpuManufacturers = cpuManufacturers != null ? new ArrayList<>(cpuManufacturers) : new ArrayList<>();
+ }
+
+ public DoubleRange getMemoryGiBPerVCpu() { return memoryGiBPerVCpu; }
+ public void setMemoryGiBPerVCpu(DoubleRange memoryGiBPerVCpu) { this.memoryGiBPerVCpu = memoryGiBPerVCpu; }
+
+ public List<String> getExcludedInstanceTypes() { return excludedInstanceTypes; }
+ public void setExcludedInstanceTypes(List<String> excludedInstanceTypes) {
+ this.excludedInstanceTypes = excludedInstanceTypes != null ? new ArrayList<>(excludedInstanceTypes) : new ArrayList<>();
+ }
+
+ public List<String> getInstanceGenerations() { return instanceGenerations; }
+ public void setInstanceGenerations(List<String> instanceGenerations) {
+ this.instanceGenerations = instanceGenerations != null ? new ArrayList<>(instanceGenerations) : new ArrayList<>();
+ }
+
+ public Integer getSpotMaxPricePercentageOverLowestPrice() { return spotMaxPricePercentageOverLowestPrice; }
+ public void setSpotMaxPricePercentageOverLowestPrice(Integer spotMaxPricePercentageOverLowestPrice) { this.spotMaxPricePercentageOverLowestPrice = spotMaxPricePercentageOverLowestPrice; }
+
+ public Integer getOnDemandMaxPricePercentageOverLowestPrice() { return onDemandMaxPricePercentageOverLowestPrice; }
+ public void setOnDemandMaxPricePercentageOverLowestPrice(Integer onDemandMaxPricePercentageOverLowestPrice) { this.onDemandMaxPricePercentageOverLowestPrice = onDemandMaxPricePercentageOverLowestPrice; }
+
+ public String getBareMetal() { return bareMetal; }
+ public void setBareMetal(String bareMetal) { this.bareMetal = bareMetal; }
+
+ public String getBurstablePerformance() { return burstablePerformance; }
+ public void setBurstablePerformance(String burstablePerformance) { this.burstablePerformance = burstablePerformance; }
+
+ public Boolean getRequireHibernateSupport() { return requireHibernateSupport; }
+ public void setRequireHibernateSupport(Boolean requireHibernateSupport) { this.requireHibernateSupport = requireHibernateSupport; }
+
+ public IntRange getNetworkInterfaceCount() { return networkInterfaceCount; }
+ public void setNetworkInterfaceCount(IntRange networkInterfaceCount) { this.networkInterfaceCount = networkInterfaceCount; }
+
+ public String getLocalStorage() { return localStorage; }
+ public void setLocalStorage(String localStorage) { this.localStorage = localStorage; }
+
+ public List<String> getLocalStorageTypes() { return localStorageTypes; }
+ public void setLocalStorageTypes(List<String> localStorageTypes) {
+ this.localStorageTypes = localStorageTypes != null ? new ArrayList<>(localStorageTypes) : new ArrayList<>();
+ }
+
+ public DoubleRange getTotalLocalStorageGB() { return totalLocalStorageGB; }
+ public void setTotalLocalStorageGB(DoubleRange totalLocalStorageGB) { this.totalLocalStorageGB = totalLocalStorageGB; }
+
+ public IntRange getBaselineEbsBandwidthMbps() { return baselineEbsBandwidthMbps; }
+ public void setBaselineEbsBandwidthMbps(IntRange baselineEbsBandwidthMbps) { this.baselineEbsBandwidthMbps = baselineEbsBandwidthMbps; }
+
+ public List<String> getAcceleratorTypes() { return acceleratorTypes; }
+ public void setAcceleratorTypes(List<String> acceleratorTypes) {
+ this.acceleratorTypes = acceleratorTypes != null ? new ArrayList<>(acceleratorTypes) : new ArrayList<>();
+ }
+
+ public IntRange getAcceleratorCount() { return acceleratorCount; }
+ public void setAcceleratorCount(IntRange acceleratorCount) { this.acceleratorCount = acceleratorCount; }
+
+ public List<String> getAcceleratorManufacturers() { return acceleratorManufacturers; }
+ public void setAcceleratorManufacturers(List<String> acceleratorManufacturers) {
+ this.acceleratorManufacturers = acceleratorManufacturers != null ? new ArrayList<>(acceleratorManufacturers) : new ArrayList<>();
+ }
+
+ public List<String> getAcceleratorNames() { return acceleratorNames; }
+ public void setAcceleratorNames(List<String> acceleratorNames) {
+ this.acceleratorNames = acceleratorNames != null ? new ArrayList<>(acceleratorNames) : new ArrayList<>();
+ }
+
+ public IntRange getAcceleratorTotalMemoryMiB() { return acceleratorTotalMemoryMiB; }
+ public void setAcceleratorTotalMemoryMiB(IntRange acceleratorTotalMemoryMiB) { this.acceleratorTotalMemoryMiB = acceleratorTotalMemoryMiB; }
+
+ public DoubleRange getNetworkBandwidthGbps() { return networkBandwidthGbps; }
+ public void setNetworkBandwidthGbps(DoubleRange networkBandwidthGbps) { this.networkBandwidthGbps = networkBandwidthGbps; }
+
+ public List<String> getAllowedInstanceTypes() { return allowedInstanceTypes; }
+ public void setAllowedInstanceTypes(List<String> allowedInstanceTypes) {
+ this.allowedInstanceTypes = allowedInstanceTypes != null ? new ArrayList<>(allowedInstanceTypes) : new ArrayList<>();
+ }
+
+ public Integer getMaxSpotPriceAsPercentageOfOptimalOnDemandPrice() { return maxSpotPriceAsPercentageOfOptimalOnDemandPrice; }
+ public void setMaxSpotPriceAsPercentageOfOptimalOnDemandPrice(Integer maxSpotPriceAsPercentageOfOptimalOnDemandPrice) { this.maxSpotPriceAsPercentageOfOptimalOnDemandPrice = maxSpotPriceAsPercentageOfOptimalOnDemandPrice; }
+
+ public BaselinePerformanceFactors getBaselinePerformanceFactors() { return baselinePerformanceFactors; }
+ public void setBaselinePerformanceFactors(BaselinePerformanceFactors baselinePerformanceFactors) { this.baselinePerformanceFactors = baselinePerformanceFactors; }
+
+ public Boolean getRequireEncryptionInTransit() { return requireEncryptionInTransit; }
+ public void setRequireEncryptionInTransit(Boolean requireEncryptionInTransit) { this.requireEncryptionInTransit = requireEncryptionInTransit; }
+ }
+
+ /** {@code VCpuCountRangeRequest} and the other whole-number Min/Max ranges. */
+ @RegisterForReflection
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ public static class IntRange {
+ private Integer min;
+ private Integer max;
+
+ public IntRange() {}
+
+ public IntRange(Integer min, Integer max) {
+ this.min = min;
+ this.max = max;
+ }
+
+ public Integer getMin() { return min; }
+ public void setMin(Integer min) { this.min = min; }
+
+ public Integer getMax() { return max; }
+ public void setMax(Integer max) { this.max = max; }
+ }
+
+ /** {@code MemoryGiBPerVCpuRequest} and the other fractional Min/Max ranges. */
+ @RegisterForReflection
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ public static class DoubleRange {
+ private Double min;
+ private Double max;
+
+ public DoubleRange() {}
+
+ public DoubleRange(Double min, Double max) {
+ this.min = min;
+ this.max = max;
+ }
+
+ public Double getMin() { return min; }
+ public void setMin(Double min) { this.min = min; }
+
+ public Double getMax() { return max; }
+ public void setMax(Double max) { this.max = max; }
+ }
+
+ @RegisterForReflection
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ public static class BaselinePerformanceFactors {
+ private CpuPerformanceFactor cpu;
+
+ public CpuPerformanceFactor getCpu() { return cpu; }
+ public void setCpu(CpuPerformanceFactor cpu) { this.cpu = cpu; }
+ }
+
+ @RegisterForReflection
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ public static class CpuPerformanceFactor {
+ private List<PerformanceFactorReference> references = new ArrayList<>();
+
+ public List<PerformanceFactorReference> getReferences() { return references; }
+ public void setReferences(List<PerformanceFactorReference> references) {
+ this.references = references != null ? new ArrayList<>(references) : new ArrayList<>();
+ }
+ }
+
+ @RegisterForReflection
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ public static class PerformanceFactorReference {
+ private String instanceFamily;
+
+ public PerformanceFactorReference() {}
+
+ public PerformanceFactorReference(String instanceFamily) {
+ this.instanceFamily = instanceFamily;
+ }
+
+ public String getInstanceFamily() { return instanceFamily; }
+ public void setInstanceFamily(String instanceFamily) { this.instanceFamily = instanceFamily; }
+ }
+
+ /** The spot request block. Sent as {@code LaunchTemplateInstanceMarketOptionsRequest}. */
+ @RegisterForReflection
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ public static class InstanceMarketOptions {
+ private String marketType;
+ private SpotOptions spotOptions;
+
+ public String getMarketType() { return marketType; }
+ public void setMarketType(String marketType) { this.marketType = marketType; }
+
+ public SpotOptions getSpotOptions() { return spotOptions; }
+ public void setSpotOptions(SpotOptions spotOptions) { this.spotOptions = spotOptions; }
+ }
+
+ @RegisterForReflection
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ public static class SpotOptions {
+ private String maxPrice;
+ private String spotInstanceType;
+ private Integer blockDurationMinutes;
+ private String validUntil;
+ private String instanceInterruptionBehavior;
+
+ public String getMaxPrice() { return maxPrice; }
+ public void setMaxPrice(String maxPrice) { this.maxPrice = maxPrice; }
+
+ public String getSpotInstanceType() { return spotInstanceType; }
+ public void setSpotInstanceType(String spotInstanceType) { this.spotInstanceType = spotInstanceType; }
+
+ public Integer getBlockDurationMinutes() { return blockDurationMinutes; }
+ public void setBlockDurationMinutes(Integer blockDurationMinutes) {
+ this.blockDurationMinutes = blockDurationMinutes;
+ }
+
+ public String getValidUntil() { return validUntil; }
+ public void setValidUntil(String validUntil) { this.validUntil = validUntil; }
+
+ public String getInstanceInterruptionBehavior() { return instanceInterruptionBehavior; }
+ public void setInstanceInterruptionBehavior(String instanceInterruptionBehavior) {
+ this.instanceInterruptionBehavior = instanceInterruptionBehavior;
+ }
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2LaunchTemplateFieldsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2LaunchTemplateFieldsIntegrationTest.java
index 7b81386efb..b60e476634 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2LaunchTemplateFieldsIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2LaunchTemplateFieldsIntegrationTest.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ec2;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
+import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.util.UUID;
@@ -351,4 +352,555 @@ class Ec2LaunchTemplateFieldsIntegrationTest {
assertFalse(describeBody(name).contains("my-app-sg"),
"SecurityGroups (by name) is accepted and ignored, not stored");
}
+
+ @Test
+ void instanceMarketOptionsRoundTrips() {
+ // aws_launch_template's instance_market_options block. Dropping it made every spot
+ // launch template diff forever, because Terraform read back no market options at all.
+ String name = uniqueName("spot-lt");
+ given()
+ .formParam("Action", "CreateLaunchTemplate")
+ .formParam("LaunchTemplateName", name)
+ .formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
+ .formParam("LaunchTemplateData.InstanceMarketOptions.MarketType", "spot")
+ .formParam("LaunchTemplateData.InstanceMarketOptions.SpotOptions.MaxPrice", "0.05")
+ .formParam("LaunchTemplateData.InstanceMarketOptions.SpotOptions.SpotInstanceType", "one-time")
+ .formParam("LaunchTemplateData.InstanceMarketOptions.SpotOptions.BlockDurationMinutes", "60")
+ .formParam("LaunchTemplateData.InstanceMarketOptions.SpotOptions.ValidUntil", "2030-01-01T00:00:00Z")
+ .formParam("LaunchTemplateData.InstanceMarketOptions.SpotOptions.InstanceInterruptionBehavior",
+ "terminate")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ describeLatest(name)
+ .body(DATA + "instanceMarketOptions.marketType", equalTo("spot"))
+ .body(DATA + "instanceMarketOptions.spotOptions.maxPrice", equalTo("0.05"))
+ .body(DATA + "instanceMarketOptions.spotOptions.spotInstanceType", equalTo("one-time"))
+ .body(DATA + "instanceMarketOptions.spotOptions.blockDurationMinutes", equalTo("60"))
+ .body(DATA + "instanceMarketOptions.spotOptions.validUntil", equalTo("2030-01-01T00:00:00Z"))
+ .body(DATA + "instanceMarketOptions.spotOptions.instanceInterruptionBehavior", equalTo("terminate"));
+ }
+
+ @Test
+ void marketOptionsWithoutSpotOptionsOmitsTheSpotBlock() {
+ String name = uniqueName("market-only-lt");
+ given()
+ .formParam("Action", "CreateLaunchTemplate")
+ .formParam("LaunchTemplateName", name)
+ .formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
+ .formParam("LaunchTemplateData.InstanceMarketOptions.MarketType", "spot")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ describeLatest(name)
+ .body(DATA + "instanceMarketOptions.marketType", equalTo("spot"));
+ assertFalse(describeBody(name).contains("<spotOptions>"),
+ "an unset SpotOptions must stay absent rather than read back empty");
+ }
+
+ @Test
+ void instanceRequirementsRoundTrips() {
+ // Attribute-based instance type selection. The scalar lists carry the model's singular
+ // locationName on the wire, so CpuManufacturer.N feeds cpuManufacturerSet on the way out.
+ String name = uniqueName("requirements-lt");
+ String req = "LaunchTemplateData.InstanceRequirements.";
+ given()
+ .formParam("Action", "CreateLaunchTemplate")
+ .formParam("LaunchTemplateName", name)
+ .formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
+ .formParam(req + "VCpuCount.Min", "2")
+ .formParam(req + "VCpuCount.Max", "8")
+ .formParam(req + "MemoryMiB.Min", "1024")
+ .formParam(req + "MemoryGiBPerVCpu.Min", "0.5")
+ .formParam(req + "MemoryGiBPerVCpu.Max", "4.0")
+ .formParam(req + "CpuManufacturer.1", "intel")
+ .formParam(req + "CpuManufacturer.2", "amd")
+ .formParam(req + "ExcludedInstanceType.1", "t2.*")
+ .formParam(req + "InstanceGeneration.1", "current")
+ .formParam(req + "BareMetal", "excluded")
+ .formParam(req + "BurstablePerformance", "included")
+ .formParam(req + "RequireHibernateSupport", "false")
+ .formParam(req + "LocalStorage", "required")
+ .formParam(req + "LocalStorageType.1", "ssd")
+ .formParam(req + "TotalLocalStorageGB.Max", "100.0")
+ .formParam(req + "NetworkInterfaceCount.Min", "1")
+ .formParam(req + "BaselineEbsBandwidthMbps.Min", "100")
+ .formParam(req + "AcceleratorType.1", "gpu")
+ .formParam(req + "AcceleratorCount.Min", "1")
+ .formParam(req + "AcceleratorManufacturer.1", "nvidia")
+ .formParam(req + "AcceleratorName.1", "t4")
+ .formParam(req + "AcceleratorTotalMemoryMiB.Min", "16")
+ .formParam(req + "NetworkBandwidthGbps.Min", "1.5")
+ .formParam(req + "SpotMaxPricePercentageOverLowestPrice", "20")
+ .formParam(req + "OnDemandMaxPricePercentageOverLowestPrice", "30")
+ .formParam(req + "RequireEncryptionInTransit", "true")
+ .formParam(req + "BaselinePerformanceFactors.Cpu.Reference.1.InstanceFamily", "m6i")
+ .formParam(req + "BaselinePerformanceFactors.Cpu.Reference.2.InstanceFamily", "c6i")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ String set = DATA + "instanceRequirements.";
+ describeLatest(name)
+ .body(set + "vCpuCount.min", equalTo("2"))
+ .body(set + "vCpuCount.max", equalTo("8"))
+ .body(set + "memoryMiB.min", equalTo("1024"))
+ .body(set + "memoryGiBPerVCpu.min", equalTo("0.5"))
+ .body(set + "memoryGiBPerVCpu.max", equalTo("4.0"))
+ .body(set + "cpuManufacturerSet.item", contains("intel", "amd"))
+ .body(set + "excludedInstanceTypeSet.item", equalTo("t2.*"))
+ .body(set + "instanceGenerationSet.item", equalTo("current"))
+ .body(set + "bareMetal", equalTo("excluded"))
+ .body(set + "burstablePerformance", equalTo("included"))
+ .body(set + "requireHibernateSupport", equalTo("false"))
+ .body(set + "localStorage", equalTo("required"))
+ .body(set + "localStorageTypeSet.item", equalTo("ssd"))
+ .body(set + "totalLocalStorageGB.max", equalTo("100.0"))
+ .body(set + "networkInterfaceCount.min", equalTo("1"))
+ .body(set + "baselineEbsBandwidthMbps.min", equalTo("100"))
+ .body(set + "acceleratorTypeSet.item", equalTo("gpu"))
+ .body(set + "acceleratorCount.min", equalTo("1"))
+ .body(set + "acceleratorManufacturerSet.item", equalTo("nvidia"))
+ .body(set + "acceleratorNameSet.item", equalTo("t4"))
+ .body(set + "acceleratorTotalMemoryMiB.min", equalTo("16"))
+ .body(set + "networkBandwidthGbps.min", equalTo("1.5"))
+ .body(set + "spotMaxPricePercentageOverLowestPrice", equalTo("20"))
+ .body(set + "onDemandMaxPricePercentageOverLowestPrice", equalTo("30"))
+ .body(set + "requireEncryptionInTransit", equalTo("true"))
+ .body(set + "baselinePerformanceFactors.cpu.referenceSet.item.instanceFamily",
+ contains("m6i", "c6i"));
+ // A range the request never set must not read back as an empty element.
+ assertFalse(describeBody(name).contains("<totalLocalStorageGB><min>"),
+ "an unset range bound must stay absent");
+ }
+
+ @Test
+ void theOtherHalfOfEachExclusiveRequirementsPairRoundTripsOnItsOwn() {
+ // AllowedInstanceTypes excludes ExcludedInstanceTypes, and
+ // MaxSpotPriceAsPercentageOfOptimalOnDemandPrice excludes
+ // SpotMaxPricePercentageOverLowestPrice, so the members the round trip above cannot carry
+ // are read back from a template of their own.
+ String name = uniqueName("allowed-requirements-lt");
+ String req = "LaunchTemplateData.InstanceRequirements.";
+ given()
+ .formParam("Action", "CreateLaunchTemplate")
+ .formParam("LaunchTemplateName", name)
+ .formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
+ .formParam(req + "VCpuCount.Min", "2")
+ .formParam(req + "MemoryMiB.Min", "1024")
+ .formParam(req + "AllowedInstanceType.1", "m5.*")
+ .formParam(req + "MaxSpotPriceAsPercentageOfOptimalOnDemandPrice", "40")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ String set = DATA + "instanceRequirements.";
+ describeLatest(name)
+ .body(set + "allowedInstanceTypeSet.item", equalTo("m5.*"))
+ .body(set + "maxSpotPriceAsPercentageOfOptimalOnDemandPrice", equalTo("40"));
+ }
+
+ @Test
+ void connectionTrackingSpecificationRoundTripsInsideANetworkInterface() {
+ String name = uniqueName("tracking-lt");
+ String tracking = "LaunchTemplateData.NetworkInterface.1.ConnectionTrackingSpecification.";
+ given()
+ .formParam("Action", "CreateLaunchTemplate")
+ .formParam("LaunchTemplateName", name)
+ .formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
+ .formParam("LaunchTemplateData.NetworkInterface.1.DeviceIndex", "0")
+ .formParam("LaunchTemplateData.NetworkInterface.1.SubnetId", "subnet-0123456789abcdef0")
+ .formParam(tracking + "TcpEstablishedTimeout", "60")
+ .formParam(tracking + "UdpStreamTimeout", "120")
+ .formParam(tracking + "UdpTimeout", "30")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ String item = DATA + "networkInterfaceSet.item.";
+ describeLatest(name)
+ .body(item + "deviceIndex", equalTo("0"))
+ .body(item + "connectionTrackingSpecification.tcpEstablishedTimeout", equalTo("60"))
+ .body(item + "connectionTrackingSpecification.udpStreamTimeout", equalTo("120"))
+ .body(item + "connectionTrackingSpecification.udpTimeout", equalTo("30"));
+ }
+
+ @Test
+ void aTemplateSettingNoneOfTheseBlocksReadsBackWithoutThem() {
+ String name = uniqueName("bare-lt");
+ given()
+ .formParam("Action", "CreateLaunchTemplate")
+ .formParam("LaunchTemplateName", name)
+ .formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
+ .formParam("LaunchTemplateData.InstanceType", "t3.micro")
+ .formParam("LaunchTemplateData.NetworkInterface.1.DeviceIndex", "0")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ String body = describeBody(name);
+ assertFalse(body.contains("instanceMarketOptions"),
+ "an unset InstanceMarketOptions must stay absent");
+ assertFalse(body.contains("instanceRequirements"),
+ "an unset InstanceRequirements must stay absent");
+ assertFalse(body.contains("connectionTrackingSpecification"),
+ "an unset ConnectionTrackingSpecification must stay absent");
+ }
+
+ @Test
+ void aNewVersionInheritsMarketOptionsAndRequirementsItDoesNotRestate() {
+ String name = uniqueName("inherit-lt");
+ String tracking = "LaunchTemplateData.NetworkInterface.1.ConnectionTrackingSpecification.";
+ given()
+ .formParam("Action", "CreateLaunchTemplate")
+ .formParam("LaunchTemplateName", name)
+ .formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
+ .formParam("LaunchTemplateData.InstanceMarketOptions.MarketType", "spot")
+ .formParam("LaunchTemplateData.InstanceMarketOptions.SpotOptions.MaxPrice", "0.05")
+ .formParam("LaunchTemplateData.InstanceRequirements.VCpuCount.Min", "2")
+ .formParam("LaunchTemplateData.InstanceRequirements.MemoryMiB.Min", "1024")
+ .formParam("LaunchTemplateData.NetworkInterface.1.DeviceIndex", "0")
+ .formParam(tracking + "TcpEstablishedTimeout", "60")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ // The source selects instance types by attribute, so the new version restates a member
+ // that does not collide with InstanceRequirements.
+ given()
+ .formParam("Action", "CreateLaunchTemplateVersion")
+ .formParam("LaunchTemplateName", name)
+ .formParam("SourceVersion", "1")
+ .formParam("LaunchTemplateData.KeyName", "app-key")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ describeLatest(name)
+ .body(DATA + "keyName", equalTo("app-key"))
+ .body(DATA + "instanceMarketOptions.marketType", equalTo("spot"))
+ .body(DATA + "instanceMarketOptions.spotOptions.maxPrice", equalTo("0.05"))
+ .body(DATA + "instanceRequirements.vCpuCount.min", equalTo("2"))
+ .body(DATA + "instanceRequirements.memoryMiB.min", equalTo("1024"))
+ .body(DATA + "networkInterfaceSet.item.connectionTrackingSpecification.tcpEstablishedTimeout",
+ equalTo("60"));
+ }
+
+ private ValidatableResponse createWithRequirements(String name, String... requirementParams) {
+ RequestSpecification request = given()
+ .formParam("Action", "CreateLaunchTemplate")
+ .formParam("LaunchTemplateName", name)
+ .formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
+ .header("Authorization", AUTH_HEADER);
+ for (int i = 0; i < requirementParams.length; i += 2) {
+ request = request.formParam(
+ "LaunchTemplateData.InstanceRequirements." + requirementParams[i], requirementParams[i + 1]);
+ }
+ return request.when().post("/").then();
+ }
+
+ private ValidatableResponse createWithConnectionTracking(String name, String parameter, String value) {
+ return given()
+ .formParam("Action", "CreateLaunchTemplate")
+ .formParam("LaunchTemplateName", name)
+ .formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
+ .formParam("LaunchTemplateData.NetworkInterface.1.DeviceIndex", "0")
+ .formParam("LaunchTemplateData.NetworkInterface.1.ConnectionTrackingSpecification." + parameter, value)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then();
+ }
+
+ private void assertInvalidParameterValue(ValidatableResponse response) {
+ response.statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));
+ }
+
+ @Test
+ void instanceRequirementsWithoutVCpuCountIsRejected() {
+ // InstanceRequirementsRequest declares required: ["VCpuCount", "MemoryMiB"], so a block
+ // carrying only an optional member is not a launch template AWS would store.
+ String name = uniqueName("no-vcpu-lt");
+ createWithRequirements(name, "BurstablePerformance", "included")
+ .statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("MissingParameter"));
+
+ given()
+ .formParam("Action", "DescribeLaunchTemplates")
+ .formParam("LaunchTemplateName.1", name)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("InvalidLaunchTemplateName.NotFoundException"));
+ }
+
+ @Test
+ void instanceRequirementsWithoutMemoryMiBIsRejected() {
+ createWithRequirements(uniqueName("no-memory-lt"), "VCpuCount.Min", "2")
+ .statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("MissingParameter"));
+ }
+
+ @Test
+ void aRequiredRangeWithoutItsMinIsRejected() {
+ // VCpuCountRangeRequest and MemoryMiBRequest each declare required: ["Min"].
+ createWithRequirements(uniqueName("max-only-lt"), "VCpuCount.Max", "8", "MemoryMiB.Min", "1024")
+ .statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("MissingParameter"));
+ createWithRequirements(uniqueName("memory-max-only-lt"), "VCpuCount.Min", "2", "MemoryMiB.Max", "4096")
+ .statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("MissingParameter"));
+ }
+
+ @Test
+ void bothRequiredMembersTogetherAreAccepted() {
+ createWithRequirements(uniqueName("required-pair-lt"), "VCpuCount.Min", "2", "MemoryMiB.Min", "1024")
+ .statusCode(200);
+ }
+
+ @Test
+ void tcpEstablishedTimeoutKeepsItsDocumentedRange() {
+ // "Min: 60 seconds. Max: 432000 seconds (5 days)."
+ createWithConnectionTracking(uniqueName("tcp-min-lt"), "TcpEstablishedTimeout", "60").statusCode(200);
+ createWithConnectionTracking(uniqueName("tcp-max-lt"), "TcpEstablishedTimeout", "432000").statusCode(200);
+ assertInvalidParameterValue(
+ createWithConnectionTracking(uniqueName("tcp-under-lt"), "TcpEstablishedTimeout", "59"));
+ assertInvalidParameterValue(
+ createWithConnectionTracking(uniqueName("tcp-over-lt"), "TcpEstablishedTimeout", "432001"));
+ }
+
+ @Test
+ void udpTimeoutKeepsItsDocumentedRange() {
+ // "Min: 30 seconds. Max: 60 seconds."
+ createWithConnectionTracking(uniqueName("udp-min-lt"), "UdpTimeout", "30").statusCode(200);
+ createWithConnectionTracking(uniqueName("udp-max-lt"), "UdpTimeout", "60").statusCode(200);
+ assertInvalidParameterValue(createWithConnectionTracking(uniqueName("udp-under-lt"), "UdpTimeout", "29"));
+ assertInvalidParameterValue(createWithConnectionTracking(uniqueName("udp-over-lt"), "UdpTimeout", "61"));
+ }
+
+ @Test
+ void udpStreamTimeoutKeepsItsDocumentedRange() {
+ // "Min: 60 seconds. Max: 180 seconds (3 minutes)."
+ createWithConnectionTracking(uniqueName("stream-min-lt"), "UdpStreamTimeout", "60").statusCode(200);
+ createWithConnectionTracking(uniqueName("stream-max-lt"), "UdpStreamTimeout", "180").statusCode(200);
+ assertInvalidParameterValue(
+ createWithConnectionTracking(uniqueName("stream-under-lt"), "UdpStreamTimeout", "59"));
+ assertInvalidParameterValue(
+ createWithConnectionTracking(uniqueName("stream-over-lt"), "UdpStreamTimeout", "181"));
+ }
+
+ @Test
+ void createLaunchTemplateVersionValidatesTheSameWayAndStoresNothingWhenItFails() {
+ String name = uniqueName("version-validation-lt");
+ given()
+ .formParam("Action", "CreateLaunchTemplate")
+ .formParam("LaunchTemplateName", name)
+ .formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
+ .formParam("LaunchTemplateData.InstanceType", "t3.micro")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .formParam("Action", "CreateLaunchTemplateVersion")
+ .formParam("LaunchTemplateName", name)
+ .formParam("SourceVersion", "1")
+ .formParam("LaunchTemplateData.InstanceRequirements.BurstablePerformance", "included")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("MissingParameter"));
+
+ given()
+ .formParam("Action", "CreateLaunchTemplateVersion")
+ .formParam("LaunchTemplateName", name)
+ .formParam("SourceVersion", "1")
+ .formParam("LaunchTemplateData.NetworkInterface.1.DeviceIndex", "0")
+ .formParam("LaunchTemplateData.NetworkInterface.1.ConnectionTrackingSpecification.UdpTimeout", "999")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));
+
+ given()
+ .formParam("Action", "DescribeLaunchTemplates")
+ .formParam("LaunchTemplateName.1", name)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeLaunchTemplatesResponse.launchTemplates.item.latestVersionNumber", equalTo("1"));
+ }
+
+ private ValidatableResponse createTemplate(String name, String... dataParams) {
+ RequestSpecification request = given()
+ .formParam("Action", "CreateLaunchTemplate")
+ .formParam("LaunchTemplateName", name)
+ .formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
+ .header("Authorization", AUTH_HEADER);
+ for (int i = 0; i < dataParams.length; i += 2) {
+ request = request.formParam("LaunchTemplateData." + dataParams[i], dataParams[i + 1]);
+ }
+ return request.when().post("/").then();
+ }
+
+ private ValidatableResponse createVersion(String name, String sourceVersion, String... dataParams) {
+ RequestSpecification request = given()
+ .formParam("Action", "CreateLaunchTemplateVersion")
+ .formParam("LaunchTemplateName", name)
+ .header("Authorization", AUTH_HEADER);
+ if (sourceVersion != null) {
+ request = request.formParam("SourceVersion", sourceVersion);
+ }
+ for (int i = 0; i < dataParams.length; i += 2) {
+ request = request.formParam("LaunchTemplateData." + dataParams[i], dataParams[i + 1]);
+ }
+ return request.when().post("/").then();
+ }
+
+ private void assertInvalidParameterCombination(ValidatableResponse response) {
+ response.statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("InvalidParameterCombination"));
+ }
+
+ private void assertLatestVersionIs(String name, String expected) {
+ given()
+ .formParam("Action", "DescribeLaunchTemplates")
+ .formParam("LaunchTemplateName.1", name)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeLaunchTemplatesResponse.launchTemplates.item.latestVersionNumber", equalTo(expected));
+ }
+
+ @Test
+ void instanceRequirementsAlongsideInstanceTypeIsRejected() {
+ // "If you specify InstanceRequirements, you can't specify InstanceType."
+ String name = uniqueName("type-and-requirements-lt");
+ assertInvalidParameterCombination(createTemplate(name,
+ "InstanceType", "t3.micro",
+ "InstanceRequirements.VCpuCount.Min", "2",
+ "InstanceRequirements.MemoryMiB.Min", "1024"));
+
+ given()
+ .formParam("Action", "DescribeLaunchTemplates")
+ .formParam("LaunchTemplateName.1", name)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("InvalidLaunchTemplateName.NotFoundException"));
+ }
+
+ @Test
+ void eitherOfInstanceTypeAndInstanceRequirementsOnItsOwnIsAccepted() {
+ createTemplate(uniqueName("type-only-lt"), "InstanceType", "t3.micro").statusCode(200);
+ createTemplate(uniqueName("requirements-only-lt"),
+ "InstanceRequirements.VCpuCount.Min", "2",
+ "InstanceRequirements.MemoryMiB.Min", "1024").statusCode(200);
+ }
+
+ @Test
+ void allowedAndExcludedInstanceTypesTogetherAreRejected() {
+ // "If you specify AllowedInstanceTypes, you can't specify ExcludedInstanceTypes."
+ assertInvalidParameterCombination(createWithRequirements(uniqueName("both-lists-lt"),
+ "VCpuCount.Min", "2", "MemoryMiB.Min", "1024",
+ "AllowedInstanceType.1", "m5.*", "ExcludedInstanceType.1", "t2.*"));
+ createWithRequirements(uniqueName("allowed-only-lt"),
+ "VCpuCount.Min", "2", "MemoryMiB.Min", "1024", "AllowedInstanceType.1", "m5.*")
+ .statusCode(200);
+ createWithRequirements(uniqueName("excluded-only-lt"),
+ "VCpuCount.Min", "2", "MemoryMiB.Min", "1024", "ExcludedInstanceType.1", "t2.*")
+ .statusCode(200);
+ }
+
+ @Test
+ void bothSpotPriceCeilingsTogetherAreRejected() {
+ // "Only one of SpotMaxPricePercentageOverLowestPrice or
+ // MaxSpotPriceAsPercentageOfOptimalOnDemandPrice can be specified."
+ assertInvalidParameterCombination(createWithRequirements(uniqueName("both-spot-lt"),
+ "VCpuCount.Min", "2", "MemoryMiB.Min", "1024",
+ "SpotMaxPricePercentageOverLowestPrice", "20",
+ "MaxSpotPriceAsPercentageOfOptimalOnDemandPrice", "40"));
+ createWithRequirements(uniqueName("spot-over-lowest-lt"),
+ "VCpuCount.Min", "2", "MemoryMiB.Min", "1024",
+ "SpotMaxPricePercentageOverLowestPrice", "20")
+ .statusCode(200);
+ createWithRequirements(uniqueName("spot-over-on-demand-lt"),
+ "VCpuCount.Min", "2", "MemoryMiB.Min", "1024",
+ "MaxSpotPriceAsPercentageOfOptimalOnDemandPrice", "40")
+ .statusCode(200);
+ }
+
+ @Test
+ void createLaunchTemplateVersionRejectsTheSameExclusiveCombinations() {
+ String name = uniqueName("version-exclusive-lt");
+ createTemplate(name, "InstanceType", "t3.micro").statusCode(200);
+
+ assertInvalidParameterCombination(createVersion(name, null,
+ "InstanceType", "t3.small",
+ "InstanceRequirements.VCpuCount.Min", "2",
+ "InstanceRequirements.MemoryMiB.Min", "1024"));
+ assertInvalidParameterCombination(createVersion(name, null,
+ "InstanceRequirements.VCpuCount.Min", "2",
+ "InstanceRequirements.MemoryMiB.Min", "1024",
+ "InstanceRequirements.AllowedInstanceType.1", "m5.*",
+ "InstanceRequirements.ExcludedInstanceType.1", "t2.*"));
+ assertInvalidParameterCombination(createVersion(name, null,
+ "InstanceRequirements.VCpuCount.Min", "2",
+ "InstanceRequirements.MemoryMiB.Min", "1024",
+ "InstanceRequirements.SpotMaxPricePercentageOverLowestPrice", "20",
+ "InstanceRequirements.MaxSpotPriceAsPercentageOfOptimalOnDemandPrice", "40"));
+
+ assertLatestVersionIs(name, "1");
+ }
+
+ @Test
+ void aVersionNamingAnInstanceTypeOverAnAttributeBasedSourceIsRejected() {
+ // The merge carries InstanceRequirements forward and has no way to express removal, so
+ // this version would store both. The stored version is what AutoScaling and the fleet
+ // APIs read, so it is validated after the merge rather than only as it arrived.
+ String name = uniqueName("merge-conflict-lt");
+ createTemplate(name,
+ "InstanceRequirements.VCpuCount.Min", "2",
+ "InstanceRequirements.MemoryMiB.Min", "1024").statusCode(200);
+
+ assertInvalidParameterCombination(createVersion(name, "1", "InstanceType", "t3.micro"));
+ assertLatestVersionIs(name, "1");
+
+ // Starting from empty data instead of the source is how a caller switches selection mode.
+ createVersion(name, null, "InstanceType", "t3.micro").statusCode(200);
+ describeLatest(name).body(DATA + "instanceType", equalTo("t3.micro"));
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java
index 89911f6059..16abb3ba75 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java
@@ -506,6 +506,70 @@ class Ec2ServiceTest {
assertEquals("source", data.getInstanceTags().getFirst().getValue());
}
+ @Test
+ void launchTemplateVersionInheritsMarketOptionsRequirementsAndConnectionTracking() {
+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
+ mock(Ec2PortForwardManager.class),
+ mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
+ new InMemoryStorageFactory());
+ LaunchTemplateData source = new LaunchTemplateData();
+ source.setImageId("ami-source");
+
+ LaunchTemplateData.SpotOptions spotOptions = new LaunchTemplateData.SpotOptions();
+ spotOptions.setMaxPrice("0.05");
+ spotOptions.setSpotInstanceType("one-time");
+ LaunchTemplateData.InstanceMarketOptions marketOptions = new LaunchTemplateData.InstanceMarketOptions();
+ marketOptions.setMarketType("spot");
+ marketOptions.setSpotOptions(spotOptions);
+ source.setInstanceMarketOptions(marketOptions);
+
+ LaunchTemplateData.InstanceRequirements requirements = new LaunchTemplateData.InstanceRequirements();
+ requirements.setVCpuCount(new LaunchTemplateData.IntRange(2, 8));
+ requirements.setMemoryMiB(new LaunchTemplateData.IntRange(1024, null));
+ requirements.setMemoryGiBPerVCpu(new LaunchTemplateData.DoubleRange(0.5, 4.0));
+ requirements.setCpuManufacturers(List.of("intel", "amd"));
+ source.setInstanceRequirements(requirements);
+
+ LaunchTemplateData.ConnectionTrackingSpecification tracking =
+ new LaunchTemplateData.ConnectionTrackingSpecification();
+ tracking.setTcpEstablishedTimeout(60);
+ tracking.setUdpStreamTimeout(120);
+ LaunchTemplateData.NetworkInterface networkInterface = new LaunchTemplateData.NetworkInterface();
+ networkInterface.setDeviceIndex(0);
+ networkInterface.setConnectionTrackingSpecification(tracking);
+ source.setNetworkInterfaces(List.of(networkInterface));
+
+ LaunchTemplate template = service.createLaunchTemplate("us-east-1", "spot-template", source, List.of());
+
+ // The source selects instance types by attribute, so the new version restates a member
+ // that does not collide with InstanceRequirements.
+ LaunchTemplateData override = new LaunchTemplateData();
+ override.setImageId("ami-override");
+ service.createLaunchTemplateVersion("us-east-1", template.getLaunchTemplateId(), null, "1", override);
+
+ LaunchTemplateData data = service.describeLaunchTemplateVersions(
+ "us-east-1", template.getLaunchTemplateId(), null, List.of("2")).getFirst().getData();
+ assertEquals("ami-override", data.getImageId());
+ assertEquals("spot", data.getInstanceMarketOptions().getMarketType());
+ assertEquals("0.05", data.getInstanceMarketOptions().getSpotOptions().getMaxPrice());
+ assertEquals("one-time", data.getInstanceMarketOptions().getSpotOptions().getSpotInstanceType());
+ assertNull(data.getInstanceMarketOptions().getSpotOptions().getBlockDurationMinutes(),
+ "an unset SpotOptions member must not acquire a value on the way through a version");
+ assertEquals(2, data.getInstanceRequirements().getVCpuCount().getMin());
+ assertEquals(8, data.getInstanceRequirements().getVCpuCount().getMax());
+ assertEquals(0.5, data.getInstanceRequirements().getMemoryGiBPerVCpu().getMin());
+ assertEquals(List.of("intel", "amd"), data.getInstanceRequirements().getCpuManufacturers());
+ assertEquals(1024, data.getInstanceRequirements().getMemoryMiB().getMin());
+ assertNull(data.getInstanceRequirements().getNetworkInterfaceCount(),
+ "an unset InstanceRequirements range must stay null rather than default to a range");
+ assertNull(data.getInstanceRequirements().getBaselinePerformanceFactors());
+ LaunchTemplateData.ConnectionTrackingSpecification inherited =
+ data.getNetworkInterfaces().getFirst().getConnectionTrackingSpecification();
+ assertEquals(60, inherited.getTcpEstablishedTimeout());
+ assertEquals(120, inherited.getUdpStreamTimeout());
+ assertNull(inherited.getUdpTimeout(), "an unset UdpTimeout must stay absent");
+ }
+
@Test
void launchTemplateVersionWithoutSourceVersionDoesNotInheritFromLatest() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),