feat(ec2): report instance credit specifications (#3492)

* feat(ec2): report instance credit specifications

DescribeInstanceCreditSpecifications was not implemented, so the action
Terraform's aws_instance resource reads credit_specification from always came
back empty and every plan after an apply showed a credit_specification diff for
an instance nobody had touched. CreditSpecification is not a member of the
Instance shape DescribeInstances returns, per botocore's ec2 2016-11-15 model,
so this dedicated action is the only way that value can reach a client.

The credit option is the launch's explicit CreditSpecification.CpuCredits when
the request named one, and the instance type family's documented default
otherwise: standard for t2, unlimited for t3, t3a and t4g. The model's own
InstanceType enum lists t1, t2, t3, t3a and t4g as the only T families, and t1
predates the credit model, so that table is complete. The default is resolved on
read rather than frozen at launch, so a resize moves the instance onto its new
family's default.

The two request shapes mean different things and both are implemented. Naming
instance ids reports exactly those instances, and an id with no credit option is
an error rather than an omission, which is what the model documents for "an
instance that is not a burstable performance instance". Naming no ids reports
only the instances running unlimited, paginated by MaxResults and NextToken;
AWS rejects MaxResults together with instance ids and so does this.

DescribeInstanceTypes now reports burstablePerformanceSupported. Terraform
checks that flag before it reads a credit specification at all, so without it
the new action would never be called.

ModifyInstanceCreditSpecification is deliberately left out. Describe stands on
its own here: it fixes the read that produced the perpetual diff, and a launch
can already set the option through RunInstances or launch template data. The
modify path is a separate change.

Tests: Ec2InstanceCreditSpecificationsIntegrationTest covers each burstable
family default, a non-burstable type, an explicit launch-time override, an
unknown instance id, the unfiltered form and the MaxResults combination error
on the real Query wire. Ec2InstanceTypeCatalogTest covers the family table.
Ec2RunInstancesPublicIpParamTest's mocked signature gains the new parameter.

* fix(ec2): persist the instance credit option and report standard for non-burstable ids

The first cut of DescribeInstanceCreditSpecifications had the documented behaviour
backwards on two points. Both come from the operation's own documentation string in
botocore's ec2 2016-11-15 model, which the constraint keys alone do not carry.

"If you specify an instance ID that is not a burstable performance instance, Amazon
EC2 returns the standard credit option." A named m5 was answered with
InvalidInstanceID.NotFound, because effectiveCpuCredits() returned null for a type
with no credit model and the named-id path treated that as an unknown id. It now
reports standard. An id that names no instance at all is still
InvalidInstanceID.NotFound, which is the only error that path raises.

The unfiltered form returns burstable instances on the unlimited option "as well as
instances that were previously configured as T2, T3, and T3a with the unlimited
credit option. For example, if you resize a T2 instance, while it is configured as
unlimited, to an M4 instance, Amazon EC2 returns the M4 instance." A launch without
an explicit CreditSpecification stored null and the credit option was recomputed from
the instance's current type on every read, so a t3 that defaulted to unlimited lost
that option the moment it was resized onto an m5. The option is now resolved once, at
the point the instance acquires it, and stored on the instance:
Instance.creditSpecificationCpuCredits, written in runInstances from the request or
the family default, and written again in modifyInstanceAttribute when a resize moves
an instance with no option yet onto a burstable type. Reads return the stored value.
The family default stays on the read path only as a fallback for instance records
written before the option was stored.

Tests: aNonBurstableInstanceIdReportsStandard replaces the regression that locked in
the error. theUnlimitedOptionSurvivesAResizeOntoANonBurstableType,
aResizeOntoABurstableTypeAcquiresTheFamilyDefault and
aStandardOptionSurvivesAResizeOntoAnotherBurstableFamily cover the resize paths, and
the unfiltered-form test now also asserts a non-burstable instance is absent.

* fix(ec2): honor DryRun, Filter.N and the MaxResults range on DescribeInstanceCreditSpecifications

The EC2 model declares more request behavior for this action than the handler
accepted. All three gaps come from local/model-preflight.py ec2
DescribeInstanceCreditSpecifications, which prints the constraint keys and the
documentation prose together.

DryRun is a modeled member and the handler never probed it, so DryRun=true
returned a normal response instead of DryRunOperation. The pagination parameters
are now validated before the probe, matching the order the snapshot block public
access handlers use, since AWS reports an invalid parameter ahead of
DryRunOperation and only returns DryRunOperation once the request could
otherwise succeed.

Filter.N is a modeled member and was parsed nowhere. The model declares one
filter name here, instance-id, which Ec2Service.matchesFilter already resolves
for an Instance, so both request shapes now run their candidates through
matchesFilters. Named ids still decide the base set and are still validated for
existence, then the filters narrow that set with an AND, which is what the
Filters member documents. An unrecognised filter name matches everything,
following the default arm every other filtered EC2 Describe action in this
service already takes.

DescribeInstanceCreditSpecificationsMaxResults carries a min of 5 and a max of
1000, and any positive integer was accepted, so 1 and 1001 were treated as page
sizes. Out of range now raises InvalidMaxResults with the message
describeNetworkInterfaces already uses for the same range.

Tests: maxResultsHonorsItsModeledRange covers 5, 1000, 4 and 1001,
dryRunReturnsDryRunOperation and anInvalidMaxResultsIsReportedAheadOfDryRun
cover the probe and its ordering, and four filter tests cover the unfiltered
form, named ids, an unknown named id under a filter and an unrecognised filter
name.
This commit is contained in:
lex00 authored and GitHub committed 2026-09-13 00:26:47 -04:00
1 parent 24a8c8440b
commit 325bdfb30e
10 files changed
+714 -6

No files matched your search

+2 -1
View File
@@ -175,6 +175,7 @@ Floci seeds the following resources on first use in each region so Terraform, th
| StopInstances | Stops running instances and updates their stored lifecycle state. |
| RebootInstances | Reboots instances through the local EC2 service model. |
| DescribeInstanceStatus | Returns status records for stored instances. |
| DescribeInstanceCreditSpecifications | Returns the CPU credit option of burstable performance instances. A named instance id reports the option the instance acquired at launch, either the explicit `CreditSpecification.CpuCredits` or the family default, `standard` for t2 and `unlimited` for t3, t3a and t4g. An id that is not a burstable performance instance reports `standard`, and only an unknown id is an error. Naming no id returns the instances on the unlimited option, including one that kept `unlimited` after a resize onto a non-burstable type. `Filter.N` supports the modeled `instance-id` and narrows whichever set the request selected. `MaxResults` accepts 5 through 1000 and cannot be combined with instance ids. `DryRun=true` returns `DryRunOperation`. |
| DescribeInstanceAttribute | Returns a supported attribute for an instance. |
| ModifyInstanceAttribute | Updates supported mutable attributes for an instance. |
| ModifyInstanceMetadataOptions | Updates an instance's IMDS options, changing only the fields the request names. |
@@ -528,7 +529,7 @@ allocated address.
| Action | Description |
|--------|-------------|
| DescribeInstanceTypes | Returns instance type metadata known to the local EC2 service. |
| DescribeInstanceTypes | Returns instance type metadata known to the local EC2 service, including `burstablePerformanceSupported` for the T families. |
| DescribeInstanceTypeOfferings | Returns instance type offerings for the requested location filters. |
### Launch Templates
@@ -21,6 +21,21 @@ public class Ec2InstanceTypeCatalog {
private static final String CATALOG_RESOURCE_NAME = "ec2/instance-type-catalog.yaml";
private static final ObjectMapper YAML_MAPPER = new ObjectMapper(new YAMLFactory());
/**
* The burstable performance families and the credit option each one launches with when the
* request names none. AWS documents t2 as standard and t3, t3a and t4g as unlimited; every
* other family, t1 included, has no credit model at all. The EC2 model's own InstanceType
* enum lists t1, t2, t3, t3a and t4g as the only T families, so this table is complete.
*
* <p>Family derivation rather than a per-type catalog entry, because the catalog holds only
* the sizes Floci ships metadata for while a launch may name any size of a burstable family.
*/
private static final Map<String, String> DEFAULT_CPU_CREDITS_BY_FAMILY = Map.of(
"t2", "standard",
"t3", "unlimited",
"t3a", "unlimited",
"t4g", "unlimited");
private volatile Loaded loaded;
public Ec2InstanceTypeCatalog() {
@@ -43,6 +58,26 @@ public class Ec2InstanceTypeCatalog {
return Optional.ofNullable(loaded().instanceTypesByName.get(instanceType));
}
/**
* The credit option a launch of this instance type gets when it names no CreditSpecification,
* or empty when the type has no burstable credit model.
*/
public static Optional<String> defaultCpuCredits(String instanceType) {
return Optional.ofNullable(DEFAULT_CPU_CREDITS_BY_FAMILY.get(familyOf(instanceType)));
}
public static boolean isBurstablePerformanceType(String instanceType) {
return DEFAULT_CPU_CREDITS_BY_FAMILY.containsKey(familyOf(instanceType));
}
private static String familyOf(String instanceType) {
if (instanceType == null) {
return "";
}
int separator = instanceType.indexOf('.');
return separator < 0 ? instanceType : instanceType.substring(0, separator);
}
private Loaded loaded() {
Loaded result = loaded;
if (result == null) {
@@ -176,6 +211,7 @@ public class Ec2InstanceTypeCatalog {
type.put("supportedArchitectures", List.copyOf(supportedArchitectures));
type.put("supportedUsageClasses", List.copyOf(supportedUsageClasses));
type.put("currentGeneration", currentGeneration == null || currentGeneration);
type.put("burstablePerformanceSupported", isBurstablePerformanceType(instanceType));
Map<String, Object> networkInfo = new LinkedHashMap<>();
networkInfo.put("encryptionInTransitSupported", encryptionInTransitSupported);
networkInfo.put("defaultNetworkCardIndex", defaultNetworkCardIndex);
@@ -74,6 +74,7 @@ public class Ec2QueryHandler {
case "MonitorInstances" -> handleMonitoring(params, region, "MonitorInstances", true);
case "UnmonitorInstances" -> handleMonitoring(params, region, "UnmonitorInstances", false);
case "DescribeInstanceStatus" -> handleDescribeInstanceStatus(params, region);
case "DescribeInstanceCreditSpecifications" -> handleDescribeInstanceCreditSpecifications(params, region);
case "DescribeInstanceAttribute" -> handleDescribeInstanceAttribute(params, region);
case "ModifyInstanceAttribute" -> handleModifyInstanceAttribute(params, region);
case "ModifyInstanceMetadataOptions" -> handleModifyInstanceMetadataOptions(params, region);
@@ -731,6 +732,7 @@ public class Ec2QueryHandler {
// Absent fields stay null so the launch default, or the launch template's value, applies.
LaunchTemplateData.MetadataOptions metadataOptions = parseMetadataOptions(p, "MetadataOptions.");
String creditSpecificationCpuCredits = p.getFirst("CreditSpecification.CpuCredits");
LaunchTemplateData launchTemplateData = resolveRunInstancesLaunchTemplateData(p, region);
if (launchTemplateData != null) {
@@ -738,6 +740,10 @@ public class Ec2QueryHandler {
metadataOptions = LaunchTemplateData.MetadataOptions.merge(
launchTemplateData.getMetadataOptions(), metadataOptions);
}
if (launchTemplateData.getCreditSpecification() != null) {
creditSpecificationCpuCredits = firstNonBlank(creditSpecificationCpuCredits,
launchTemplateData.getCreditSpecification().getCpuCredits());
}
imageId = firstNonBlank(imageId, launchTemplateData.getImageId());
instanceType = firstNonBlank(instanceType, launchTemplateData.getInstanceType());
keyName = firstNonBlank(keyName, launchTemplateData.getKeyName());
@@ -757,7 +763,8 @@ public class Ec2QueryHandler {
Reservation res = service.runInstances(region, imageId, instanceType, minCount, maxCount,
keyName, sgIds, subnetId, clientToken, instanceTags, userData, iamInstanceProfileArn,
associatePublicIp, networkInterfaceId, networkInterfaceDeviceIndex, null, metadataOptions);
associatePublicIp, networkInterfaceId, networkInterfaceDeviceIndex, null, metadataOptions,
creditSpecificationCpuCredits);
if (!networkInterfaceTags.isEmpty()) {
List<String> eniIds = new ArrayList<>();
@@ -1310,6 +1317,44 @@ public class Ec2QueryHandler {
return xmlResponse(xml.build());
}
/**
* CreditSpecification is not a member of the Instance shape DescribeInstances returns, per the
* EC2 model, so this dedicated action is the only place an instance's credit option reaches
* the wire. Terraform's aws_instance resource reads credit_specification from here.
*/
private Response handleDescribeInstanceCreditSpecifications(MultivaluedMap<String, String> p, String region) {
List<String> ids = getList(p, "InstanceId");
Map<String, List<String>> filters = getFilters(p);
int maxResults = parseIntParam(p, "MaxResults", 0);
String nextToken = p.getFirst("NextToken");
// Validate the pagination parameters before honoring DryRun. AWS returns DryRunOperation
// only once the request would otherwise have succeeded, so a MaxResults outside its
// modeled range still fails on its own error.
service.validateInstanceCreditSpecificationsPagination(ids, maxResults);
checkDryRun(p);
InstanceCreditSpecificationListResult result =
service.describeInstanceCreditSpecifications(region, ids, filters, maxResults, nextToken);
XmlBuilder xml = new XmlBuilder()
.start("DescribeInstanceCreditSpecificationsResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("instanceCreditSpecificationSet");
for (InstanceCreditSpecification spec : result.instanceCreditSpecifications()) {
xml.start("item")
.elem("instanceId", spec.instanceId())
.elem("cpuCredits", spec.cpuCredits())
.end("item");
}
xml.end("instanceCreditSpecificationSet");
if (result.nextToken() != null) {
xml.elem("nextToken", result.nextToken());
}
xml.end("DescribeInstanceCreditSpecificationsResponse");
return xmlResponse(xml.build());
}
private Response handleDescribeInstanceAttribute(MultivaluedMap<String, String> p, String region) {
String instanceId = p.getFirst("InstanceId");
String attribute = p.getFirst("Attribute");
@@ -3958,7 +4003,8 @@ public class Ec2QueryHandler {
.start("memoryInfo")
.elem("sizeInMiB", String.valueOf(t.get("memoryMib")))
.end("memoryInfo")
.elem("instanceStorageSupported", String.valueOf(t.get("instanceStorageSupported")));
.elem("instanceStorageSupported", String.valueOf(t.get("instanceStorageSupported")))
.elem("burstablePerformanceSupported", String.valueOf(t.get("burstablePerformanceSupported")));
if (Boolean.TRUE.equals(t.get("instanceStorageSupported"))) {
xml.start("instanceStorageInfo")
.elem("totalSizeInGB", String.valueOf(t.get("localStorageGiB")))
@@ -50,6 +50,8 @@ import io.github.hectorvent.floci.services.ec2.net.VpcNetworkManager;
import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
import io.github.hectorvent.floci.services.ec2.model.Image;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.services.ec2.model.InstanceCreditSpecification;
import io.github.hectorvent.floci.services.ec2.model.InstanceCreditSpecificationListResult;
import io.github.hectorvent.floci.services.ec2.model.InstanceNetworkInterface;
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
import io.github.hectorvent.floci.services.ec2.model.NetworkInterface;
@@ -2446,6 +2448,28 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
Boolean associatePublicIp, String networkInterfaceId,
int networkInterfaceDeviceIndex, String availabilityZone,
LaunchTemplateData.MetadataOptions metadataOptions) {
return runInstances(region, imageId, instanceType, minCount, maxCount, keyName,
securityGroupIds, subnetId, clientToken, instanceTags, userData,
iamInstanceProfileArn, associatePublicIp, networkInterfaceId,
networkInterfaceDeviceIndex, availabilityZone, metadataOptions, null);
}
/**
* @param creditSpecificationCpuCredits the launch's explicit CreditSpecification.CpuCredits,
* or null when the request named none. A burstable
* launch that names none acquires its family's
* documented default and stores it on the instance, so
* the option outlives a later resize.
*/
public Reservation runInstances(String region, String imageId, String instanceType,
int minCount, int maxCount, String keyName,
List<String> securityGroupIds, String subnetId,
String clientToken, List<Tag> instanceTags,
String userData, String iamInstanceProfileArn,
Boolean associatePublicIp, String networkInterfaceId,
int networkInterfaceDeviceIndex, String availabilityZone,
LaunchTemplateData.MetadataOptions metadataOptions,
String creditSpecificationCpuCredits) {
if (imageId == null || imageId.isBlank()) {
throw new AwsException("MissingParameter", "The request must contain the parameter ImageId", 400);
}
@@ -2454,6 +2478,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
// their ancestry, so the launch path has to reject it explicitly.
requireNotDeregistered(region, imageId);
validateMetadataOptions(metadataOptions);
validateCreditSpecification(creditSpecificationCpuCredits);
LaunchTemplateData.MetadataOptions launchMetadataOptions = LaunchTemplateData.MetadataOptions.merge(
LaunchTemplateData.MetadataOptions.launchDefaults(), metadataOptions);
ensureDefaultResources(region);
@@ -2587,6 +2612,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
inst.setUserData(userData);
inst.setIamInstanceProfileArn(iamInstanceProfileArn);
inst.setMetadataOptions(LaunchTemplateData.MetadataOptions.merge(launchMetadataOptions, null));
inst.setCreditSpecificationCpuCredits(
acquiredCpuCredits(effectiveInstanceType, creditSpecificationCpuCredits));
if (instanceTags != null && !instanceTags.isEmpty()) {
inst.setTags(new ArrayList<>(instanceTags));
tags.put(instanceId, new ArrayList<>(instanceTags));
@@ -3078,6 +3105,122 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
.collect(Collectors.toList());
}
/**
* The credit option for CPU usage of burstable performance instances.
*
* <p>Two request shapes, and AWS gives them different meanings. Naming instance ids returns
* the credit option of exactly those instances, and the EC2 model documents that "if you
* specify an instance ID that is not a burstable performance instance, Amazon EC2 returns the
* standard credit option", so an m5 reports standard instead of failing. Only an id that
* names no instance at all is an error. Naming none returns the burstable instances on the
* unlimited option "as well as instances that were previously configured as T2, T3, and T3a
* with the unlimited credit option", which is why a t2 on its standard default is absent from
* an unfiltered call but present when its id is named.
*
* <p>The option itself is the value the instance stored when it acquired one, at launch or at
* a resize onto a burstable type. It is read back rather than recomputed from the current
* instance type, because recomputing would drop the unlimited option the moment a resize took
* the instance out of the T family.
*
* <p>Filters narrow whichever of the two sets the request selected. The EC2 model declares
* one filter name here, {@code instance-id}, and documents that "if you specify multiple
* filters, the filters are joined with an AND, and the request returns only results that
* match all of the specified filters". Named ids still decide the base set and are still
* validated for existence, so an id that names no instance fails even when a filter would
* have excluded it. An unrecognised filter name matches everything, which is what every
* other filtered EC2 Describe action in this service already does.
*
* @param instanceIds the ids to report on, or empty for the unfiltered form
* @param filters the Filter.N entries, joined with an AND
* @param maxResults page size, or 0 for no pagination. AWS rejects it together with ids
* @param nextToken the cursor from a previous page, or null
*/
public InstanceCreditSpecificationListResult describeInstanceCreditSpecifications(
String region, List<String> instanceIds, Map<String, List<String>> filters,
int maxResults, String nextToken) {
validateInstanceCreditSpecificationsPagination(instanceIds, maxResults);
ensureDefaultResources(region);
if (!instanceIds.isEmpty()) {
List<InstanceCreditSpecification> named = new ArrayList<>();
for (String instanceId : instanceIds) {
Instance inst = getRequiredInstance(region, instanceId);
if (!matchesFilters(inst, filters, region)) {
continue;
}
named.add(new InstanceCreditSpecification(instanceId, effectiveCpuCredits(inst)));
}
return new InstanceCreditSpecificationListResult(named, null);
}
List<InstanceCreditSpecification> unlimited = instances.scan(k -> true).stream()
.filter(i -> i.getRegion().equals(region))
.filter(i -> "unlimited".equals(effectiveCpuCredits(i)))
.filter(i -> matchesFilters(i, filters, region))
.map(i -> new InstanceCreditSpecification(i.getInstanceId(), "unlimited"))
.collect(Collectors.toList());
if (maxResults > 0) {
int offset = decodeToken(nextToken);
int total = unlimited.size();
int toIndex = Math.min(offset + maxResults, total);
List<InstanceCreditSpecification> page = offset < total
? unlimited.subList(offset, toIndex)
: Collections.emptyList();
String newNextToken = toIndex < total ? encodeToken(toIndex) : null;
return new InstanceCreditSpecificationListResult(new ArrayList<>(page), newNextToken);
}
return new InstanceCreditSpecificationListResult(unlimited, null);
}
/**
* Validate the pagination parameters of DescribeInstanceCreditSpecifications without touching
* stored state, so a caller can reject a bad request before it honors DryRun. AWS reports an
* invalid parameter ahead of DryRunOperation, which it only returns once the request could
* otherwise succeed.
*
* <p>DescribeInstanceCreditSpecificationsMaxResults carries a min of 5 and a max of 1000 in
* the EC2 model, and InvalidMaxResults is the code this service already raises for a
* MaxResults outside its modeled range.
*/
public void validateInstanceCreditSpecificationsPagination(List<String> instanceIds, int maxResults) {
if (maxResults > 0 && !instanceIds.isEmpty()) {
throw new AwsException("InvalidParameterCombination",
"The parameter instanceIdsSet cannot be used with the parameter maxResults", 400);
}
if (maxResults > 0 && (maxResults < 5 || maxResults > 1000)) {
throw new AwsException("InvalidMaxResults",
"Value (" + maxResults + ") for parameter MaxResults is invalid. "
+ "Expecting a value between 5 and 1000.", 400);
}
}
/**
* The credit option an instance stores when it acquires one, either the option the caller
* named or the instance type family's documented default. Null for a type with no credit
* model, which is how an instance that never carried a credit option stays out of the
* unfiltered DescribeInstanceCreditSpecifications response.
*/
private static String acquiredCpuCredits(String instanceType, String requestedCpuCredits) {
if (requestedCpuCredits != null && !requestedCpuCredits.isBlank()) {
return requestedCpuCredits;
}
return Ec2InstanceTypeCatalog.defaultCpuCredits(instanceType).orElse(null);
}
/**
* The stored credit option. The family default covers a record written before the option was
* stored at launch, and standard covers a type with no credit model at all, which is what the
* EC2 model documents for an instance id that is not a burstable performance instance.
*/
private static String effectiveCpuCredits(Instance inst) {
String stored = inst.getCreditSpecificationCpuCredits();
if (stored != null) {
return stored;
}
return Ec2InstanceTypeCatalog.defaultCpuCredits(inst.getInstanceType()).orElse("standard");
}
public Instance describeInstanceAttribute(String region, String instanceId, String attribute) {
ensureDefaultResources(region);
Instance inst = getRequiredInstance(region, instanceId);
@@ -3091,7 +3234,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
// basic attribute modifications
switch (attribute) {
case "instanceType" -> inst.setInstanceType(value);
case "instanceType" -> {
inst.setInstanceType(value);
// A resize onto a burstable type acquires that family's default. A resize away
// from one changes nothing, because AWS keeps reporting the unlimited option of
// an instance that was configured as a T2, T3 or T3a and then resized.
if (inst.getCreditSpecificationCpuCredits() == null) {
inst.setCreditSpecificationCpuCredits(acquiredCpuCredits(value, null));
}
}
case "sourceDestCheck" -> inst.setSourceDestCheck(Boolean.parseBoolean(value));
case "ebsOptimized" -> inst.setEbsOptimized(Boolean.parseBoolean(value));
}
@@ -3165,6 +3316,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
+ String.join(", ", allowed) + ".", 400);
}
private static void validateCreditSpecification(String cpuCredits) {
if (cpuCredits == null || "standard".equals(cpuCredits) || "unlimited".equals(cpuCredits)) {
return;
}
throw new AwsException("InvalidParameterValue",
"Value (" + cpuCredits + ") for parameter CreditSpecification.CpuCredits is invalid. "
+ "Valid values are: standard, unlimited.", 400);
}
private Instance getRequiredInstance(String region, String instanceId) {
Instance inst = instances.get(key(region, instanceId)).orElse(null);
if (inst == null)
@@ -61,6 +61,15 @@ public class Instance {
// AWS's launch defaults through effectiveMetadataOptions().
private LaunchTemplateData.MetadataOptions metadataOptions;
// The credit option this instance acquired, at launch from the request or from its burstable
// family's default, or at a resize onto a burstable type. Stored rather than derived from the
// current instance type on read, because AWS keeps reporting the unlimited option of an
// instance that was configured as a T2, T3 or T3a and then resized onto another family. Null
// for an instance that never acquired one. CreditSpecification is not a member of the Instance
// shape DescribeInstances returns, so this reaches the wire only through
// DescribeInstanceCreditSpecifications.
private String creditSpecificationCpuCredits;
// Docker backing fields (not serialised to AWS wire format)
private String dockerContainerId;
private String containerBridgeIp;
@@ -218,6 +227,9 @@ public class Instance {
public LaunchTemplateData.MetadataOptions getMetadataOptions() { return metadataOptions; }
public void setMetadataOptions(LaunchTemplateData.MetadataOptions metadataOptions) { this.metadataOptions = metadataOptions; }
public String getCreditSpecificationCpuCredits() { return creditSpecificationCpuCredits; }
public void setCreditSpecificationCpuCredits(String creditSpecificationCpuCredits) { this.creditSpecificationCpuCredits = creditSpecificationCpuCredits; }
/** The stored metadata options, or AWS's launch defaults for a record that has none. */
public LaunchTemplateData.MetadataOptions effectiveMetadataOptions() {
return metadataOptions != null ? metadataOptions : LaunchTemplateData.MetadataOptions.launchDefaults();
@@ -0,0 +1,13 @@
package io.github.hectorvent.floci.services.ec2.model;
/**
* The credit option for CPU usage of one burstable performance instance.
*
* @param instanceId the instance
* @param cpuCredits the credit option, either {@code standard} or {@code unlimited}
* @see <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_InstanceCreditSpecification.html">AWS EC2 InstanceCreditSpecification</a>
*/
public record InstanceCreditSpecification(
String instanceId,
String cpuCredits
) {}
@@ -0,0 +1,15 @@
package io.github.hectorvent.floci.services.ec2.model;
import java.util.List;
/**
* Result of a paginated DescribeInstanceCreditSpecifications call.
*
* @param instanceCreditSpecifications the credit options for this page
* @param nextToken token for the next page, or {@code null} when the page is the last
* @see <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstanceCreditSpecifications.html">AWS EC2 DescribeInstanceCreditSpecifications</a>
*/
public record InstanceCreditSpecificationListResult(
List<InstanceCreditSpecification> instanceCreditSpecifications,
String nextToken
) {}
@@ -0,0 +1,397 @@
package io.github.hectorvent.floci.services.ec2;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.util.List;
/**
* DescribeInstanceCreditSpecifications on the Query wire. Terraform's aws_instance resource
* reads credit_specification from this action and from nowhere else, since CreditSpecification
* is not a member of the Instance shape DescribeInstances returns. Without it the read came back
* empty and every plan after an apply showed a credit_specification diff for an instance nobody
* had touched.
*/
@QuarkusTest
class Ec2InstanceCreditSpecificationsIntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
private static final String ITEM =
"DescribeInstanceCreditSpecificationsResponse.instanceCreditSpecificationSet.item.";
@Test
void t2DefaultsToStandardAndTheOtherBurstableFamiliesDefaultToUnlimited() {
assertCpuCredits(launch("t2.micro", null), "standard");
assertCpuCredits(launch("t3.micro", null), "unlimited");
assertCpuCredits(launch("t3a.micro", null), "unlimited");
assertCpuCredits(launch("t4g.micro", null), "unlimited");
}
@Test
void anExplicitLaunchTimeCreditOptionWinsOverTheFamilyDefault() {
assertCpuCredits(launch("t2.micro", "unlimited"), "unlimited");
assertCpuCredits(launch("t3.micro", "standard"), "standard");
}
/**
* The EC2 model, verbatim: "If you specify an instance ID that is not a burstable performance
* instance, Amazon EC2 returns the standard credit option." A named m5 is a report, not an
* error.
*/
@Test
void aNonBurstableInstanceIdReportsStandard() {
assertCpuCredits(launch("m5.large", null), "standard");
}
/**
* The EC2 model, verbatim: the unfiltered form returns "instances that were previously
* configured as T2, T3, and T3a with the unlimited credit option. For example, if you resize a
* T2 instance, while it is configured as unlimited, to an M4 instance, Amazon EC2 returns the
* M4 instance."
*/
@Test
void theUnlimitedOptionSurvivesAResizeOntoANonBurstableType() {
String instanceId = launch("t3.micro", null);
resize(instanceId, "m5.large");
assertCpuCredits(instanceId, "unlimited");
assertTrue(unfilteredInstanceIds().contains(instanceId));
}
@Test
void aResizeOntoABurstableTypeAcquiresTheFamilyDefault() {
String instanceId = launch("m5.large", null);
assertCpuCredits(instanceId, "standard");
resize(instanceId, "t3.micro");
assertCpuCredits(instanceId, "unlimited");
assertTrue(unfilteredInstanceIds().contains(instanceId));
}
@Test
void aStandardOptionSurvivesAResizeOntoAnotherBurstableFamily() {
String instanceId = launch("t2.micro", null);
resize(instanceId, "t3.micro");
assertCpuCredits(instanceId, "standard");
assertFalse(unfilteredInstanceIds().contains(instanceId));
}
@Test
void anUnknownInstanceIdIsAnError() {
given()
.formParam("Action", "DescribeInstanceCreditSpecifications")
.formParam("InstanceId.1", "i-00000000000000000")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidInstanceID.NotFound"));
}
@Test
void anInvalidLaunchTimeCreditOptionIsRejected() {
given()
.formParam("Action", "RunInstances")
.formParam("ImageId", "ami-0abcdef1234567890")
.formParam("InstanceType", "t3.micro")
.formParam("MinCount", "1")
.formParam("MaxCount", "1")
.formParam("CreditSpecification.CpuCredits", "boundless")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));
}
/**
* The unfiltered form reports only the instances running on the unlimited option, so a t2 on
* its standard default is absent from it while the t3 beside it is present. Naming that same
* t2's id still reports it, which is the difference the two request shapes carry.
*/
@Test
void theUnfilteredFormReportsOnlyUnlimitedInstances() {
String standardInstance = launch("t2.micro", null);
String unlimitedInstance = launch("t3.micro", null);
String nonBurstableInstance = launch("m5.large", null);
List<String> reported = unfilteredInstanceIds();
assertTrue(reported.contains(unlimitedInstance));
assertFalse(reported.contains(standardInstance));
assertFalse(reported.contains(nonBurstableInstance));
}
@Test
void maxResultsCapsThePageAndCannotBeCombinedWithInstanceIds() {
launch("t3.micro", null);
launch("t3.small", null);
List<String> page = given()
.formParam("Action", "DescribeInstanceCreditSpecifications")
.formParam("MaxResults", "5")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getList(ITEM + "instanceId", String.class);
assertTrue(page.size() <= 5);
given()
.formParam("Action", "DescribeInstanceCreditSpecifications")
.formParam("InstanceId.1", launch("t3.micro", null))
.formParam("MaxResults", "5")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidParameterCombination"));
}
/**
* DescribeInstanceCreditSpecificationsMaxResults carries a min of 5 and a max of 1000 in the
* EC2 model, so both ends are valid and one step outside either end is InvalidMaxResults.
*/
@Test
void maxResultsHonorsItsModeledRange() {
launch("t3.micro", null);
assertMaxResultsAccepted("5");
assertMaxResultsAccepted("1000");
assertMaxResultsRejected("4");
assertMaxResultsRejected("1001");
}
@Test
void dryRunReturnsDryRunOperation() {
given()
.formParam("Action", "DescribeInstanceCreditSpecifications")
.formParam("DryRun", "true")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(412)
.body("Response.Errors.Error.Code", equalTo("DryRunOperation"));
}
/**
* An invalid MaxResults is reported ahead of DryRunOperation, which AWS returns only once the
* request could otherwise have succeeded. Sibling EC2 actions order the two probes the same
* way.
*/
@Test
void anInvalidMaxResultsIsReportedAheadOfDryRun() {
given()
.formParam("Action", "DescribeInstanceCreditSpecifications")
.formParam("MaxResults", "1001")
.formParam("DryRun", "true")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidMaxResults"));
}
/**
* The EC2 model declares one filter name for this operation, instance-id. On the unfiltered
* form it narrows the set of instances on the unlimited option.
*/
@Test
void anInstanceIdFilterNarrowsTheUnfilteredForm() {
String wanted = launch("t3.micro", null);
String other = launch("t3.small", null);
List<String> reported = filteredInstanceIds("instance-id", wanted);
assertTrue(reported.contains(wanted));
assertFalse(reported.contains(other));
}
/**
* Named ids decide the base set and are still validated for existence, and the filters narrow
* that set with an AND. A named id the filter excludes drops out of the response.
*/
@Test
void anInstanceIdFilterAlsoNarrowsNamedIds() {
String wanted = launch("t3.micro", null);
String excluded = launch("t3.small", null);
List<String> reported = given()
.formParam("Action", "DescribeInstanceCreditSpecifications")
.formParam("InstanceId.1", wanted)
.formParam("InstanceId.2", excluded)
.formParam("Filter.1.Name", "instance-id")
.formParam("Filter.1.Value.1", wanted)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getList(ITEM + "instanceId", String.class);
assertTrue(reported.contains(wanted));
assertFalse(reported.contains(excluded));
}
@Test
void anUnknownNamedIdStillFailsWhenAFilterIsPresent() {
given()
.formParam("Action", "DescribeInstanceCreditSpecifications")
.formParam("InstanceId.1", "i-00000000000000000")
.formParam("Filter.1.Name", "instance-id")
.formParam("Filter.1.Value.1", "i-00000000000000000")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidInstanceID.NotFound"));
}
/**
* An unrecognised filter name matches everything, which is what every other filtered EC2
* Describe action in this handler already does.
*/
@Test
void anUnrecognisedFilterNameMatchesEverything() {
String instanceId = launch("t3.micro", null);
assertTrue(filteredInstanceIds("no-such-filter", "anything").contains(instanceId));
}
private List<String> filteredInstanceIds(String name, String value) {
return given()
.formParam("Action", "DescribeInstanceCreditSpecifications")
.formParam("Filter.1.Name", name)
.formParam("Filter.1.Value.1", value)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getList(ITEM + "instanceId", String.class);
}
private void assertMaxResultsAccepted(String maxResults) {
given()
.formParam("Action", "DescribeInstanceCreditSpecifications")
.formParam("MaxResults", maxResults)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
}
private void assertMaxResultsRejected(String maxResults) {
given()
.formParam("Action", "DescribeInstanceCreditSpecifications")
.formParam("MaxResults", maxResults)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidMaxResults"));
}
/**
* Terraform checks BurstablePerformanceSupported on DescribeInstanceTypes before it reads a
* credit specification at all, so the flag has to be right or the action is never called.
*/
@Test
void describeInstanceTypesReportsBurstablePerformanceSupport() {
assertBurstablePerformanceSupported("t3.micro", "true");
assertBurstablePerformanceSupported("t2.micro", "true");
assertBurstablePerformanceSupported("t4g.medium", "true");
assertBurstablePerformanceSupported("m5.large", "false");
}
private void assertBurstablePerformanceSupported(String instanceType, String expected) {
given()
.formParam("Action", "DescribeInstanceTypes")
.formParam("InstanceType.1", instanceType)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeInstanceTypesResponse.instanceTypeSet.item.burstablePerformanceSupported",
equalTo(expected));
}
private List<String> unfilteredInstanceIds() {
return given()
.formParam("Action", "DescribeInstanceCreditSpecifications")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getList(ITEM + "instanceId", String.class);
}
private void resize(String instanceId, String instanceType) {
given()
.formParam("Action", "ModifyInstanceAttribute")
.formParam("InstanceId", instanceId)
.formParam("InstanceType.Value", instanceType)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
}
private void assertCpuCredits(String instanceId, String expected) {
given()
.formParam("Action", "DescribeInstanceCreditSpecifications")
.formParam("InstanceId.1", instanceId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body(ITEM + "instanceId", equalTo(instanceId))
.body(ITEM + "cpuCredits", equalTo(expected));
}
private String launch(String instanceType, String cpuCredits) {
// t4g is Graviton, so it needs an arm64 image or the launch fails the architecture check.
String imageId = instanceType.startsWith("t4g.") ? "ami-ubuntu2404-arm64" : "ami-0abcdef1234567890";
RequestSpecification request = given()
.formParam("Action", "RunInstances")
.formParam("ImageId", imageId)
.formParam("InstanceType", instanceType)
.formParam("MinCount", "1")
.formParam("MaxCount", "1")
.header("Authorization", AUTH_HEADER);
if (cpuCredits != null) {
request = request.formParam("CreditSpecification.CpuCredits", cpuCredits);
}
String instanceId = request
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
assertTrue(instanceId.startsWith("i-"));
return instanceId;
}
}
@@ -7,6 +7,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@@ -113,6 +114,32 @@ class Ec2InstanceTypeCatalogTest {
assertTrue(error.getMessage().contains("maximumNetworkInterfaces"));
}
@Test
void burstableFamiliesCarryTheirDocumentedDefaultCreditOption() {
assertEquals(Optional.of("standard"), Ec2InstanceTypeCatalog.defaultCpuCredits("t2.micro"));
assertEquals(Optional.of("unlimited"), Ec2InstanceTypeCatalog.defaultCpuCredits("t3.small"));
assertEquals(Optional.of("unlimited"), Ec2InstanceTypeCatalog.defaultCpuCredits("t3a.large"));
assertEquals(Optional.of("unlimited"), Ec2InstanceTypeCatalog.defaultCpuCredits("t4g.medium"));
}
@Test
void nonBurstableFamiliesHaveNoCreditOption() {
assertEquals(Optional.empty(), Ec2InstanceTypeCatalog.defaultCpuCredits("m5.large"));
// t1 is the one T family that predates the credit model.
assertEquals(Optional.empty(), Ec2InstanceTypeCatalog.defaultCpuCredits("t1.micro"));
assertEquals(Optional.empty(), Ec2InstanceTypeCatalog.defaultCpuCredits(null));
assertFalse(Ec2InstanceTypeCatalog.isBurstablePerformanceType("m5.large"));
assertTrue(Ec2InstanceTypeCatalog.isBurstablePerformanceType("t3.micro"));
}
@Test
void responseMapReportsBurstablePerformanceSupport() {
assertEquals(true, instanceTypeCatalog.find("t4g.medium").orElseThrow()
.toResponseMap().get("burstablePerformanceSupported"));
assertEquals(false, instanceTypeCatalog.find("m5.large").orElseThrow()
.toResponseMap().get("burstablePerformanceSupported"));
}
private void assertLargeGravitonType(String name) {
Ec2InstanceTypeCatalog.CatalogInstanceType instanceType = instanceTypeCatalog.find(name).orElseThrow();
@@ -59,7 +59,8 @@ class Ec2RunInstancesPublicIpParamTest {
anyInt(), anyInt(), nullable(String.class), anyList(), nullable(String.class),
nullable(String.class), anyList(), nullable(String.class), nullable(String.class),
nullable(Boolean.class), nullable(String.class), anyInt(), nullable(String.class),
nullable(LaunchTemplateData.MetadataOptions.class))).thenReturn(new Reservation());
nullable(LaunchTemplateData.MetadataOptions.class), nullable(String.class)))
.thenReturn(new Reservation());
Ec2QueryHandler handler = new Ec2QueryHandler(service, mock(EmulatorConfig.class),
mock(FlowLogService.class), mock(Ec2EbsEncryptionService.class),
@@ -71,7 +72,7 @@ class Ec2RunInstancesPublicIpParamTest {
anyInt(), anyInt(), nullable(String.class), anyList(), nullable(String.class),
nullable(String.class), anyList(), nullable(String.class), nullable(String.class),
associatePublicIp.capture(), nullable(String.class), anyInt(), nullable(String.class),
nullable(LaunchTemplateData.MetadataOptions.class));
nullable(LaunchTemplateData.MetadataOptions.class), nullable(String.class));
if (expected == null) {
assertNull(associatePublicIp.getValue(),
"an absent override must stay null so the subnet default decides");