feat(ec2): return spot price history for known instance types (#4698)

* feat(ec2): return spot price history for known instance types

* fix(ec2): address review feedback on spot price history pagination and platforms

* style(ec2): fix import ordering and inline qualified class names
This commit is contained in:
Simone Primarosa authored and GitHub committed 2026-09-29 22:05:16 -04:00
1 parent 433893d298
commit c0ec98b43e
7 files changed
+616 -15

No files matched your search

@@ -19,6 +19,7 @@ import org.jboss.logging.Logger;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
@@ -351,6 +352,17 @@ public class Ec2QueryHandler {
return value != null && !value.isBlank() ? value : p.getFirst(second);
}
private List<String> getListOrSingle(MultivaluedMap<String, String> p, String prefix) {
List<String> result = getList(p, prefix);
if (result.isEmpty()) {
String single = p.getFirst(prefix);
if (single != null && !single.isBlank()) {
result.add(single);
}
}
return result;
}
private int parseIntParam(MultivaluedMap<String, String> p, String name, int defaultValue) {
String val = p.getFirst(name);
if (val == null || val.isEmpty()) return defaultValue;
@@ -6070,14 +6082,62 @@ public class Ec2QueryHandler {
* clients such as Karpenter to distinguish an empty result from an unsupported action.</p>
*/
private Response handleDescribeSpotPriceHistory(MultivaluedMap<String, String> p, String region) {
List<String> instanceTypes = getListOrSingle(p, "InstanceType");
List<String> productDescriptions = getListOrSingle(p, "ProductDescription");
String availabilityZone = p.getFirst("AvailabilityZone");
if (availabilityZone == null) {
availabilityZone = p.getFirst("AvailabilityZone.1");
}
String availabilityZoneId = p.getFirst("AvailabilityZoneId");
if (availabilityZoneId == null) {
availabilityZoneId = p.getFirst("AvailabilityZoneId.1");
}
Instant startTime = instantOrNull(p, "StartTime");
Instant endTime = instantOrNull(p, "EndTime");
Map<String, List<String>> filters = getFilters(p);
String nextToken = p.getFirst("NextToken");
int maxResults = 0;
String maxResultsStr = p.getFirst("MaxResults");
if (maxResultsStr != null && !maxResultsStr.isEmpty()) {
try {
maxResults = Integer.parseInt(maxResultsStr);
if (maxResults < 1) {
throw new AwsException("InvalidParameterValue",
"The parameter MaxResults must be greater than or equal to 1", 400);
}
} catch (NumberFormatException e) {
throw new AwsException("InvalidParameterValue",
"The specified value for MaxResults is not valid.", 400);
}
}
service.validateSpotPriceHistory(productDescriptions, availabilityZone, availabilityZoneId, startTime, endTime, filters);
checkDryRun(p);
SpotPriceHistoryResult result = service.describeSpotPriceHistory(region,
instanceTypes, productDescriptions, availabilityZone, availabilityZoneId,
startTime, endTime, filters, maxResults, nextToken);
XmlBuilder xml = new XmlBuilder()
.start("DescribeSpotPriceHistoryResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.elem("nextToken", "")
.start("spotPriceHistorySet")
.end("spotPriceHistorySet")
.end("DescribeSpotPriceHistoryResponse");
.start("spotPriceHistorySet");
for (SpotPrice sp : result.spotPrices()) {
xml.start("item")
.elem("instanceType", sp.instanceType())
.elem("productDescription", sp.productDescription())
.elem("spotPrice", sp.spotPrice())
.elem("timestamp", ISO_FMT.format(sp.timestamp()))
.elem("availabilityZone", sp.availabilityZone());
if (sp.availabilityZoneId() != null) {
xml.elem("availabilityZoneId", sp.availabilityZoneId());
}
xml.end("item");
}
xml.end("spotPriceHistorySet");
xml.elem("nextToken", result.nextToken() != null ? result.nextToken() : "");
xml.end("DescribeSpotPriceHistoryResponse");
return xmlResponse(xml.build());
}
@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ec2.Ec2InstanceTypeCatalog.CatalogInstanceType;
import io.github.hectorvent.floci.services.ec2.model.Address;
import io.github.hectorvent.floci.services.ec2.model.BlockDeviceMapping;
import io.github.hectorvent.floci.services.ec2.model.CapacityReservation;
@@ -62,6 +63,8 @@ import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroupRule;
import io.github.hectorvent.floci.services.ec2.model.Snapshot;
import io.github.hectorvent.floci.services.ec2.model.SpotInstanceRequest;
import io.github.hectorvent.floci.services.ec2.model.SpotPrice;
import io.github.hectorvent.floci.services.ec2.model.SpotPriceHistoryResult;
import io.github.hectorvent.floci.services.ec2.model.Subnet;
import io.github.hectorvent.floci.services.ec2.model.Tag;
import io.github.hectorvent.floci.services.ec2.model.TransitGateway;
@@ -100,6 +103,7 @@ import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
@@ -199,6 +203,16 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
private static final Set<String> EGRESS_ONLY_INTERNET_GATEWAY_FILTERS = Set.of(
"attachment.state", "attachment.vpc-id",
"egress-only-internet-gateway-id", "tag-key", "tag-value");
private static final Set<String> SPOT_PRICE_HISTORY_FILTERS = Set.of(
"availability-zone", "availability-zone-id",
"instance-type", "product-description",
"spot-price", "timestamp");
private static final List<String> MODELLED_PRODUCT_DESCRIPTIONS = List.of(
"Linux/UNIX", "Linux/UNIX (Amazon VPC)",
"SUSE Linux", "SUSE Linux (Amazon VPC)",
"Red Hat Enterprise Linux", "Red Hat Enterprise Linux (Amazon VPC)",
"Windows", "Windows (Amazon VPC)");
private static final Set<String> VALID_PRODUCT_DESCRIPTIONS = new HashSet<>(MODELLED_PRODUCT_DESCRIPTIONS);
private final String defaultAccountId;
private final jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance;
@@ -9773,7 +9787,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
String json = new String(Base64.getDecoder().decode(token), StandardCharsets.UTF_8);
int start = json.indexOf("\"offset\":") + 9;
int end = json.indexOf('}', start);
return Integer.parseInt(json.substring(start, end));
int offset = Integer.parseInt(json.substring(start, end));
if (offset < 0) {
throw new AwsException("InvalidParameterValue",
"Invalid NextToken", 400);
}
return offset;
} catch (AwsException e) {
throw e;
} catch (Exception e) {
throw new AwsException("InvalidParameterValue",
"Invalid NextToken", 400);
@@ -9889,6 +9910,169 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
return result;
}
public void validateSpotPriceHistory(List<String> productDescriptions,
String availabilityZone,
String availabilityZoneId,
Instant startTime,
Instant endTime,
Map<String, List<String>> filters) {
if (filters != null && !filters.isEmpty()) {
requireSupportedFilters(filters, SPOT_PRICE_HISTORY_FILTERS);
}
if (productDescriptions != null) {
for (String desc : productDescriptions) {
if (!VALID_PRODUCT_DESCRIPTIONS.contains(desc)) {
throw new AwsException("InvalidParameterValue",
"The parameter ProductDescription is not valid", 400);
}
}
}
if (availabilityZone != null && availabilityZoneId != null) {
throw new AwsException("InvalidParameterCombination",
"The parameter AvailabilityZone cannot be used with the parameter AvailabilityZoneId", 400);
}
if (startTime != null && endTime != null && startTime.isAfter(endTime)) {
throw new AwsException("InvalidParameterValue",
"StartTime must be before EndTime", 400);
}
}
/**
* Synthesizes spot price history for known instance types across modeled availability zones.
* Prices are synthetic and derived deterministically from instance type vCPU and memory.
* They bear no relation to real AWS spot prices.
*/
public SpotPriceHistoryResult describeSpotPriceHistory(String region,
List<String> instanceTypes,
List<String> productDescriptions,
String availabilityZone,
String availabilityZoneId,
Instant startTime,
Instant endTime,
Map<String, List<String>> filters,
int maxResults,
String nextToken) {
ensureDefaultResources(region);
validateSpotPriceHistory(productDescriptions, availabilityZone, availabilityZoneId, startTime, endTime, filters);
Instant now = Instant.now();
if (startTime != null && startTime.isAfter(now)) {
return new SpotPriceHistoryResult(List.of(), null);
}
Instant effectiveTimestamp = startTime != null
? startTime
: (endTime != null ? endTime : now.truncatedTo(ChronoUnit.HOURS));
if (endTime != null && effectiveTimestamp.isAfter(endTime)) {
return new SpotPriceHistoryResult(List.of(), null);
}
List<Map<String, String>> zones = describeAvailabilityZones(region);
if (availabilityZone != null) {
zones = zones.stream()
.filter(z -> availabilityZone.equals(z.get("zoneName")))
.toList();
}
if (availabilityZoneId != null) {
zones = zones.stream()
.filter(z -> availabilityZoneId.equals(z.get("zoneId")))
.toList();
}
if (filters != null && filters.containsKey("availability-zone")) {
List<String> azFilter = filters.get("availability-zone");
zones = zones.stream()
.filter(z -> matchesValue(z.get("zoneName"), azFilter))
.toList();
}
if (filters != null && filters.containsKey("availability-zone-id")) {
List<String> azIdFilter = filters.get("availability-zone-id");
zones = zones.stream()
.filter(z -> matchesValue(z.get("zoneId"), azIdFilter))
.toList();
}
List<CatalogInstanceType> catalogTypes;
if (instanceTypes != null && !instanceTypes.isEmpty()) {
Set<String> distinctTypes = new LinkedHashSet<>(instanceTypes);
catalogTypes = distinctTypes.stream()
.map(instanceTypeCatalog::find)
.flatMap(Optional::stream)
.filter(t -> t.supportedUsageClasses.contains("spot"))
.toList();
} else {
catalogTypes = instanceTypeCatalog.instanceTypes().stream()
.filter(t -> t.supportedUsageClasses.contains("spot"))
.toList();
}
if (filters != null && filters.containsKey("instance-type")) {
List<String> itFilter = filters.get("instance-type");
catalogTypes = catalogTypes.stream()
.filter(t -> matchesValue(t.instanceType, itFilter))
.toList();
}
List<String> targetProductDescs = MODELLED_PRODUCT_DESCRIPTIONS;
if (productDescriptions != null && !productDescriptions.isEmpty()) {
Set<String> requested = new HashSet<>(productDescriptions);
targetProductDescs = targetProductDescs.stream()
.filter(requested::contains)
.toList();
}
if (filters != null && filters.containsKey("product-description")) {
List<String> pdFilter = filters.get("product-description");
targetProductDescs = targetProductDescs.stream()
.filter(pd -> matchesValue(pd, pdFilter))
.toList();
}
List<String> priceFilter = filters != null ? filters.get("spot-price") : null;
List<String> timestampFilter = filters != null ? filters.get("timestamp") : null;
String formattedTimestamp = ISO_FMT.format(effectiveTimestamp);
if (timestampFilter != null && !matchesValue(formattedTimestamp, timestampFilter)) {
return new SpotPriceHistoryResult(List.of(), null);
}
List<SpotPrice> allEntries = new ArrayList<>();
for (CatalogInstanceType type : catalogTypes) {
for (Map<String, String> zone : zones) {
String zoneName = zone.get("zoneName");
String zoneId = zone.get("zoneId");
int zoneOffset = Math.max(0, zoneName.charAt(zoneName.length() - 1) - 'a');
double multiplier = 1.0 + (zoneOffset * 0.03);
double priceVal = ((type.vcpu * 0.0016) + ((type.memoryMib / 1024.0) * 0.0012)) * multiplier;
String formattedPrice = String.format(Locale.ROOT, "%.6f", priceVal);
if (priceFilter != null && !matchesValue(formattedPrice, priceFilter)) {
continue;
}
for (String pd : targetProductDescs) {
allEntries.add(new SpotPrice(zoneName, zoneId, type.instanceType, pd, formattedPrice, effectiveTimestamp));
}
}
}
allEntries.sort(Comparator
.comparing(SpotPrice::instanceType)
.thenComparing(SpotPrice::availabilityZone)
.thenComparing(SpotPrice::productDescription));
if (maxResults > 0 || (nextToken != null && !nextToken.isEmpty())) {
int offset = decodeToken(nextToken);
int total = allEntries.size();
int fromIndex = Math.min(offset, total);
int pageSize = maxResults > 0 ? maxResults : 1000;
int toIndex = (int) Math.min((long) fromIndex + pageSize, total);
List<SpotPrice> paged = allEntries.subList(fromIndex, toIndex);
String newNextToken = toIndex < total ? encodeToken(toIndex) : null;
return new SpotPriceHistoryResult(paged, newNextToken);
}
return new SpotPriceHistoryResult(allEntries, null);
}
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
/**
@@ -0,0 +1,23 @@
package io.github.hectorvent.floci.services.ec2.model;
import java.time.Instant;
/**
* A spot price history entry.
*
* @param availabilityZone the availability zone name
* @param availabilityZoneId the availability zone id
* @param instanceType the instance type
* @param productDescription the product description
* @param spotPrice the synthetic spot price formatted to six decimal places
* @param timestamp the effective timestamp
* @see <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_SpotPrice.html">AWS EC2 SpotPrice</a>
*/
public record SpotPrice(
String availabilityZone,
String availabilityZoneId,
String instanceType,
String productDescription,
String spotPrice,
Instant timestamp
) {}
@@ -0,0 +1,15 @@
package io.github.hectorvent.floci.services.ec2.model;
import java.util.List;
/**
* Result of a paginated DescribeSpotPriceHistory call.
*
* @param spotPrices the spot prices for this page
* @param nextToken token for the next page, or null when the page is the last
* @see <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeSpotPriceHistory.html">AWS EC2 DescribeSpotPriceHistory</a>
*/
public record SpotPriceHistoryResult(
List<SpotPrice> spotPrices,
String nextToken
) {}