fix(emr): list an instance fleet's instances (#8183)

ListInstances listed only instance groups' instances, so a cluster made
of instance fleets listed none, though its core and task nodes run as
containers named by the private DNS names its instances would have.

- A fleet has an instance for each unit of its capacity, as its nodes
  do, its on-demand ones first, each of the first instance type in its
  InstanceTypeConfigs, which Floci now keeps, and with its
  InstanceFleetId.
- The primary fleet's instance is numbered first, i-00000000000000001
  at 10.0.0.1, as MasterPublicDnsName names it, and every other fleet's
  are at 10.<fleet>.0.<n>, the names its nodes run under, kept while
  another fleet resizes. One helper numbers groups and fleets for both.
- An ended fleet's instances stay listed as TERMINATED for 30 days, as
  an ended group's do, from its target capacities, which it can no
  longer change.
- InstanceGroupId, InstanceGroupTypes, InstanceFleetId and
  InstanceFleetType now narrow the listing, all given ones together;
  they were ignored.

A call lists at most 2,000 instances, building only that page, with a
Marker for the rest, so a fleet of any capacity costs one page, counted in longs, as a fleet's
two capacities add up past an int. A
cluster has instance groups or instance fleets, never both, as they
"cannot coexist in a cluster": RunJobFlow with both, AddInstanceGroups
on a cluster with fleets and AddInstanceFleet on one with groups are
refused, and so is a fleet without its required InstanceFleetType or an
InstanceTypeConfigs member without its required InstanceType.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-13 07:14:19 -04:00
1 parent babf8419f4
commit f5fd41a6ac
8 files changed
+467 -51

No files matched your search

@@ -40,6 +40,9 @@ import java.util.Map;
public class EmrHandler {
private static final Logger LOG = Logger.getLogger(EmrHandler.class);
// ListInstances "Provides information for all active Amazon EC2 instances and Amazon EC2 instances terminated in the
// last 30 days, up to a maximum of 2,000": that many to a call, the rest after its Marker.
static final int INSTANCES_PER_PAGE = 2000;
private final EmrService service;
private final ObjectMapper objectMapper;
@@ -295,7 +298,11 @@ public class EmrHandler {
}
private Response handleAddInstanceFleet(JsonNode request) {
EmrInstanceFleet fleet = parseInstanceFleet(request.path("InstanceFleet"));
List<String> violations = new ArrayList<>();
EmrInstanceFleet fleet = parseInstanceFleet(request.path("InstanceFleet"), "instanceFleet", violations);
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
String id = service.addInstanceFleet(text(request, "ClusterId"), fleet);
ObjectNode response = objectMapper.createObjectNode();
response.put("ClusterId", text(request, "ClusterId"));
@@ -323,27 +330,106 @@ public class EmrHandler {
|| (terminated && !withinTerminatedInstanceRetention(cluster.getEndDateTime(), Instant.now()))) {
return Response.ok(response).build();
}
// Listed in their groups' order, the first MASTER group's instances numbered first, so the primary node keeps
// its id and address, DescribeCluster's MasterPublicDnsName, while the other groups resize, as an instance
// does; any other group's follow, each after those before it.
EmrInstanceGroup primary = cluster.getInstanceGroups().stream().filter(EmrService::isMasterGroup)
.findFirst().orElse(null);
int next = primary == null ? 1 : 1 + listedInstanceCount(primary, terminated);
for (EmrInstanceGroup group : cluster.getInstanceGroups()) {
int count = listedInstanceCount(group, terminated);
int first = group == primary ? 1 : next;
int number = EmrService.groupNumber(cluster.getInstanceGroups(), group);
for (int i = 0; i < count; i++) {
arr.add(syntheticInstanceNode(cluster, group, first + i, EmrService.privateIpAddress(number, i + 1),
terminated));
String groupId = text(request, "InstanceGroupId");
List<String> groupTypes = stringList(request.path("InstanceGroupTypes"));
String fleetId = text(request, "InstanceFleetId");
String fleetType = text(request, "InstanceFleetType");
// Listed in their groups' or fleets' order, the primary node's group or fleet numbered first, so the primary
// node keeps its id and address, DescribeCluster's MasterPublicDnsName, while the others resize, as an
// instance does; any other's follow, each after those before it. Only the page asked for is built, so a
// group or fleet of any size costs a page. Counted in longs, as a fleet's two capacities add up past an int.
long skip = instancesMarker(text(request, "Marker"));
long start = skip;
int page = 0;
List<ListedInstances> listed = listedInstances(cluster, terminated);
ListedInstances primary = listed.stream().filter(set -> set.number() == 0).findFirst().orElse(null);
long next = primary == null ? 1 : 1 + primary.count();
for (ListedInstances set : listed) {
long first = set == primary ? 1 : next;
if (set != primary) {
next += set.count();
}
if (group != primary) {
next += count;
if (!set.matches(groupId, groupTypes, fleetId, fleetType)) {
continue;
}
if (skip >= set.count()) {
skip -= set.count();
continue;
}
for (long ordinal = skip + 1; ordinal <= set.count(); ordinal++) {
if (page == INSTANCES_PER_PAGE) {
response.put("Marker", String.valueOf(start + page));
return Response.ok(response).build();
}
arr.add(syntheticInstanceNode(cluster, set, first + ordinal - 1, ordinal, terminated));
page++;
}
skip = 0;
}
return Response.ok(response).build();
}
// How many of a listing's instances its Marker passes, the count the page before it ended at; none without one.
private static long instancesMarker(String marker) {
if (marker == null) {
return 0;
}
try {
long passed = Long.parseLong(marker);
if (passed >= 0) {
return passed;
}
} catch (NumberFormatException e) {
// Refused below, as any marker no page gave.
}
throw new AwsException("InvalidRequestException", "Invalid pagination token: " + marker, 400);
}
/**
* A cluster's instance groups' and fleets' instances, in the cluster's order. A fleet has one instance for each unit
* of its capacity, as its nodes do, its on-demand ones first, each of its first instance type.
*/
static List<ListedInstances> listedInstances(EmrCluster cluster, boolean terminated) {
List<ListedInstances> listed = new ArrayList<>();
List<EmrInstanceGroup> groups = cluster.getInstanceGroups();
for (EmrInstanceGroup group : groups) {
int count = listedInstanceCount(group, terminated);
listed.add(new ListedInstances(group.getId(), null, group.getInstanceGroupType(), group.getInstanceType(),
EmrService.groupNumber(groups, group), count, group.getMarket(), count));
}
List<EmrInstanceFleet> fleets = cluster.getInstanceFleets();
for (EmrInstanceFleet fleet : fleets) {
// An ended fleet has no capacity provisioned any more; its targets, which it can no longer change, say what
// it ran.
long onDemand = terminated ? fleet.getTargetOnDemandCapacity() : fleet.getProvisionedOnDemandCapacity();
long spot = terminated ? fleet.getTargetSpotCapacity() : fleet.getProvisionedSpotCapacity();
listed.add(new ListedInstances(null, fleet.getId(), fleet.getInstanceFleetType(),
fleet.getInstanceTypes().isEmpty() ? null : fleet.getInstanceTypes().getFirst(),
EmrService.fleetNumber(fleets, fleet), onDemand + spot, "ON_DEMAND", onDemand));
}
return listed;
}
/**
* The instances ListInstances lists for one instance group or fleet: {@code count} of them, with addresses numbered
* {@code number}, those after the first {@code spotAfter} on the spot market and the others on {@code market}.
*/
record ListedInstances(String groupId, String fleetId, String type, String instanceType, int number, long count,
String market, long spotAfter) {
String marketOf(long ordinal) {
return ordinal <= spotAfter ? market : "SPOT";
}
/** Whether ListInstances' filters keep them: the group ones keep groups' instances, the fleet ones fleets'. */
boolean matches(String instanceGroupId, List<String> groupTypes, String instanceFleetId, String fleetType) {
return (instanceGroupId == null || instanceGroupId.equals(groupId))
&& (groupTypes.isEmpty() || (groupId != null && groupTypes.contains(type)))
&& (instanceFleetId == null || instanceFleetId.equals(fleetId))
&& (fleetType == null || (fleetId != null && fleetType.equals(type)));
}
}
static boolean withinTerminatedInstanceRetention(Instant endedAt, Instant now) {
return endedAt != null && !endedAt.isBefore(now.minus(30, ChronoUnit.DAYS));
}
@@ -754,19 +840,27 @@ public class EmrHandler {
return node;
}
private ObjectNode syntheticInstanceNode(EmrCluster cluster, EmrInstanceGroup group, int index, String privateIp,
private ObjectNode syntheticInstanceNode(EmrCluster cluster, ListedInstances set, long index, long ordinal,
boolean terminated) {
String privateIp = EmrService.privateIpAddress(set.number(), ordinal);
ObjectNode node = objectMapper.createObjectNode();
node.put("Id", "ci-" + index + cluster.getId());
node.put("Ec2InstanceId", EmrService.ec2InstanceId(index));
node.put("PublicDnsName", AwsEndpoints.ec2PublicDns("203.0.113." + index, cluster.getRegion()));
node.put("PrivateDnsName", AwsRegions.ec2PrivateIpDnsName(privateIp, cluster.getRegion()));
node.put("PrivateIpAddress", privateIp);
node.put("InstanceGroupId", group.getId());
if (group.getMarket() != null) {
node.put("Market", group.getMarket());
if (set.groupId() != null) {
node.put("InstanceGroupId", set.groupId());
}
if (set.fleetId() != null) {
node.put("InstanceFleetId", set.fleetId());
}
if (set.marketOf(ordinal) != null) {
node.put("Market", set.marketOf(ordinal));
}
if (set.instanceType() != null) {
node.put("InstanceType", set.instanceType());
}
node.put("InstanceType", group.getInstanceType());
node.putObject("Status").put("State", terminated ? "TERMINATED" : "RUNNING");
return node;
}
@@ -840,16 +934,41 @@ public class EmrHandler {
if (!fleetsNode.isArray()) {
return fleets;
}
List<String> violations = new ArrayList<>();
int position = 1;
for (JsonNode f : fleetsNode) {
fleets.add(parseInstanceFleet(f));
fleets.add(parseInstanceFleet(f, "instances.instanceFleets." + position++ + ".member", violations));
}
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
return fleets;
}
private EmrInstanceFleet parseInstanceFleet(JsonNode f) {
/**
* An InstanceFleetConfig at {@code path} in its request, as the framework names a member's place; one without its
* required InstanceFleetType, or with an InstanceTypeConfigs member without its required InstanceType, adds to
* {@code violations}, as the framework refuses such a request.
*/
private EmrInstanceFleet parseInstanceFleet(JsonNode f, String path, List<String> violations) {
EmrInstanceFleet fleet = new EmrInstanceFleet();
fleet.setName(f.path("Name").asText(null));
fleet.setInstanceFleetType(f.path("InstanceFleetType").asText(null));
if (fleet.getInstanceFleetType() == null) {
violations.add(SmithyValidationErrors.notNull(path + ".instanceFleetType"));
}
List<String> instanceTypes = new ArrayList<>();
int position = 1;
for (JsonNode config : f.path("InstanceTypeConfigs")) {
String instanceType = config.path("InstanceType").asText(null);
if (instanceType == null) {
violations.add(SmithyValidationErrors.notNull(
path + ".instanceTypeConfigs." + position + ".member.instanceType"));
}
instanceTypes.add(instanceType);
position++;
}
fleet.setInstanceTypes(instanceTypes);
fleet.setTargetOnDemandCapacity(f.path("TargetOnDemandCapacity").asInt(0));
fleet.setTargetSpotCapacity(f.path("TargetSpotCapacity").asInt(0));
return fleet;
@@ -62,6 +62,7 @@ import java.util.function.BiFunction;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
/**
@@ -369,6 +370,12 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
if (cluster.getName() == null) {
throw SmithyValidationErrors.validationException(SmithyValidationErrors.notNull("name"));
}
// "The RunJobFlow request can contain InstanceFleets parameters or InstanceGroups parameters, but not
// both", as "instance fleets and instance groups cannot coexist in a cluster".
if (!cluster.getInstanceGroups().isEmpty() && !cluster.getInstanceFleets().isEmpty()) {
throw new AwsException("ValidationException", "The RunJobFlow request can contain InstanceFleets"
+ " parameters or InstanceGroups parameters, but not both.", 400);
}
String id = "j-" + randomId(13);
cluster.setId(id);
cluster.setRegion(region);
@@ -569,6 +576,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
return call(() -> {
EmrCluster cluster = requireCluster(clusterId);
rejectShutDownCluster(cluster, EmrService::jobFlowShutDownValidation);
if (!cluster.getInstanceFleets().isEmpty()) {
throw new AwsException("ValidationException", fleetsAndGroupsApart(clusterId, "instance fleets"), 400);
}
List<String> ids = new ArrayList<>();
for (EmrInstanceGroup group : groups) {
group.setId("ig-" + randomId(13));
@@ -668,6 +678,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
return call(() -> {
EmrCluster cluster = requireCluster(clusterId);
rejectShutDownCluster(cluster, EmrService::jobFlowShutDown);
if (!cluster.getInstanceGroups().isEmpty()) {
throw invalid(fleetsAndGroupsApart(clusterId, "instance groups"));
}
fleet.setId("if-" + randomId(13));
fleet.setProvisionedOnDemandCapacity(fleet.getTargetOnDemandCapacity());
fleet.setProvisionedSpotCapacity(fleet.getTargetSpotCapacity());
@@ -1134,6 +1147,14 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
return new AwsException("InvalidRequestException", message, 400);
}
// Why a cluster gets no instance group or fleet of the other kind: "The configuration option you choose applies to
// all nodes, it applies for the lifetime of the cluster, and instance fleets and instance groups cannot coexist in
// a cluster."
private static String fleetsAndGroupsApart(String clusterId, String uses) {
return "Cluster " + clusterId + " uses " + uses + ", and instance fleets and instance groups cannot coexist"
+ " in a cluster.";
}
/**
* ModifyInstanceFleet's answer for a job flow that is shutting down or ended, ErrorCode member included.
* AddInstanceFleet and ModifyCluster give it too, as their models also declare InvalidRequestException.
@@ -1746,16 +1767,13 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
isCore, isCore ? core : task);
}
}
EmrInstanceFleet primaryFleet = cluster.getInstanceFleets().stream()
.filter(fleet -> "MASTER".equals(fleet.getInstanceFleetType())).findFirst().orElse(null);
int number = 1;
for (EmrInstanceFleet fleet : cluster.getInstanceFleets()) {
if (fleet == primaryFleet) {
continue;
int number = fleetNumber(cluster.getInstanceFleets(), fleet);
if (number > 0) {
boolean isCore = "CORE".equals(fleet.getInstanceFleetType());
int count = fleet.getTargetOnDemandCapacity() + fleet.getTargetSpotCapacity();
addNodes(cluster, number, isCore ? Math.max(count, floor) : count, isCore, isCore ? core : task);
}
boolean isCore = "CORE".equals(fleet.getInstanceFleetType());
int count = fleet.getTargetOnDemandCapacity() + fleet.getTargetSpotCapacity();
addNodes(cluster, number++, isCore ? Math.max(count, floor) : count, isCore, isCore ? core : task);
}
List<ClusterStorage.Node> nodes = new ArrayList<>(core);
nodes.addAll(task);
@@ -1934,7 +1952,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
}
/** The EC2 instance id ListInstances gives a cluster's instance {@code index}, counted from 1. */
static String ec2InstanceId(int index) {
static String ec2InstanceId(long index) {
return "i-" + String.format("%017d", index);
}
@@ -1942,7 +1960,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
* The private IPv4 address of the instance {@code ordinal}, counted from 1, of a cluster's instance group numbered
* {@code group}: an instance keeps it while its cluster's other groups resize, as an EC2 instance does.
*/
static String privateIpAddress(int group, int ordinal) {
static String privateIpAddress(int group, long ordinal) {
return "10." + group + "." + (ordinal - 1) / 254 + "." + ((ordinal - 1) % 254 + 1);
}
@@ -1951,23 +1969,32 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
* group, and from 1 for the others in the order the cluster has them, which only adds to the end.
*/
static int groupNumber(List<EmrInstanceGroup> groups, EmrInstanceGroup group) {
EmrInstanceGroup primary = groups.stream().filter(EmrService::isMasterGroup).findFirst().orElse(null);
if (group == primary) {
return numberAmong(groups, group, EmrService::isMasterGroup);
}
/** A cluster's instance fleet's number in its instances' addresses, as {@link #groupNumber} gives a group's. */
static int fleetNumber(List<EmrInstanceFleet> fleets, EmrInstanceFleet fleet) {
return numberAmong(fleets, fleet, EmrService::isMasterFleet);
}
private static <T> int numberAmong(List<T> all, T one, Predicate<T> isMaster) {
T primary = all.stream().filter(isMaster).findFirst().orElse(null);
if (one == primary) {
return 0;
}
int number = 1;
for (EmrInstanceGroup other : groups) {
if (other == group) {
for (T other : all) {
if (other == one) {
return number;
}
if (other != primary) {
number++;
}
}
throw new IllegalArgumentException("The instance group is not one of the cluster's");
throw new IllegalArgumentException("The instance group or fleet is not one of the cluster's");
}
// The primary instance's: the first of the MASTER group, which ListInstances numbers before the others.
// The primary instance's: the first of the MASTER group or fleet, which ListInstances numbers before the others.
static String masterInstanceId(EmrCluster cluster) {
return ec2InstanceId(1);
}
@@ -1982,6 +2009,10 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
return "MASTER".equals(group.getInstanceGroupType());
}
static boolean isMasterFleet(EmrInstanceFleet fleet) {
return "MASTER".equals(fleet.getInstanceFleetType());
}
/** What a step's thread asks the service while its driver goes: a step has no timeout to report. */
private final class StepProgress implements SparkJobRunner.Progress {
@@ -2,6 +2,9 @@ package io.floci.aws.services.emr.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
import java.util.List;
/** An EMR instance fleet (MASTER | CORE | TASK). */
@RegisterForReflection
public class EmrInstanceFleet {
@@ -9,6 +12,7 @@ public class EmrInstanceFleet {
private String id;
private String name;
private String instanceFleetType;
private List<String> instanceTypes = new ArrayList<>();
private int targetOnDemandCapacity;
private int targetSpotCapacity;
private int provisionedOnDemandCapacity;
@@ -26,6 +30,10 @@ public class EmrInstanceFleet {
public String getInstanceFleetType() { return instanceFleetType; }
public void setInstanceFleetType(String instanceFleetType) { this.instanceFleetType = instanceFleetType; }
/** The instance types of its InstanceTypeConfigs, in their order. */
public List<String> getInstanceTypes() { return instanceTypes; }
public void setInstanceTypes(List<String> instanceTypes) { this.instanceTypes = instanceTypes; }
public int getTargetOnDemandCapacity() { return targetOnDemandCapacity; }
public void setTargetOnDemandCapacity(int targetOnDemandCapacity) {
this.targetOnDemandCapacity = targetOnDemandCapacity;