From 4c9572b95bd56ddf925112ff4213aa0a605a625b Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:08:56 -0400 Subject: [PATCH] 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 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. --- docs/services/emr.md | 20 ++++- .../io/floci/aws/services/emr/EmrService.java | 55 ++++++++---- .../aws/services/emr/EmrIntegrationTest.java | 52 +++++++++++ .../emr/EmrPoliciesIntegrationTest.java | 27 ++++++ .../emr/EmrServiceContainerStepsTest.java | 20 +++++ .../aws/services/emr/EmrServiceTest.java | 88 +++++++++++++++++++ .../EmrTerminatedCapacityIntegrationTest.java | 13 ++- 7 files changed, 252 insertions(+), 23 deletions(-) diff --git a/docs/services/emr.md b/docs/services/emr.md index e1220be35d..f0f2d61677 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -95,10 +95,22 @@ and `ModifyInstanceFleet` answers `InvalidRequestException` "A job flow that is terminated, or finished may not be modified." with `ErrorCode` `INVALID_JOB_SHUT_DOWN` for a `TERMINATING` or `TERMINATED` one, and "An instance fleet may only be modified when the cluster is running or waiting." with `ErrorCode` `MODIFY_INSTANCE_FLEET_OF_RUNNING_JOBFLOW_ONLY` for one in any -other state, such as `STARTING` or `BOOTSTRAPPING`. `AddInstanceFleet` gives a `TERMINATING` cluster -the "shutting down" answer, and `AddInstanceGroups` gives it as `ValidationException`, as -`AddJobFlowSteps` does. `InstanceStates` filters the modeled `RUNNING` and `TERMINATED` -instances. +other state, such as `STARTING` or `BOOTSTRAPPING`. `AddInstanceFleet` gives a `TERMINATING` or +`TERMINATED` cluster the "shutting down" answer, and `AddInstanceGroups` gives it as +`ValidationException`, as `AddJobFlowSteps` does. `InstanceStates` filters the modeled `RUNNING` and +`TERMINATED` instances. + +A cluster that is `TERMINATING`, `TERMINATED` or `TERMINATED_WITH_ERRORS` also refuses `ModifyCluster`, +the four `Set*` setters, and `Put` and `Remove` of its managed scaling, auto-termination and automatic +scaling policies, with the same "shutting down" message: `ModifyCluster` as `InvalidRequestException` +with `ErrorCode` `INVALID_JOB_SHUT_DOWN`, since its model declares that exception, and the others as +`ValidationException`, since theirs declare none. AWS documents these operations for running clusters, +but no answer for an ended one is recorded, so this is Floci's reading, taken from the operations whose +answer is. A `Set*` request naming such a cluster changes none of the clusters it names. `AddTags` and +`RemoveTags` refuse a `TERMINATED` or `TERMINATED_WITH_ERRORS` cluster, as the Management Guide says "you +cannot add, edit, or remove tags from a terminated cluster", with `InvalidRequestException` "Tags cannot +be modified on terminated clusters." The guide names no error: the message is the one a tagging tool +matches from AWS, and the code is Floci's reading. `TerminateJobFlows`, the four `Set*` cluster setters and `CancelSteps` refuse a request without a member their model requires (`JobFlowIds` and the setting, or `StepIds`) with `ValidationException` diff --git a/src/main/java/io/floci/aws/services/emr/EmrService.java b/src/main/java/io/floci/aws/services/emr/EmrService.java index dd166051cd..024e1c4177 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrService.java @@ -480,6 +480,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear public int modifyCluster(String id, Integer stepConcurrencyLevel) { return call(() -> { EmrCluster cluster = requireCluster(id); + rejectShutDownCluster(cluster, EmrService::jobFlowShutDown); if (stepConcurrencyLevel != null) { cluster.setStepConcurrencyLevel(stepConcurrencyLevel); lifecycle.concurrencyChanged(cluster, now(), regionOf(cluster)); @@ -858,6 +859,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear public void addTags(String resourceId, Map tags) { run(() -> { EmrCluster cluster = requireCluster(resourceId); + rejectTerminatedTagging(cluster); cluster.getTags().putAll(tags); clusterStore.put(resourceId, cluster); }); @@ -866,6 +868,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear public void removeTags(String resourceId, List keys) { run(() -> { EmrCluster cluster = requireCluster(resourceId); + rejectTerminatedTagging(cluster); keys.forEach(cluster.getTags()::remove); clusterStore.put(resourceId, cluster); }); @@ -878,6 +881,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear public void putManagedScalingPolicy(String clusterId, JsonNode policy) { run(() -> { EmrCluster cluster = requireCluster(clusterId); + rejectShutDownCluster(cluster, EmrService::jobFlowShutDownValidation); validateManagedScalingPolicy(policy); cluster.setManagedScalingPolicy(policy.toString()); clusterStore.put(clusterId, cluster); @@ -892,6 +896,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear public void removeManagedScalingPolicy(String clusterId) { run(() -> { EmrCluster cluster = requireCluster(clusterId); + rejectShutDownCluster(cluster, EmrService::jobFlowShutDownValidation); cluster.setManagedScalingPolicy(null); clusterStore.put(clusterId, cluster); }); @@ -901,6 +906,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear public void putAutoTerminationPolicy(String clusterId, JsonNode policy) { run(() -> { EmrCluster cluster = requireCluster(clusterId); + rejectShutDownCluster(cluster, EmrService::jobFlowShutDownValidation); validateAutoTerminationPolicy(policy); cluster.setAutoTerminationPolicy( policy == null || policy.isMissingNode() || policy.isNull() ? "{}" : policy.toString()); @@ -916,6 +922,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear public void removeAutoTerminationPolicy(String clusterId) { run(() -> { EmrCluster cluster = requireCluster(clusterId); + rejectShutDownCluster(cluster, EmrService::jobFlowShutDownValidation); cluster.setAutoTerminationPolicy(null); clusterStore.put(clusterId, cluster); }); @@ -925,6 +932,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear public EmrInstanceGroup putAutoScalingPolicy(String clusterId, String instanceGroupId, JsonNode policy) { return call(() -> { EmrCluster cluster = requireCluster(clusterId); + rejectShutDownCluster(cluster, EmrService::jobFlowShutDownValidation); EmrInstanceGroup group = requireInstanceGroup(cluster, instanceGroupId); validateAutoScalingPolicy(policy, group.getInstanceGroupType()); group.setAutoScalingPolicy(policy.toString()); @@ -936,6 +944,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear public void removeAutoScalingPolicy(String clusterId, String instanceGroupId) { run(() -> { EmrCluster cluster = requireCluster(clusterId); + rejectShutDownCluster(cluster, EmrService::jobFlowShutDownValidation); requireInstanceGroup(cluster, instanceGroupId).setAutoScalingPolicy(null); clusterStore.put(clusterId, cluster); }); @@ -1111,31 +1120,43 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear return new AwsException("InvalidRequestException", message, 400); } - /** ModifyInstanceFleet's answer for a job flow that is shutting down or ended, ErrorCode member included. */ + /** + * 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. + */ private static AwsException jobFlowShutDown() { return new AwsException("InvalidRequestException", JOB_FLOW_SHUT_DOWN, 400, Map.of("ErrorCode", "INVALID_JOB_SHUT_DOWN")); } /** - * AddJobFlowSteps' answer for a job flow that is shutting down or ended. AddInstanceGroups gives it too: - * like AddJobFlowSteps, its model declares no InvalidRequestException. + * AddJobFlowSteps' answer for a job flow that is shutting down or ended. The operations whose models, + * like AddJobFlowSteps', declare no InvalidRequestException give it too: AddInstanceGroups, the Set* + * setters, and Put and Remove of the managed scaling, auto-termination and automatic scaling policies. */ private static AwsException jobFlowShutDownValidation() { return new AwsException("ValidationException", JOB_FLOW_SHUT_DOWN, 400); } /** - * AddInstanceGroups and AddInstanceFleet on a cluster that is shutting down or ended. A TERMINATING one - * gets {@code shuttingDown}, the operation's answer with AWS's wording, which covers it; a TERMINATED - * one keeps Floci's own, since no AWS answer to either operation is recorded. + * Refuses a change to a cluster that is shutting down or ended with {@code answer}, the job flow message in + * the code the operation's model points at. AWS's answer is recorded for AddJobFlowSteps and + * ModifyInstanceFleet only; the operations calling this, documented for running clusters, take it from them. */ - private static void rejectShutDownCluster(EmrCluster cluster, Supplier shuttingDown) { - if (EmrClusterLifecycle.TERMINATING.equals(cluster.getState())) { - throw shuttingDown.get(); + private static void rejectShutDownCluster(EmrCluster cluster, Supplier answer) { + if (isShutDown(cluster)) { + throw answer.get(); } + } + + /** + * AddTags and RemoveTags on an ended cluster: the Management Guide's "you cannot add, edit, or remove tags + * from a terminated cluster" names no error, so the message is the one a tagging tool matches from AWS, in + * the InvalidRequestException both models declare. + */ + private static void rejectTerminatedTagging(EmrCluster cluster) { if (EmrClusterLifecycle.isTerminated(cluster.getState())) { - throw invalid("Cluster " + cluster.getId() + " is terminated."); + throw invalid("Tags cannot be modified on terminated clusters."); } } @@ -1167,12 +1188,16 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear .map(this::settle); } + /** + * The Set* setters: an unknown id is passed over, and one cluster shutting down or ended refuses the + * request before any of the clusters it names is changed. + */ private void mutateClusters(List ids, Consumer mutation) { - for (String id : ids) { - findCluster(id).ifPresent(c -> { - mutation.accept(c); - clusterStore.put(id, c); - }); + List clusters = ids.stream().map(this::findCluster).flatMap(Optional::stream).toList(); + clusters.forEach(c -> rejectShutDownCluster(c, EmrService::jobFlowShutDownValidation)); + for (EmrCluster c : clusters) { + mutation.accept(c); + clusterStore.put(c.getId(), c); } } diff --git a/src/test/java/io/floci/aws/services/emr/EmrIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrIntegrationTest.java index e44b55f4e3..81fde294ce 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrIntegrationTest.java @@ -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")) diff --git a/src/test/java/io/floci/aws/services/emr/EmrPoliciesIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrPoliciesIntegrationTest.java index 741911a2ce..04456eaa49 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrPoliciesIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrPoliciesIntegrationTest.java @@ -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.")); + } } diff --git a/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java b/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java index a613a9a80c..8b0dc51082 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java @@ -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"), diff --git a/src/test/java/io/floci/aws/services/emr/EmrServiceTest.java b/src/test/java/io/floci/aws/services/emr/EmrServiceTest.java index 7e64eb1d0f..919a0f7d53 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceTest.java @@ -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 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 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); diff --git a/src/test/java/io/floci/aws/services/emr/EmrTerminatedCapacityIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrTerminatedCapacityIntegrationTest.java index a69c93a8c6..b20588edfe 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrTerminatedCapacityIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrTerminatedCapacityIntegrationTest.java @@ -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); }