fix(emr): refuse changes to a cluster that is shutting down or ended (#8037)

ModifyCluster, the four Set* setters, and Put and Remove of a cluster's
managed scaling, auto-termination and automatic scaling policies all
changed a TERMINATED cluster, and AddTags and RemoveTags its tags.

AWS documents these for running clusters, but no answer for an ended
one is recorded. So they give the one AWS gives AddJobFlowSteps and
ModifyInstanceFleet, "A job flow that is shutting down, terminated, or
finished may not be modified.", in the code each operation's model
points at, as AddInstanceGroups and AddInstanceFleet already did for a
TERMINATING cluster: InvalidRequestException with ErrorCode
INVALID_JOB_SHUT_DOWN for ModifyCluster, ValidationException for the
others, whose models declare no InvalidRequestException. A Set* request
naming such a cluster changes none of the clusters it names.

AddInstanceGroups and AddInstanceFleet now answer a TERMINATED cluster
that way too, in place of "Cluster <id> is terminated.", which no source
has.

The Management Guide says "you cannot add, edit, or remove tags from a
terminated cluster" and names no error. AddTags and RemoveTags refuse an
ended cluster with InvalidRequestException "Tags cannot be modified on
terminated clusters.", the message a tagging tool matches from AWS.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-11 14:08:56 -06:00
1 parent 4766d86077
commit 4c9572b95b
7 files changed
+252 -23

No files matched your search

@@ -15,6 +15,7 @@ import org.junit.jupiter.api.TestMethodOrder;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.List;
import static io.floci.aws.testing.EmrRequests.emr;
import static org.hamcrest.Matchers.endsWith;
@@ -38,6 +39,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class EmrIntegrationTest {
private static final String SHUT_DOWN =
"A job flow that is shutting down, terminated, or finished may not be modified.";
private static String clusterId;
private static String stepId;
@@ -432,6 +436,54 @@ class EmrIntegrationTest {
emr("TerminateJobFlows", "{" + ids + "}").then().statusCode(200);
}
@Test
void anEndedClusterRefusesModifyClusterTheSettersAndTagChanges() {
String ended = emr("RunJobFlow", "{\"Name\":\"ended\",\"Tags\":[{\"Key\":\"team\",\"Value\":\"data\"}],"
+ "\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true}}")
.then().statusCode(200).extract().path("JobFlowId");
String active = emr("RunJobFlow", "{\"Name\":\"active\",\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true}}")
.then().statusCode(200).extract().path("JobFlowId");
emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + ended + "\"]}").then().statusCode(200);
String both = "\"JobFlowIds\":[\"" + active + "\",\"" + ended + "\"]";
emr("ModifyCluster", "{\"ClusterId\":\"" + ended + "\",\"StepConcurrencyLevel\":5}")
.then().statusCode(400)
.body("__type", equalTo("InvalidRequestException"))
.body("message", equalTo(SHUT_DOWN))
.body("ErrorCode", equalTo("INVALID_JOB_SHUT_DOWN"));
assertShutDown("SetTerminationProtection", "{" + both + ",\"TerminationProtected\":true}");
assertShutDown("SetVisibleToAllUsers", "{" + both + ",\"VisibleToAllUsers\":false}");
assertShutDown("SetKeepJobFlowAliveWhenNoSteps", "{" + both + ",\"KeepJobFlowAliveWhenNoSteps\":false}");
assertShutDown("SetUnhealthyNodeReplacement", "{" + both + ",\"UnhealthyNodeReplacement\":true}");
assertTagsRefused("AddTags", "{\"ResourceId\":\"" + ended + "\",\"Tags\":[{\"Key\":\"env\",\"Value\":\"test\"}]}");
assertTagsRefused("RemoveTags", "{\"ResourceId\":\"" + ended + "\",\"TagKeys\":[\"team\"]}");
for (String id : List.of(active, ended)) {
emr("DescribeCluster", "{\"ClusterId\":\"" + id + "\"}").then().statusCode(200)
.body("Cluster.StepConcurrencyLevel", equalTo(1))
.body("Cluster.TerminationProtected", equalTo(false))
.body("Cluster.VisibleToAllUsers", equalTo(true))
.body("Cluster.AutoTerminate", equalTo(false))
.body("Cluster.UnhealthyNodeReplacement", equalTo(false));
}
emr("DescribeCluster", "{\"ClusterId\":\"" + ended + "\"}").then().statusCode(200)
.body("Cluster.Tags", hasSize(1))
.body("Cluster.Tags[0].Key", equalTo("team"));
emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + active + "\"]}").then().statusCode(200);
}
private static void assertShutDown(String action, String body) {
emr(action, body).then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo(SHUT_DOWN));
}
private static void assertTagsRefused(String action, String body) {
emr(action, body).then().statusCode(400)
.body("__type", equalTo("InvalidRequestException"))
.body("message", equalTo("Tags cannot be modified on terminated clusters."));
}
private static void assertMissing(String action, String body, String member) {
emr(action, body).then().statusCode(400)
.body("__type", equalTo("ValidationException"))
@@ -180,4 +180,31 @@ class EmrPoliciesIntegrationTest {
emr("PutBlockPublicAccessConfiguration", "{\"BlockPublicAccessConfiguration\":{}}")
.then().statusCode(400).body("__type", equalTo("InvalidRequestException"));
}
@Test
@Order(8)
void anEndedClustersPoliciesCannotBePutOrRemoved() {
String core = ",\"InstanceGroupId\":\"" + coreGroupId + "\"";
emr("PutAutoScalingPolicy", cluster() + core + ",\"AutoScalingPolicy\":" + AUTO_SCALING + "}")
.then().statusCode(200);
emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + clusterId + "\"]}").then().statusCode(200);
assertShutDown("PutManagedScalingPolicy", cluster() + ",\"ManagedScalingPolicy\":" + MANAGED_SCALING + "}");
assertShutDown("RemoveManagedScalingPolicy", cluster() + "}");
assertShutDown("PutAutoTerminationPolicy", cluster() + ",\"AutoTerminationPolicy\":{\"IdleTimeout\":3600}}");
assertShutDown("RemoveAutoTerminationPolicy", cluster() + "}");
assertShutDown("PutAutoScalingPolicy", cluster() + core + ",\"AutoScalingPolicy\":" + AUTO_SCALING + "}");
assertShutDown("RemoveAutoScalingPolicy", cluster() + core + "}");
emr("ListInstanceGroups", cluster() + "}").then().statusCode(200)
.body("InstanceGroups.find { it.Id == '" + coreGroupId + "' }.AutoScalingPolicy.Constraints.MaxCapacity",
equalTo(4));
}
private static void assertShutDown(String action, String body) {
emr(action, body).then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo(
"A job flow that is shutting down, terminated, or finished may not be modified."));
}
}
@@ -3,6 +3,7 @@ package io.floci.aws.services.emr;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.ContainerTeardown;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.services.emr.model.EmrCluster;
@@ -34,6 +35,7 @@ import static io.floci.aws.services.emr.EmrServiceFixture.cluster;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
@@ -217,6 +219,24 @@ class EmrServiceContainerStepsTest {
+ " 2026-01-01 00:00 UTC with a reason of STEP_FAILURE.", event.path("message").asText());
}
@Test
void aClusterEndedWithErrorsRefusesChangesAndTagChanges() {
String id = service.runJobFlow(cluster("doomed", true, sparkStep("breaks", "TERMINATE_CLUSTER")), REGION)
.getId();
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
fixture.runStepThread();
AwsException modifying = assertThrows(AwsException.class, () -> service.modifyCluster(id, 2));
AwsException protecting = assertThrows(AwsException.class,
() -> service.setTerminationProtection(List.of(id), true));
AwsException tagging = assertThrows(AwsException.class, () -> service.addTags(id, Map.of("team", "data")));
assertEquals("TERMINATED_WITH_ERRORS", service.describeCluster(id).getState());
assertEquals(Map.of("ErrorCode", "INVALID_JOB_SHUT_DOWN"), modifying.getExtendedData());
assertEquals("ValidationException", protecting.getErrorCode());
assertEquals("Tags cannot be modified on terminated clusters.", tagging.getMessage());
}
@Test
void terminateClusterLeavesAProtectedClusterThatWaitsAfterItsStepsRunning() {
EmrCluster requested = cluster("protected", true, sparkStep("breaks", "TERMINATE_CLUSTER"),
@@ -1,5 +1,8 @@
package io.floci.aws.services.emr;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrInstanceFleet;
@@ -7,6 +10,7 @@ import io.floci.aws.services.emr.model.EmrInstanceGroup;
import io.floci.aws.services.emr.model.EmrStep;
import io.floci.aws.testing.MutableClock;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.time.Duration;
import java.time.Instant;
@@ -34,6 +38,12 @@ class EmrServiceTest {
private static final String SHUT_DOWN =
"A job flow that is shutting down, terminated, or finished may not be modified.";
private static final String MANAGED_SCALING =
"{\"ComputeLimits\":{\"UnitType\":\"Instances\",\"MinimumCapacityUnits\":1,\"MaximumCapacityUnits\":5}}";
private static final String AUTO_TERMINATION = "{\"IdleTimeout\":3600}";
private static final String AUTO_SCALING = "{\"Constraints\":{\"MinCapacity\":1,\"MaxCapacity\":4},"
+ "\"Rules\":[{\"Name\":\"scale-out\",\"Action\":{},\"Trigger\":{}}]}";
private static final ObjectMapper MAPPER = new ObjectMapper();
@Test
void aClusterIsStartingThenBootstrappingUntilItIsReady() {
@@ -337,6 +347,76 @@ class EmrServiceTest {
assertEquals(1, service.listInstanceFleets(cluster.getId()).size());
}
@Test
void aClusterShuttingDownKeepsItsSettingsAndPolicies() {
EmrServiceFixture fixture = new EmrServiceFixture(0, 0, 30);
EmrService service = fixture.service;
EmrCluster withGroup = cluster("settings", true);
withGroup.getInstanceGroups().add(group("CORE", 2));
EmrCluster cluster = service.runJobFlow(withGroup, REGION);
String id = cluster.getId();
String groupId = cluster.getInstanceGroups().get(0).getId();
service.putManagedScalingPolicy(id, json(MANAGED_SCALING));
service.putAutoTerminationPolicy(id, json(AUTO_TERMINATION));
service.putAutoScalingPolicy(id, groupId, json(AUTO_SCALING));
service.terminateJobFlows(List.of(id));
EmrCluster before = service.describeCluster(id);
List<Executable> changes = List.of(
() -> service.setTerminationProtection(List.of(id), true),
() -> service.setVisibleToAllUsers(List.of(id), !before.isVisibleToAllUsers()),
() -> service.setKeepJobFlowAliveWhenNoSteps(List.of(id), false),
() -> service.setUnhealthyNodeReplacement(List.of(id), true),
() -> service.putManagedScalingPolicy(id, json(MANAGED_SCALING)),
() -> service.removeManagedScalingPolicy(id),
() -> service.putAutoTerminationPolicy(id, json(AUTO_TERMINATION)),
() -> service.removeAutoTerminationPolicy(id),
() -> service.putAutoScalingPolicy(id, groupId, json(AUTO_SCALING)),
() -> service.removeAutoScalingPolicy(id, groupId));
AwsException modifying = assertThrows(AwsException.class, () -> service.modifyCluster(id, 4));
List<AwsException> refusals = changes.stream()
.map(change -> assertThrows(AwsException.class, change))
.toList();
assertEquals("TERMINATING", before.getState());
assertShutDown(modifying);
for (AwsException refused : refusals) {
assertEquals("ValidationException", refused.getErrorCode());
assertEquals(SHUT_DOWN, refused.getMessage());
}
EmrCluster after = service.describeCluster(id);
assertEquals(before.getStepConcurrencyLevel(), after.getStepConcurrencyLevel());
assertEquals(before.isTerminationProtected(), after.isTerminationProtected());
assertEquals(before.isVisibleToAllUsers(), after.isVisibleToAllUsers());
assertEquals(before.isKeepJobFlowAliveWhenNoSteps(), after.isKeepJobFlowAliveWhenNoSteps());
assertEquals(before.isAutoTerminate(), after.isAutoTerminate());
assertEquals(before.isUnhealthyNodeReplacement(), after.isUnhealthyNodeReplacement());
assertEquals(json(MANAGED_SCALING).toString(), after.getManagedScalingPolicy());
assertEquals(json(AUTO_TERMINATION).toString(), after.getAutoTerminationPolicy());
assertEquals(json(AUTO_SCALING).toString(), after.getInstanceGroups().get(0).getAutoScalingPolicy());
}
@Test
void tagsChangeUntilTheClusterHasEnded() {
EmrServiceFixture fixture = new EmrServiceFixture(0, 0, 30);
EmrService service = fixture.service;
String id = service.runJobFlow(cluster("tagged", true), REGION).getId();
service.terminateJobFlows(List.of(id));
service.addTags(id, Map.of("team", "data", "stage", "test"));
service.removeTags(id, List.of("stage"));
fixture.clock.advance(Duration.ofSeconds(30));
AwsException adding = assertThrows(AwsException.class, () -> service.addTags(id, Map.of("owner", "me")));
AwsException removing = assertThrows(AwsException.class, () -> service.removeTags(id, List.of("team")));
assertEquals("TERMINATED", service.describeCluster(id).getState());
for (AwsException refused : List.of(adding, removing)) {
assertEquals("InvalidRequestException", refused.getErrorCode());
assertEquals("Tags cannot be modified on terminated clusters.", refused.getMessage());
}
assertEquals(Map.of("team", "data"), service.describeCluster(id).getTags());
}
@Test
void listingClustersByStateFindsThemAsTheyStandNow() {
EmrServiceFixture fixture = new EmrServiceFixture(10, 0, 0);
@@ -437,6 +517,14 @@ class EmrServiceTest {
assertEquals(Map.of("ErrorCode", "MODIFY_INSTANCE_FLEET_OF_RUNNING_JOBFLOW_ONLY"), refused.getExtendedData());
}
private static JsonNode json(String text) {
try {
return MAPPER.readTree(text);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(text, e);
}
}
private static EmrInstanceGroup group(String type, int count) {
EmrInstanceGroup group = new EmrInstanceGroup();
group.setInstanceGroupType(type);
@@ -33,7 +33,7 @@ class EmrTerminatedCapacityIntegrationTest {
+ "\"HadoopJarStep\":{\"Jar\":\"command-runner.jar\"}}";
private static final String GROUP_REFUSAL =
"An instance group may only be modified when the cluster is running or waiting.";
private static final String FLEET_REFUSAL =
private static final String SHUT_DOWN =
"A job flow that is shutting down, terminated, or finished may not be modified.";
@BeforeAll
@@ -98,7 +98,9 @@ class EmrTerminatedCapacityIntegrationTest {
assertCannotModifyGroup(id, true);
emr("AddInstanceGroups", "{\"JobFlowId\":\"" + id + "\",\"InstanceGroups\":["
+ "{\"InstanceRole\":\"TASK\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1}]}")
.then().statusCode(400).body("__type", equalTo("InvalidRequestException"));
.then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo(SHUT_DOWN));
assertTerminatedGroup(id);
}
@@ -119,7 +121,10 @@ class EmrTerminatedCapacityIntegrationTest {
emr("AddInstanceFleet", "{\"ClusterId\":\"" + id + "\",\"InstanceFleet\":{"
+ "\"InstanceFleetType\":\"TASK\",\"TargetOnDemandCapacity\":1,"
+ "\"InstanceTypeConfigs\":[{\"InstanceType\":\"m5.xlarge\"}]}}")
.then().statusCode(400).body("__type", equalTo("InvalidRequestException"));
.then().statusCode(400)
.body("__type", equalTo("InvalidRequestException"))
.body("message", equalTo(SHUT_DOWN))
.body("ErrorCode", equalTo("INVALID_JOB_SHUT_DOWN"));
assertTerminatedFleet(id);
}
@@ -191,7 +196,7 @@ class EmrTerminatedCapacityIntegrationTest {
+ "\"InstanceFleetId\":\"" + fleetId + "\",\"TargetOnDemandCapacity\":4}}")
.then().statusCode(400)
.body("__type", equalTo("InvalidRequestException"))
.body("message", equalTo(FLEET_REFUSAL))
.body("message", equalTo(SHUT_DOWN))
.body("ErrorCode", equalTo("INVALID_JOB_SHUT_DOWN"));
assertTerminatedFleet(id);
}