fix(emr): keep instance fleets' launch and resize specifications, and modify their configs (#9168)

An instance fleet dropped the LaunchSpecifications, ResizeSpecifications
and Context that RunJobFlow and AddInstanceFleet gave it, and
ModifyInstanceFleet changed its target capacities alone, ignoring the
ResizeSpecifications, InstanceTypeConfigs and Context it took.

- A fleet keeps its LaunchSpecifications, ResizeSpecifications and
  Context, and ListInstanceFleets gives them back.
- ModifyInstanceFleet changes the ResizeSpecifications, InstanceTypeConfigs
  and Context it gives. The configs replace the fleet's own, as the
  Management Guide warns that "Not including fields can result in
  overwriting specifications you declared at launch", and must name
  every instance type the fleet has, as "You must include all instance
  types that are part of your instance fleet in the modify request". A
  request that leaves one out is refused with InvalidRequestException.
  Its configs are checked as AddInstanceFleet checks them, and on both
  calls specifications that are not an object, or a Context that is not
  a string, are refused with SerializationException.
- AWS::EMR::Cluster no longer warns that a fleet's launch and resize
  specifications are not stored, and AWS::EMR::InstanceFleetConfig now
  applies a change to InstanceTypeConfigs or ResizeSpecifications in
  place rather than warning. A rollback puts them back, but not an
  instance type the update added, which every later request must
  include, nor resize specifications where the fleet had none, which no
  request can clear. The update is checked as ModifyInstanceFleet checks
  its request, before anything changes, and dropped configs or resize
  specifications are kept.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-21 20:29:04 -04:00
1 parent 26eb1e9264
commit cff222a6f1
9 files changed
+464 -49

No files matched your search

@@ -1,5 +1,6 @@
package io.floci.aws.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
@@ -8,6 +9,7 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.emr.EmrHandler;
import io.floci.aws.services.emr.EmrService;
import io.floci.aws.services.emr.EmrService.InstanceFleetModification;
import io.floci.aws.services.emr.EmrService.InstanceGroupModification;
import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrInstanceFleet;
@@ -109,8 +111,6 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner {
/** The members of {@code Instances} Floci's RunJobFlow keeps nothing of, accepted with a warning. */
private static final List<String> INSTANCES_NOT_STORED = List.of("Ec2SubnetIds", "AdditionalMasterSecurityGroups",
"AdditionalSlaveSecurityGroups", "HadoopVersion");
/** The members of an instance fleet Floci's RunJobFlow keeps nothing of. */
private static final List<String> FLEET_NOT_STORED = List.of("LaunchSpecifications", "ResizeSpecifications");
private static final String GROUPS = "groups";
private static final String FLEETS = "fleets";
private static final Duration READY_TIMEOUT = Duration.ofMinutes(15);
@@ -298,7 +298,7 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner {
}
}
/** Warns of each property, or member of {@code Instances} or its fleets, RunJobFlow keeps nothing of. */
/** Warns of each property, or member of {@code Instances}, RunJobFlow keeps nothing of. */
private static void warnNotStored(String logicalId, JsonNode template) {
List<String> ignored = new ArrayList<>();
for (String name : CLUSTER_NOT_STORED) {
@@ -312,14 +312,6 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner {
ignored.add("Instances." + name);
}
}
List<JsonNode> fleets = new ArrayList<>(List.of(instances.path("MasterInstanceFleet"),
instances.path("CoreInstanceFleet")));
instances.path("TaskInstanceFleets").forEach(fleets::add);
for (String name : FLEET_NOT_STORED) {
if (fleets.stream().anyMatch(fleet -> fleet.has(name))) {
ignored.add("an instance fleet's " + name);
}
}
if (!ignored.isEmpty()) {
LOG.warnv("EMR cluster {0}: {1} accepted and not stored", logicalId, String.join(", ", ignored));
}
@@ -380,11 +372,9 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner {
if (copy.has("Configurations")) {
copy.set("Configurations", configurations(copy.get("Configurations")));
}
copy.path("InstanceTypeConfigs").forEach(type -> {
if (type instanceof ObjectNode typeConfig && typeConfig.has("Configurations")) {
typeConfig.set("Configurations", configurations(typeConfig.get("Configurations")));
}
});
if (copy.has("InstanceTypeConfigs")) {
copy.set("InstanceTypeConfigs", apiInstanceTypeConfigs(copy.get("InstanceTypeConfigs")));
}
into.add(copy);
}
@@ -807,10 +797,11 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner {
}
/**
* An instance fleet is added through AddInstanceFleet; its target capacities change in place through
* ModifyInstanceFleet, and any create-only change adds a new fleet. Floci's ModifyInstanceFleet changes the
* capacities alone, so a change to {@code InstanceTypeConfigs} or {@code ResizeSpecifications} is accepted with a
* warning and not applied. A rollback puts back the capacities it had changed.
* An instance fleet is added through AddInstanceFleet; its target capacities, {@code InstanceTypeConfigs} and
* {@code ResizeSpecifications} change in place through ModifyInstanceFleet, and any create-only change adds a new
* fleet. A rollback puts back what the update had changed, but not what ModifyInstanceFleet cannot take away: an
* instance type the update added, which every later request must include, and resize specifications where the
* fleet had none. Dropped resize specifications are kept for the same reason.
*/
private void provisionInstanceFleet(StackResource r, JsonNode props, ProvisionContext ctx, boolean stub) {
JsonNode template = new CfnPropertyTypes.HandlerReader(ctx.engine()).read(INSTANCE_FLEET, props);
@@ -824,28 +815,39 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner {
EmrInstanceFleet live = emrService.listInstanceFleets(clusterId).stream()
.filter(fleet -> id.equals(fleet.getId())).findFirst()
.orElseThrow(() -> notFound(INSTANCE_FLEET, id));
ArrayNode configs = changed(changes, "InstanceTypeConfigs") && template.has("InstanceTypeConfigs")
? apiInstanceTypeConfigs(template.get("InstanceTypeConfigs")) : null;
JsonNode resize = changed(changes, "ResizeSpecifications") ? template.get("ResizeSpecifications") : null;
for (String name : List.of("InstanceTypeConfigs", "ResizeSpecifications")) {
PropertyChanges.Kind kind = changes.kindOf(name);
if (kind != null && kind != PropertyChanges.Kind.UNCHANGED) {
LOG.warnv("EMR instance fleet {0}: {1} is not applied, as ModifyInstanceFleet changes the "
+ "target capacities alone", id, name);
if (changed(changes, name) && !template.has(name)) {
LOG.warnv("EMR instance fleet {0}: the dropped {1} are kept, as ModifyInstanceFleet cannot take "
+ "them away", id, name);
}
}
int onDemand = template.path("TargetOnDemandCapacity").asInt(0);
int spot = template.path("TargetSpotCapacity").asInt(0);
// Checked before anything changes, as ModifyInstanceFleet checks its request.
InstanceFleetModification modification = fleetModification(onDemand, spot, configs, resize);
ObjectNode snapshot = MAPPER.createObjectNode();
snapshot.put("clusterId", clusterId);
snapshot.put("fleetId", id);
snapshot.put("region", ctx.region());
snapshot.put("onDemand", live.getTargetOnDemandCapacity());
snapshot.put("spot", live.getTargetSpotCapacity());
if (configs != null) {
snapshot.set("configs", configsOf(live));
}
if (resize != null && live.getResizeSpecifications() != null) {
snapshot.set("resize", rawJson(live.getResizeSpecifications(), null));
}
publishCapacity(r, id, clusterId);
r.getAttributes().put("InstanceFleetId", id);
r.getAttributes().put(CAPACITY_SNAPSHOT_ATTR, snapshot.toString());
AtomicBoolean changed = new AtomicBoolean();
CfnRollback.guarded(r, ctx, false, () -> { }, () -> restoreCapacity(snapshot, changed.get(), false), () -> {
if (onDemand != live.getTargetOnDemandCapacity() || spot != live.getTargetSpotCapacity()) {
emrService.modifyInstanceFleet(clusterId, id, onDemand, spot);
if (onDemand != live.getTargetOnDemandCapacity() || spot != live.getTargetSpotCapacity()
|| configs != null || resize != null) {
emrService.modifyInstanceFleet(clusterId, id, modification);
changed.set(true);
}
});
@@ -857,16 +859,87 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner {
fleet.set(name, template.get(name).deepCopy());
}
}
fleet.path("InstanceTypeConfigs").forEach(type -> {
if (type instanceof ObjectNode typeConfig && typeConfig.has("Configurations")) {
typeConfig.set("Configurations", configurations(typeConfig.get("Configurations")));
}
});
if (fleet.has("InstanceTypeConfigs")) {
fleet.set("InstanceTypeConfigs", apiInstanceTypeConfigs(fleet.get("InstanceTypeConfigs")));
}
String id = emrService.addInstanceFleet(clusterId, emrHandler.instanceFleetFrom(fleet));
publishCapacity(r, id, clusterId);
r.getAttributes().put("InstanceFleetId", id);
}
private static boolean changed(PropertyChanges changes, String name) {
PropertyChanges.Kind kind = changes.kindOf(name);
return kind != null && kind != PropertyChanges.Kind.UNCHANGED;
}
/** A template's InstanceTypeConfigs as the API takes them: their ConfigurationProperties as Properties. */
private static ArrayNode apiInstanceTypeConfigs(JsonNode templateConfigs) {
ArrayNode configs = MAPPER.createArrayNode();
for (JsonNode type : templateConfigs) {
JsonNode config = type.deepCopy();
if (config instanceof ObjectNode typeConfig && typeConfig.has("Configurations")) {
typeConfig.set("Configurations", configurations(typeConfig.get("Configurations")));
}
configs.add(config);
}
return configs;
}
/** The ModifyInstanceFleet change, read and checked as ModifyInstanceFleet reads its request. */
private static InstanceFleetModification fleetModification(int onDemand, int spot, ArrayNode configs,
JsonNode resize) {
ObjectNode request = MAPPER.createObjectNode();
request.put("TargetOnDemandCapacity", onDemand);
request.put("TargetSpotCapacity", spot);
if (configs != null) {
request.set("InstanceTypeConfigs", configs);
}
if (resize != null) {
request.set("ResizeSpecifications", resize);
}
return EmrHandler.instanceFleetModificationFrom(request);
}
/**
* A fleet's InstanceTypeConfigs as stored, or, for one stored with its instance types alone, a config naming each,
* so a rollback puts back what the fleet had rather than keeping the update's.
*/
private static ArrayNode configsOf(EmrInstanceFleet fleet) {
if (fleet.getInstanceTypeConfigs() != null) {
return (ArrayNode) rawJson(fleet.getInstanceTypeConfigs(), null);
}
ArrayNode configs = MAPPER.createArrayNode();
fleet.getInstanceTypes().forEach(type -> configs.addObject().put("InstanceType", type));
return configs;
}
/** Adds to {@code configs} the live fleet's configs of the types they lack: ModifyInstanceFleet needs them all. */
private void keepAddedInstanceTypes(String clusterId, String fleetId, ArrayNode configs) {
List<String> named = new ArrayList<>();
configs.forEach(config -> named.add(config.path("InstanceType").asText()));
for (EmrInstanceFleet fleet : emrService.listInstanceFleets(clusterId)) {
if (fleetId.equals(fleet.getId())) {
List<String> added = EmrService.instanceTypesLeftOut(fleet.getInstanceTypes(), named);
for (JsonNode config : configsOf(fleet)) {
if (added.contains(config.path("InstanceType").asText())) {
configs.add(config);
}
}
}
}
}
private static JsonNode rawJson(String text, JsonNode none) {
if (text == null) {
return none;
}
try {
return MAPPER.readTree(text);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Unreadable stored EMR JSON", e);
}
}
private void applyGroupPolicy(String clusterId, String groupId, JsonNode policy) {
if (policy == null) {
emrService.removeAutoScalingPolicy(clusterId, groupId);
@@ -880,8 +953,13 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner {
String clusterId = snapshot.path("clusterId").asText();
if (snapshot.has("fleetId")) {
if (first) {
emrService.modifyInstanceFleet(clusterId, snapshot.path("fleetId").asText(),
snapshot.path("onDemand").asInt(), snapshot.path("spot").asInt());
String fleetId = snapshot.path("fleetId").asText();
ArrayNode configs = snapshot.get("configs") instanceof ArrayNode prior ? prior.deepCopy() : null;
if (configs != null) {
keepAddedInstanceTypes(clusterId, fleetId, configs);
}
emrService.modifyInstanceFleet(clusterId, fleetId, fleetModification(snapshot.path("onDemand").asInt(),
snapshot.path("spot").asInt(), configs, snapshot.get("resize")));
}
return;
}
@@ -1364,12 +1364,38 @@ public class EmrHandler {
private Response handleModifyInstanceFleet(JsonNode request) {
JsonNode fleet = request.path("InstanceFleet");
service.modifyInstanceFleet(text(request, "ClusterId"), fleet.path("InstanceFleetId").asText(null),
instanceFleetModificationFrom(fleet));
return Response.ok(objectMapper.createObjectNode()).build();
}
/**
* The change a ModifyInstanceFleet request's {@code InstanceFleet} describes, read and checked as
* ModifyInstanceFleet reads it, for this handler and for CloudFormation's {@code AWS::EMR::InstanceFleetConfig}:
* its configs' required InstanceType and their volume limit, as AddInstanceFleet checks them, and its members'
* JSON types.
*/
public static EmrService.InstanceFleetModification instanceFleetModificationFrom(JsonNode fleet) {
JsonNode onDemand = fleet.path("TargetOnDemandCapacity");
JsonNode spot = fleet.path("TargetSpotCapacity");
service.modifyInstanceFleet(text(request, "ClusterId"), fleet.path("InstanceFleetId").asText(null),
JsonNode configs = fleet.path("InstanceTypeConfigs");
List<String> instanceTypes = null;
if (!configs.isMissingNode() && !configs.isNull()) {
if (!configs.isArray()) {
throw malformed("InstanceTypeConfigs must be a list");
}
List<String> violations = new ArrayList<>();
instanceTypes = instanceTypes(configs, "instanceFleet", violations);
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
requireFleetEbsVolumeLimit(fleet);
}
return new EmrService.InstanceFleetModification(
onDemand.isMissingNode() || onDemand.isNull() ? null : onDemand.asInt(),
spot.isMissingNode() || spot.isNull() ? null : spot.asInt());
return Response.ok(objectMapper.createObjectNode()).build();
spot.isMissingNode() || spot.isNull() ? null : spot.asInt(),
object(fleet, "ResizeSpecifications"), instanceTypes == null ? null : configs.toString(),
instanceTypes, string(fleet, "Context"));
}
/** Each BootstrapActionConfig given to RunJobFlow, as the Command shape: Name, ScriptPath and Args. */
@@ -1681,6 +1707,15 @@ public class EmrHandler {
node.put("ProvisionedSpotCapacity", f.getProvisionedSpotCapacity());
node.set("InstanceTypeSpecifications", instanceTypeSpecifications(f));
node.putObject("Status").put("State", f.getState());
if (f.getLaunchSpecifications() != null) {
setRawJson(node, "LaunchSpecifications", f.getLaunchSpecifications());
}
if (f.getResizeSpecifications() != null) {
setRawJson(node, "ResizeSpecifications", f.getResizeSpecifications());
}
if (f.getContext() != null) {
node.put("Context", f.getContext());
}
return node;
}
@@ -1968,9 +2003,24 @@ public class EmrHandler {
if (fleet.getInstanceFleetType() == null) {
violations.add(SmithyValidationErrors.notNull(path + ".instanceFleetType"));
}
fleet.setInstanceTypes(instanceTypes(f.path("InstanceTypeConfigs"), path, violations));
fleet.setInstanceTypeConfigs(rawArray(f.path("InstanceTypeConfigs")));
fleet.setTargetOnDemandCapacity(f.path("TargetOnDemandCapacity").asInt(0));
fleet.setTargetSpotCapacity(f.path("TargetSpotCapacity").asInt(0));
fleet.setLaunchSpecifications(object(f, "LaunchSpecifications"));
fleet.setResizeSpecifications(object(f, "ResizeSpecifications"));
fleet.setContext(string(f, "Context"));
return fleet;
}
/**
* The instance types of a fleet's InstanceTypeConfigs at {@code path}; a config without its required InstanceType
* adds to {@code violations}, as the framework refuses such a request.
*/
private static List<String> instanceTypes(JsonNode configs, String path, List<String> violations) {
List<String> instanceTypes = new ArrayList<>();
int position = 1;
for (JsonNode config : f.path("InstanceTypeConfigs")) {
for (JsonNode config : configs) {
String instanceType = config.path("InstanceType").asText(null);
if (instanceType == null) {
violations.add(SmithyValidationErrors.notNull(
@@ -1979,11 +2029,22 @@ public class EmrHandler {
instanceTypes.add(instanceType);
position++;
}
fleet.setInstanceTypes(instanceTypes);
fleet.setInstanceTypeConfigs(rawArray(f.path("InstanceTypeConfigs")));
fleet.setTargetOnDemandCapacity(f.path("TargetOnDemandCapacity").asInt(0));
fleet.setTargetSpotCapacity(f.path("TargetSpotCapacity").asInt(0));
return fleet;
return instanceTypes;
}
/**
* A member an object where the model has one, as raw JSON; another JSON type is refused with
* SerializationException, as {@link #string} refuses one.
*/
private static String object(JsonNode request, String member) {
JsonNode value = request.path(member);
if (value.isMissingNode() || value.isNull()) {
return null;
}
if (!value.isObject()) {
throw malformed(member + " must be an object");
}
return value.toString();
}
// The cluster's EC2 attributes, its availability zone among them: the one Placement names, the first of its
@@ -1803,9 +1803,40 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
});
}
/**
* What a ModifyInstanceFleet request changes, each member null when it leaves it as it is: the target capacities,
* the ResizeSpecifications, the InstanceTypeConfigs (raw JSON) with their instance types, and the Context.
*/
public record InstanceFleetModification(Integer targetOnDemandCapacity, Integer targetSpotCapacity,
String resizeSpecifications, String instanceTypeConfigs,
List<String> instanceTypes, String context) {
}
/**
* The instance types of {@code types} that {@code named} leaves out, each once, in their order: those a
* ModifyInstanceFleet request must still name, or that it adds to a fleet's own.
*/
public static List<String> instanceTypesLeftOut(List<String> types, List<String> named) {
return types.stream().filter(type -> !named.contains(type)).distinct().toList();
}
/** Resizes an instance fleet; a null target leaves that capacity as it is. */
public void modifyInstanceFleet(String clusterId, String instanceFleetId,
Integer targetOnDemandCapacity, Integer targetSpotCapacity) {
modifyInstanceFleet(clusterId, instanceFleetId, new InstanceFleetModification(targetOnDemandCapacity,
targetSpotCapacity, null, null, null, null));
}
/**
* Changes a fleet's target capacities, and the ResizeSpecifications, InstanceTypeConfigs and Context the request
* gives, which ListInstanceFleets gives back. The configs replace the fleet's own, as the Management Guide's
* "Reconfiguring instance fleets" has it: "Not including fields can result in overwriting specifications you
* declared at launch". They must name every instance type the fleet has: "You must include all instance types
* that are part of your instance fleet in the modify request". A type they add joins the fleet's after its own.
*/
public void modifyInstanceFleet(String clusterId, String instanceFleetId, InstanceFleetModification modification) {
Integer targetOnDemandCapacity = modification.targetOnDemandCapacity();
Integer targetSpotCapacity = modification.targetSpotCapacity();
run(() -> {
EmrCluster cluster = requireCluster(clusterId);
if (instanceFleetId == null) {
@@ -1837,10 +1868,30 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
&& (onDemand != fleet.getTargetOnDemandCapacity() || spot != fleet.getTargetSpotCapacity())) {
throw invalid("The target capacity of a master instance fleet cannot be modified.");
}
List<String> instanceTypes = null;
if (modification.instanceTypes() != null) {
List<String> missing = instanceTypesLeftOut(fleet.getInstanceTypes(), modification.instanceTypes());
if (!missing.isEmpty()) {
throw invalid("The instance type configs must include every instance type of instance fleet "
+ instanceFleetId + "; missing " + String.join(", ", missing) + ".");
}
instanceTypes = new ArrayList<>(fleet.getInstanceTypes());
instanceTypes.addAll(instanceTypesLeftOut(modification.instanceTypes(), fleet.getInstanceTypes()));
}
fleet.setTargetOnDemandCapacity(onDemand);
fleet.setTargetSpotCapacity(spot);
fleet.setProvisionedOnDemandCapacity(onDemand);
fleet.setProvisionedSpotCapacity(spot);
if (modification.resizeSpecifications() != null) {
fleet.setResizeSpecifications(modification.resizeSpecifications());
}
if (instanceTypes != null) {
fleet.setInstanceTypeConfigs(modification.instanceTypeConfigs());
fleet.setInstanceTypes(instanceTypes);
}
if (modification.context() != null) {
fleet.setContext(modification.context());
}
clusterStore.put(clusterId, cluster);
resizeNodes(cluster);
});
@@ -19,6 +19,11 @@ public class EmrInstanceFleet {
private int provisionedOnDemandCapacity;
private int provisionedSpotCapacity;
private String state;
/** The LaunchSpecifications as given, raw JSON; null when none. */
private String launchSpecifications;
/** The ResizeSpecifications as given, or as ModifyInstanceFleet last set them, raw JSON; null when none. */
private String resizeSpecifications;
private String context;
public EmrInstanceFleet() {}
@@ -59,4 +64,17 @@ public class EmrInstanceFleet {
public String getState() { return state; }
public void setState(String state) { this.state = state; }
public String getLaunchSpecifications() { return launchSpecifications; }
public void setLaunchSpecifications(String launchSpecifications) {
this.launchSpecifications = launchSpecifications;
}
public String getResizeSpecifications() { return resizeSpecifications; }
public void setResizeSpecifications(String resizeSpecifications) {
this.resizeSpecifications = resizeSpecifications;
}
public String getContext() { return context; }
public void setContext(String context) { this.context = context; }
}