feat(emr): add an optional timed lifecycle for clusters and steps (#6441)

Three settings, all 0 by default, hold an EMR cluster and its steps in
the states of the Management Guide's cluster lifecycle.
cluster-startup-delay-seconds, declared before but read by nothing,
keeps a new cluster STARTING for its first half and BOOTSTRAPPING for
its second; step-duration-seconds keeps each step RUNNING; and
cluster-termination-delay-seconds keeps a cluster TERMINATING before it
is TERMINATED. A ready cluster is RUNNING while it runs its steps, in
the order they were added and at most its StepConcurrencyLevel at a
time, and WAITING once none is left; a transient one ends after them
without waiting. ModifyCluster starts the steps a higher level makes
room for. TerminateJobFlows cancels every step not yet completed, as
its API reference says, and CancelSteps cancels a RUNNING step from
release emr-5.28.0, which makes room for the next. A waiter or a step
sensor now has something to wait for, and CancelSteps something to
cancel.

A new EmrClusterLifecycle works out when each change falls due from the
settings and the times already recorded. Every call that reads a
cluster first makes the changes due by then, and the service wakes at
each cluster's next change, also after a restart, so the change's
aws.emr event goes out when it happens, read or not; a wakeup sends its
events on a thread of their own, in order, so a slow rule target holds
up no cluster's change. A step's RUNNING now sends the step events
table's event, and a WAITING cluster that runs added steps sends
WAITING again once they are done. Every call that reads a cluster now
holds the service and publishes its events after, as the four that
changed one did, and answers from a copy made while it holds it.

With the settings at 0, a cluster is ready, and its steps complete,
before the call returns, as before; the step RUNNING events and the
second WAITING are the only new events. ModifyInstanceGroups and
ModifyInstanceFleet refuse a cluster that is not RUNNING or WAITING, a
STARTING or BOOTSTRAPPING one included, as their AWS messages say, and
AddJobFlowSteps and ModifyInstanceFleet a TERMINATING one, whose AWS
message names a cluster "shutting down". AddInstanceFleet gives a
TERMINATING one ModifyInstanceFleet's answer too, and AddInstanceGroups
AddJobFlowSteps' ValidationException, since its model declares no
InvalidRequestException; an AddJobFlowSteps with no steps leaves the
cluster as it is.

Part of #6046 (part 4).
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-24 20:22:11 -05:00
1 parent 7d4caf2291
commit 55b060b891
13 files changed
+1716 -580

No files matched your search

@@ -1,15 +1,9 @@
package io.github.hectorvent.floci.services.emr;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.emr.model.EmrCluster;
import io.github.hectorvent.floci.services.emr.model.EmrStep;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.testing.InMemoryStorageFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Instant;
@@ -19,69 +13,37 @@ import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import static io.github.hectorvent.floci.services.emr.EmrServiceFixture.REGION;
import static io.github.hectorvent.floci.services.emr.EmrServiceFixture.cluster;
import static io.github.hectorvent.floci.services.emr.EmrServiceFixture.step;
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.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* The {@code aws.emr} events {@link EmrService} publishes, in the order it publishes them, each one
* checked against the Management Guide's detail and its tables' severity and message.
* checked against the Management Guide's detail and its tables' severity and message. The durations
* are 0, as by default; {@link EmrServiceTest} covers the timed lifecycle.
*/
class EmrEventPublisherTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final DateTimeFormatter MINUTE =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm 'UTC'").withZone(ZoneOffset.UTC);
private final ObjectMapper objectMapper = new ObjectMapper();
private final List<JsonNode> published = new ArrayList<>();
private Target target = event -> { };
private EmrEventPublisher publisher;
private EmrService service;
/** A rule's target, given each event as it is published, as EventBridge's first delivery is. */
@FunctionalInterface
private interface Target {
void deliver(JsonNode event) throws Exception;
}
@BeforeEach
void setUp() {
EventBridgeService eventBridge = mock(EventBridgeService.class);
doAnswer(invocation -> {
// The call that made the change has let go of the service by now.
assertFalse(Thread.holdsLock(service), "published while EmrService was held");
JsonNode event = objectMapper.createObjectNode()
.put("detail-type", invocation.<String>getArgument(1))
.set("detail", objectMapper.readTree(invocation.<String>getArgument(2)));
published.add(event);
target.deliver(event);
return null;
}).when(eventBridge).publishServiceEvent(eq("aws.emr"), anyString(), anyString(), isNull(), eq(REGION));
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().emr().defaultReleaseLabel()).thenReturn("emr-7.5.0");
publisher = new EmrEventPublisher(eventBridge, objectMapper, new RegionResolver(REGION, ACCOUNT));
service = new EmrService(new InMemoryStorageFactory(ACCOUNT), config, new RegionResolver(REGION, ACCOUNT),
publisher);
}
private final EmrServiceFixture fixture = new EmrServiceFixture();
private final EmrService service = fixture.service;
private final EmrEventPublisher publisher = fixture.publisher;
private final List<JsonNode> published = fixture.published;
@Test
void aClusterThatRunsItsStepsAndWaitsIsStartedAddsAndCompletesThemAndWaits() {
void aClusterThatRunsItsStepsAndWaitsIsStartedAddsRunsAndCompletesThemAndWaits() {
EmrCluster cluster = service.runJobFlow(cluster("nightly", true, step("load"), step("report")), REGION);
EmrStep load = cluster.getSteps().get(0);
EmrStep report = cluster.getSteps().get(1);
assertEquals(List.of("STARTING", "PENDING load", "PENDING report", "COMPLETED load", "COMPLETED report",
"WAITING"), states());
assertEquals(List.of("STARTING", "PENDING load", "PENDING report", "RUNNING load", "COMPLETED load",
"RUNNING report", "COMPLETED report", "WAITING"), fixture.states());
// As the events tell it: every step was added before the first one ran.
assertFalse(report.getCreationDateTime().isAfter(load.getStartDateTime()));
assertCluster(published.get(0), cluster, "STARTING", "INFO", "{\"code\":\"\"}",
@@ -90,22 +52,25 @@ class EmrEventPublisherTest {
assertStep(published.get(1), cluster, load, "PENDING", "INFO",
"Step " + load.getId() + " (load) was added to Amazon EMR cluster " + cluster.getId()
+ " (nightly) at " + minute(load.getCreationDateTime()) + " and is pending execution.");
assertStep(published.get(3), cluster, load, "COMPLETED", "INFO",
assertStep(published.get(3), cluster, load, "RUNNING", "INFO",
"Step " + load.getId() + " (load) in Amazon EMR cluster " + cluster.getId()
+ " (nightly) started running at " + minute(load.getStartDateTime()) + ".");
assertStep(published.get(4), cluster, load, "COMPLETED", "INFO",
"Step " + load.getId() + " (load) in Amazon EMR cluster " + cluster.getId()
+ " (nightly) completed execution at " + minute(load.getEndDateTime())
+ ". The step started running at " + minute(load.getStartDateTime())
+ " and took 0 minutes to complete.");
assertEquals(report.getId(), published.get(4).at("/detail/stepId").asText());
assertCluster(published.get(5), cluster, "WAITING", "INFO", "{\"code\":\"\"}",
assertEquals(report.getId(), published.get(6).at("/detail/stepId").asText());
assertCluster(published.get(7), cluster, "WAITING", "INFO", "{\"code\":\"\"}",
"Amazon EMR cluster " + cluster.getId() + " (nightly) finished running all pending steps at "
+ minute(cluster.getReadyDateTime()) + ".");
+ minute(report.getEndDateTime()) + ".");
}
@Test
void aClusterWithoutStepsIsReadyForUse() {
EmrCluster cluster = service.runJobFlow(cluster("idle", true), REGION);
assertEquals(List.of("STARTING", "WAITING"), states());
assertEquals(List.of("STARTING", "WAITING"), fixture.states());
assertEquals("Amazon EMR cluster " + cluster.getId() + " (idle) was created at "
+ minute(cluster.getReadyDateTime()) + " and is ready for use.",
published.get(1).at("/detail/message").asText());
@@ -115,21 +80,25 @@ class EmrEventPublisherTest {
void aTransientClusterTerminatesAfterItsStepsWithoutWaiting() {
EmrCluster cluster = service.runJobFlow(cluster("transient", false, step("only")), REGION);
assertEquals(List.of("STARTING", "PENDING only", "COMPLETED only", "TERMINATED"), states());
assertCluster(published.get(3), cluster, "TERMINATED", "INFO",
assertEquals(List.of("STARTING", "PENDING only", "RUNNING only", "COMPLETED only", "TERMINATED"),
fixture.states());
assertCluster(published.get(4), cluster, "TERMINATED", "INFO",
"{\"code\":\"ALL_STEPS_COMPLETED\",\"message\":\"All steps completed.\"}",
"Amazon EMR Cluster " + cluster.getId() + " (transient) has terminated at "
+ minute(cluster.getEndDateTime()) + " with a reason of ALL_STEPS_COMPLETED.");
}
@Test
void stepsAddedToAWaitingClusterLeaveItWaiting() {
void stepsAddedToAWaitingClusterRunAndLeaveItWaitingAgain() {
EmrCluster cluster = service.runJobFlow(cluster("kept", true), REGION);
published.clear();
service.addJobFlowSteps(cluster.getId(), List.of(step("late")));
EmrStep late = step("late");
service.addJobFlowSteps(cluster.getId(), List.of(late));
assertEquals(List.of("PENDING late", "COMPLETED late"), states());
assertEquals(List.of("PENDING late", "RUNNING late", "COMPLETED late", "WAITING"), fixture.states());
assertEquals("Amazon EMR cluster " + cluster.getId() + " (kept) finished running all pending steps at "
+ minute(late.getEndDateTime()) + ".", published.get(3).at("/detail/message").asText());
}
@Test
@@ -139,9 +108,9 @@ class EmrEventPublisherTest {
service.addJobFlowSteps(cluster.getId(), List.of(step("late")));
assertEquals(List.of("PENDING late", "COMPLETED late", "TERMINATED"), states());
assertEquals(List.of("PENDING late", "RUNNING late", "COMPLETED late", "TERMINATED"), fixture.states());
assertEquals("{\"code\":\"ALL_STEPS_COMPLETED\",\"message\":\"All steps completed.\"}",
published.get(2).at("/detail/stateChangeReason").asText());
published.get(3).at("/detail/stateChangeReason").asText());
}
@Test
@@ -157,7 +126,7 @@ class EmrEventPublisherTest {
List<String> ids = List.of(ended.getId(), gone.getId(), kept.getId());
assertThrows(AwsException.class, () -> service.terminateJobFlows(ids));
assertEquals(List.of("TERMINATED"), states());
assertEquals(List.of("TERMINATED"), fixture.states());
assertCluster(published.get(0), service.describeCluster(ended.getId()), "TERMINATED", "INFO",
"{\"code\":\"USER_REQUEST\",\"message\":\"Terminated by user request\"}",
"Amazon EMR Cluster " + ended.getId() + " (ended) has terminated at "
@@ -174,12 +143,12 @@ class EmrEventPublisherTest {
assertThrows(AwsException.class, () -> service.addJobFlowSteps(cluster.getId(), List.of(step("late"))));
assertThrows(AwsException.class, () -> service.runJobFlow(new EmrCluster(), REGION));
assertEquals(List.of(), states());
assertEquals(List.of(), fixture.states());
}
@Test
void aTargetThatEndsTheClusterOnItsStartingEventHearsOfItAfterTheRestOfTheCall() {
target = event -> {
fixture.target = event -> {
if ("STARTING".equals(event.at("/detail/state").asText())) {
service.terminateJobFlows(List.of(event.at("/detail/clusterId").asText()));
}
@@ -187,13 +156,13 @@ class EmrEventPublisherTest {
service.runJobFlow(cluster("answered", true), REGION);
assertEquals(List.of("STARTING", "WAITING", "TERMINATED"), states());
assertEquals(List.of("STARTING", "WAITING", "TERMINATED"), fixture.states());
}
@Test
void aTargetCallingBackFromAnotherThreadHearsOfItAfterTheRestOfTheCall() {
AtomicReference<Throwable> failure = new AtomicReference<>();
target = event -> {
fixture.target = event -> {
if ("STARTING".equals(event.at("/detail/state").asText())) {
// As an API destination would, from the thread serving its request, while this one waits.
String clusterId = event.at("/detail/clusterId").asText();
@@ -212,7 +181,7 @@ class EmrEventPublisherTest {
service.runJobFlow(cluster("answered", true), REGION);
assertNull(failure.get());
assertEquals(List.of("STARTING", "WAITING", "TERMINATED"), states());
assertEquals(List.of("STARTING", "WAITING", "TERMINATED"), fixture.states());
}
@Test
@@ -220,9 +189,9 @@ class EmrEventPublisherTest {
EmrCluster cluster = service.runJobFlow(cluster("failing", true), REGION);
cluster.setStateChangeReasonCode("STEP_FAILURE");
cluster.setStateChangeMessage("Shut down as step failed");
cluster.setEndDateTime(Instant.parse("2026-10-24T09:41:30Z"));
JsonNode detail = objectMapper.readTree(publisher.clusterStateChange(cluster, "TERMINATED").detail());
JsonNode detail = fixture.objectMapper.readTree(
publisher.clusterStateChange(cluster, "TERMINATED", Instant.parse("2026-10-24T09:41:30Z")).detail());
assertEquals("CRITICAL", detail.path("severity").asText());
assertEquals("Amazon EMR Cluster " + cluster.getId() + " (failing) has terminated at 2026-10-24 09:41 UTC"
@@ -238,7 +207,7 @@ class EmrEventPublisherTest {
EmrEventPublisher.Event event = publisher.stepStatusChange(cluster, step, "CANCELLED");
assertEquals("EMR Step Status Change", event.detailType());
JsonNode detail = objectMapper.readTree(event.detail());
JsonNode detail = fixture.objectMapper.readTree(event.detail());
assertEquals("WARN", detail.path("severity").asText());
assertEquals("Cancellation request has succeeded for cluster step " + step.getId() + " (doomed) in Amazon EMR"
+ " cluster " + cluster.getId() + " (cancelling) at 2026-10-24 09:41 UTC, and the step is now"
@@ -274,16 +243,6 @@ class EmrEventPublisherTest {
assertEquals(message, detail.path("message").asText());
}
/** Each event's state, a step's followed by its name. */
private List<String> states() {
return published.stream().map(event -> {
JsonNode detail = event.path("detail");
return detail.has("stepId")
? detail.path("state").asText() + " " + detail.path("name").asText()
: detail.path("state").asText();
}).toList();
}
private static List<String> fieldNames(JsonNode node) {
List<String> names = new ArrayList<>();
node.fieldNames().forEachRemaining(names::add);
@@ -293,19 +252,4 @@ class EmrEventPublisherTest {
private static String minute(Instant instant) {
return MINUTE.format(instant);
}
private static EmrCluster cluster(String name, boolean keepAlive, EmrStep... steps) {
EmrCluster cluster = new EmrCluster();
cluster.setName(name);
cluster.setKeepJobFlowAliveWhenNoSteps(keepAlive);
cluster.setSteps(new ArrayList<>(List.of(steps)));
return cluster;
}
private static EmrStep step(String name) {
EmrStep step = new EmrStep();
step.setName(name);
step.setActionOnFailure("CONTINUE");
return step;
}
}
@@ -13,9 +13,6 @@ import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import static io.github.hectorvent.floci.testing.EmrRequests.emr;
import static org.hamcrest.MatcherAssert.assertThat;
@@ -52,24 +49,32 @@ class EmrEventsIntegrationTest {
+ "\"Steps\":[{\"Name\":\"load\",\"ActionOnFailure\":\"CONTINUE\","
+ "\"HadoopJarStep\":{\"Jar\":\"command-runner.jar\"}}]}")
.then().statusCode(200).extract().path("JobFlowId");
emr(region, "AddJobFlowSteps", "{\"JobFlowId\":\"" + clusterId + "\",\"Steps\":[{\"Name\":\"report\","
+ "\"ActionOnFailure\":\"CONTINUE\",\"HadoopJarStep\":{\"Jar\":\"command-runner.jar\"}}]}")
.then().statusCode(200);
String reportId = emr(region, "AddJobFlowSteps", "{\"JobFlowId\":\"" + clusterId + "\","
+ "\"Steps\":[{\"Name\":\"report\",\"ActionOnFailure\":\"CONTINUE\","
+ "\"HadoopJarStep\":{\"Jar\":\"command-runner.jar\"}}]}")
.then().statusCode(200).extract().path("StepIds[0]");
Instant reportEnded = stepEnd(region, clusterId, reportId);
emr(region, "TerminateJobFlows", "{\"JobFlowIds\":[\"" + clusterId + "\"]}").then().statusCode(200);
Map<String, JsonNode> events = byState(queue.drain(), region, clusterId);
assertThat(events.keySet(), containsInAnyOrder("STARTING", "PENDING load", "COMPLETED load", "WAITING",
"PENDING report", "COMPLETED report", "TERMINATED"));
JsonNode waiting = events.get("WAITING").path("detail");
assertEquals("{\"code\":\"\"}", waiting.path("stateChangeReason").asText());
assertEquals("Amazon EMR cluster " + clusterId + " (kept) finished running all pending steps at "
+ minute(timeline(region, clusterId, "ReadyDateTime")) + ".", waiting.path("message").asText());
JsonNode completed = events.get("COMPLETED report").path("detail");
List<JsonNode> events = checked(queue.drain(), region, clusterId);
assertThat(events.stream().map(EmrEventsIntegrationTest::state).toList(), containsInAnyOrder(
"STARTING", "PENDING load", "RUNNING load", "COMPLETED load", "WAITING",
"PENDING report", "RUNNING report", "COMPLETED report", "WAITING", "TERMINATED"));
// Once after the first step, and again after the one added later.
List<JsonNode> waiting = withState(events, "WAITING");
for (JsonNode event : waiting) {
assertEquals("{\"code\":\"\"}", event.path("detail").path("stateChangeReason").asText());
}
String finished = "Amazon EMR cluster " + clusterId + " (kept) finished running all pending steps at ";
assertThat(waiting.stream().map(event -> event.path("detail").path("message").asText()).toList(),
containsInAnyOrder(finished + minute(timeline(region, clusterId, "ReadyDateTime")) + ".",
finished + minute(reportEnded) + "."));
JsonNode completed = withState(events, "COMPLETED report").get(0).path("detail");
assertEquals("INFO", completed.path("severity").asText());
assertEquals("CONTINUE", completed.path("actionOnFailure").asText());
assertTrue(completed.path("message").asText().endsWith(" and took 0 minutes to complete."),
completed.path("message").asText());
JsonNode terminated = events.get("TERMINATED").path("detail");
JsonNode terminated = withState(events, "TERMINATED").get(0).path("detail");
assertEquals("INFO", terminated.path("severity").asText());
assertEquals("{\"code\":\"USER_REQUEST\",\"message\":\"Terminated by user request\"}",
terminated.path("stateChangeReason").asText());
@@ -87,24 +92,23 @@ class EmrEventsIntegrationTest {
+ "\"Steps\":[{\"Name\":\"only\",\"HadoopJarStep\":{\"Jar\":\"command-runner.jar\"}}]}")
.then().statusCode(200).extract().path("JobFlowId");
Map<String, JsonNode> events = byState(queue.drain(), region, clusterId);
assertThat(events.keySet(),
containsInAnyOrder("STARTING", "PENDING only", "COMPLETED only", "TERMINATED"));
JsonNode terminated = events.get("TERMINATED").path("detail");
List<JsonNode> events = checked(queue.drain(), region, clusterId);
assertThat(events.stream().map(EmrEventsIntegrationTest::state).toList(), containsInAnyOrder(
"STARTING", "PENDING only", "RUNNING only", "COMPLETED only", "TERMINATED"));
JsonNode terminated = withState(events, "TERMINATED").get(0).path("detail");
assertEquals("INFO", terminated.path("severity").asText());
assertEquals("{\"code\":\"ALL_STEPS_COMPLETED\",\"message\":\"All steps completed.\"}",
terminated.path("stateChangeReason").asText());
assertEquals("TERMINATE_CLUSTER",
events.get("PENDING only").path("detail").path("actionOnFailure").asText());
withState(events, "PENDING only").get(0).path("detail").path("actionOnFailure").asText());
}
}
/**
* The events by state, a step's followed by its name, once each is checked to be one of
* {@code clusterId}'s, sent by EMR to {@code region}'s default bus with no resources. A state seen
* twice fails, so the keys are every event.
* The events, once each is checked to be one of {@code clusterId}'s, sent by EMR to {@code region}'s
* default bus with no resources.
*/
private static Map<String, JsonNode> byState(List<JsonNode> events, String region, String clusterId) {
private static List<JsonNode> checked(List<JsonNode> events, String region, String clusterId) {
for (JsonNode event : events) {
assertEquals("aws.emr", event.path("source").asText());
assertEquals(ACCOUNT, event.path("account").asText());
@@ -114,12 +118,19 @@ class EmrEventsIntegrationTest {
assertEquals(event.path("detail").has("stepId") ? "EMR Step Status Change" : "EMR Cluster State Change",
event.path("detail-type").asText());
}
return events.stream().collect(Collectors.toMap(event -> {
JsonNode detail = event.path("detail");
return detail.has("stepId")
? detail.path("state").asText() + " " + detail.path("name").asText()
: detail.path("state").asText();
}, Function.identity()));
return events;
}
/** The event's state, a step's followed by its name. */
private static String state(JsonNode event) {
JsonNode detail = event.path("detail");
return detail.has("stepId")
? detail.path("state").asText() + " " + detail.path("name").asText()
: detail.path("state").asText();
}
private static List<JsonNode> withState(List<JsonNode> events, String state) {
return events.stream().filter(event -> state.equals(state(event))).toList();
}
private static Instant timeline(String region, String clusterId, String field) {
@@ -129,6 +140,13 @@ class EmrEventsIntegrationTest {
return Instant.ofEpochMilli(seconds.movePointRight(3).longValue());
}
private static Instant stepEnd(String region, String clusterId, String stepId) {
BigDecimal seconds = emr(region, "DescribeStep", "{\"ClusterId\":\"" + clusterId + "\",\"StepId\":\""
+ stepId + "\"}").then().statusCode(200).extract().response().jsonPath(DECIMAL_NUMBERS)
.get("Step.Status.Timeline.EndDateTime");
return Instant.ofEpochMilli(seconds.movePointRight(3).longValue());
}
private static String minute(Instant instant) {
return MINUTE.format(instant);
}
@@ -127,22 +127,23 @@ class EmrIntegrationTest {
.then().statusCode(200)
.body("Clusters.find { it.Id == '" + clusterId + "' }", nullValue());
EmrCluster cluster = emrService.describeCluster(clusterId);
EmrCluster cluster = storedCluster("floci-emr-pinned");
String pinnedId = cluster.getId();
Instant originalCreationTime = cluster.getCreationDateTime();
cluster.setCreationDateTime(Instant.ofEpochMilli(1_761_000_000_000L));
try {
emr("ListClusters", "{\"CreatedBefore\":1761000000.001}")
.then().statusCode(200)
.body("Clusters.find { it.Id == '" + clusterId + "' }.Name", equalTo("floci-emr"));
.body("Clusters.find { it.Id == '" + pinnedId + "' }.Name", equalTo("floci-emr-pinned"));
emr("ListClusters", "{\"CreatedAfter\":1760999999.999}")
.then().statusCode(200)
.body("Clusters.find { it.Id == '" + clusterId + "' }.Name", equalTo("floci-emr"));
.body("Clusters.find { it.Id == '" + pinnedId + "' }.Name", equalTo("floci-emr-pinned"));
emr("ListClusters", "{\"CreatedBefore\":1761000000.000000001}")
.then().statusCode(200)
.body("Clusters.find { it.Id == '" + clusterId + "' }", nullValue());
.body("Clusters.find { it.Id == '" + pinnedId + "' }", nullValue());
emr("ListClusters", "{\"CreatedAfter\":1760999999.999999999}")
.then().statusCode(200)
.body("Clusters.find { it.Id == '" + clusterId + "' }", nullValue());
.body("Clusters.find { it.Id == '" + pinnedId + "' }", nullValue());
} finally {
cluster.setCreationDateTime(originalCreationTime);
}
@@ -153,7 +154,7 @@ class EmrIntegrationTest {
.then().statusCode(200).extract().asString()).path("Clusters");
JsonNode listedTime = null;
for (JsonNode listed : clusters) {
if (clusterId.equals(listed.path("Id").asText())) {
if (pinnedId.equals(listed.path("Id").asText())) {
listedTime = listed.path("Status").path("Timeline").path("CreationDateTime");
break;
}
@@ -163,7 +164,7 @@ class EmrIntegrationTest {
assertEquals(0, new BigDecimal("1761000000.123").compareTo(listedTime.decimalValue()));
JsonNode describedTime = objectMapper.readTree(emr("DescribeCluster",
"{\"ClusterId\":\"" + clusterId + "\"}")
"{\"ClusterId\":\"" + pinnedId + "\"}")
.then().statusCode(200).extract().asString())
.path("Cluster").path("Status").path("Timeline").path("CreationDateTime");
assertTrue(describedTime.isNumber());
@@ -171,10 +172,10 @@ class EmrIntegrationTest {
emr("ListClusters", "{\"CreatedAfter\":" + listedTime.asText() + "}")
.then().statusCode(200)
.body("Clusters.find { it.Id == '" + clusterId + "' }", nullValue());
.body("Clusters.find { it.Id == '" + pinnedId + "' }", nullValue());
emr("ListClusters", "{\"CreatedBefore\":" + listedTime.asText() + "}")
.then().statusCode(200)
.body("Clusters.find { it.Id == '" + clusterId + "' }", nullValue());
.body("Clusters.find { it.Id == '" + pinnedId + "' }", nullValue());
} finally {
cluster.setCreationDateTime(originalCreationTime);
}
@@ -441,14 +442,9 @@ class EmrIntegrationTest {
// Catches: a cluster stored before the DNS fix keeps reporting its old us-east-1 master name.
@Test
void storedClusterReportsTheRegionalMasterDnsName() {
String id = emr("RunJobFlow",
"{\"Name\":\"stale-dns\",\"ReleaseLabel\":\"emr-7.5.0\","
+ "\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true,"
+ "\"InstanceGroups\":[{\"Name\":\"master\",\"InstanceRole\":\"MASTER\","
+ "\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1}]}}")
.then().statusCode(200)
.extract().path("JobFlowId");
emrService.describeCluster(id).setMasterPublicDnsName("ip-10-0-0-1.us-east-1.compute.internal");
EmrCluster stored = storedCluster("stale-dns");
stored.setMasterPublicDnsName("ip-10-0-0-1.us-east-1.compute.internal");
String id = stored.getId();
emr("DescribeCluster", "{\"ClusterId\":\"" + id + "\"}")
.then().statusCode(200)
@@ -457,4 +453,15 @@ class EmrIntegrationTest {
emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + id + "\"]}")
.then().statusCode(200);
}
/**
* A kept-alive cluster as RunJobFlow stores it: the service's own object, which a test can change,
* unlike the copy DescribeCluster answers from.
*/
private EmrCluster storedCluster(String name) {
EmrCluster cluster = new EmrCluster();
cluster.setName(name);
cluster.setKeepJobFlowAliveWhenNoSteps(true);
return emrService.runJobFlow(cluster, "us-east-1");
}
}
@@ -0,0 +1,163 @@
package io.github.hectorvent.floci.services.emr;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.emr.model.EmrCluster;
import io.github.hectorvent.floci.services.emr.model.EmrStep;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.testing.InMemoryStorageFactory;
import io.github.hectorvent.floci.testing.MutableClock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* An {@link EmrService} on in-memory storage, with a clock the test moves and wakeups the test runs,
* recording the {@code aws.emr} events it publishes. Each event is handed to {@link #target} as it is
* published, as EventBridge's first delivery is, and checked to be published once the service is let go,
* and, for a wakeup's, after it, as the timer's own thread never sends them.
*/
final class EmrServiceFixture {
static final String REGION = "us-east-1";
static final String ACCOUNT = "000000000000";
/** A rule's target, given each event as it is published. */
@FunctionalInterface
interface Target {
void deliver(JsonNode event) throws Exception;
}
private record Wakeup(Instant due, Runnable task) {}
final ObjectMapper objectMapper = new ObjectMapper();
final List<JsonNode> published = new ArrayList<>();
final MutableClock clock;
final EmrEventPublisher publisher;
// Not final: the events' check reads it, from the mock set up before the service is built.
EmrService service;
Target target = event -> { };
private final List<Wakeup> wakeups = new ArrayList<>();
private final List<Runnable> deliveries = new ArrayList<>();
private boolean waking;
private final InMemoryStorageFactory storage;
private final int[] durations;
/** The service as configured by default, every duration 0. */
EmrServiceFixture() {
this(0, 0, 0);
}
EmrServiceFixture(int startupDelaySeconds, int stepDurationSeconds, int terminationDelaySeconds) {
this(new InMemoryStorageFactory(ACCOUNT), new MutableClock(),
startupDelaySeconds, stepDurationSeconds, terminationDelaySeconds);
}
private EmrServiceFixture(InMemoryStorageFactory storage, MutableClock clock, int... durations) {
this.storage = storage;
this.clock = clock;
this.durations = durations;
EventBridgeService eventBridge = mock(EventBridgeService.class);
doAnswer(invocation -> {
// The call that made the change has let go of the service by now.
assertFalse(Thread.holdsLock(service), "published while EmrService was held");
assertFalse(waking, "published by a wakeup itself");
JsonNode event = objectMapper.createObjectNode()
.put("detail-type", invocation.<String>getArgument(1))
.set("detail", objectMapper.readTree(invocation.<String>getArgument(2)));
published.add(event);
target.deliver(event);
return null;
}).when(eventBridge).publishServiceEvent(eq("aws.emr"), anyString(), anyString(), isNull(), eq(REGION));
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().emr().defaultReleaseLabel()).thenReturn("emr-7.5.0");
when(config.services().emr().clusterStartupDelaySeconds()).thenReturn(durations[0]);
when(config.services().emr().stepDurationSeconds()).thenReturn(durations[1]);
when(config.services().emr().clusterTerminationDelaySeconds()).thenReturn(durations[2]);
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
publisher = new EmrEventPublisher(eventBridge, objectMapper, regionResolver);
service = new EmrService(storage, config, regionResolver, publisher, clock, new EmrService.Wakeups() {
@Override
public void at(Instant due, Runnable task) {
wakeups.add(new Wakeup(due, task));
}
@Override
public void deliver(Runnable delivery) {
deliveries.add(delivery);
}
});
}
/** A new service on the same storage and clock, as after a restart of Floci with persistent storage. */
EmrServiceFixture restart() {
return new EmrServiceFixture(storage, clock, durations);
}
/**
* Moves the clock on by {@code duration} and runs the wakeups due by then, as the service's timer
* would, the ones they set included, each followed by the delivery of its events.
*/
void pass(Duration duration) {
clock.advance(duration);
Instant now = clock.instant();
List<Wakeup> due;
while (!(due = wakeups.stream().filter(wakeup -> !wakeup.due().isAfter(now)).toList()).isEmpty()) {
wakeups.removeAll(due);
for (Wakeup wakeup : due) {
waking = true;
try {
wakeup.task().run();
} finally {
waking = false;
}
while (!deliveries.isEmpty()) {
deliveries.remove(0).run();
}
}
}
}
/** The times of the wakeups not yet run. */
List<Instant> wakeupTimes() {
return wakeups.stream().map(Wakeup::due).toList();
}
/** Each event's state, a step's followed by its name. */
List<String> states() {
return published.stream().map(event -> {
JsonNode detail = event.path("detail");
return detail.has("stepId")
? detail.path("state").asText() + " " + detail.path("name").asText()
: detail.path("state").asText();
}).toList();
}
static EmrCluster cluster(String name, boolean keepAlive, EmrStep... steps) {
EmrCluster cluster = new EmrCluster();
cluster.setName(name);
cluster.setKeepJobFlowAliveWhenNoSteps(keepAlive);
cluster.setSteps(new ArrayList<>(List.of(steps)));
return cluster;
}
static EmrStep step(String name) {
EmrStep step = new EmrStep();
step.setName(name);
step.setActionOnFailure("CONTINUE");
return step;
}
}
@@ -0,0 +1,463 @@
package io.github.hectorvent.floci.services.emr;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.emr.model.EmrCluster;
import io.github.hectorvent.floci.services.emr.model.EmrInstanceFleet;
import io.github.hectorvent.floci.services.emr.model.EmrInstanceGroup;
import io.github.hectorvent.floci.services.emr.model.EmrStep;
import io.github.hectorvent.floci.testing.MutableClock;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static io.github.hectorvent.floci.services.emr.EmrServiceFixture.REGION;
import static io.github.hectorvent.floci.services.emr.EmrServiceFixture.cluster;
import static io.github.hectorvent.floci.services.emr.EmrServiceFixture.step;
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;
/**
* The timed lifecycle: the durations {@code cluster-startup-delay-seconds}, {@code step-duration-seconds}
* and {@code cluster-termination-delay-seconds} hold a cluster and its steps in each state of the
* Management Guide's lifecycle, a call finds them as they stand when it is made, and the service sends
* each change's event when it falls due, without anyone asking.
*/
class EmrServiceTest {
private static final String SHUT_DOWN =
"A job flow that is shutting down, terminated, or finished may not be modified.";
@Test
void aClusterIsStartingThenBootstrappingUntilItIsReady() {
EmrServiceFixture fixture = new EmrServiceFixture(10, 0, 0);
EmrService service = fixture.service;
EmrCluster cluster = service.runJobFlow(cluster("slow", true), REGION);
Instant created = cluster.getCreationDateTime();
assertEquals("STARTING", service.describeCluster(cluster.getId()).getState());
fixture.clock.advance(Duration.ofSeconds(5));
assertEquals("BOOTSTRAPPING", service.describeCluster(cluster.getId()).getState());
fixture.clock.advance(Duration.ofSeconds(5));
EmrCluster ready = service.describeCluster(cluster.getId());
assertEquals("WAITING", ready.getState());
assertEquals(created.plusSeconds(10), ready.getReadyDateTime());
assertEquals(List.of("STARTING", "WAITING"), fixture.states());
assertTrue(fixture.published.get(1).at("/detail/message").asText().endsWith(" was created at "
+ "2026-01-01 00:00 UTC and is ready for use."));
}
@Test
void aClusterNobodyReadsSendsEachEventWhenItFallsDue() {
EmrServiceFixture fixture = new EmrServiceFixture(10, 60, 30);
EmrCluster cluster = fixture.service.runJobFlow(cluster("unread", false, step("only")), REGION);
Instant created = cluster.getCreationDateTime();
assertEquals(List.of("STARTING", "PENDING only"), fixture.states());
assertEquals(List.of(created.plusSeconds(5)), fixture.wakeupTimes());
fixture.pass(Duration.ofSeconds(10));
assertEquals(List.of("STARTING", "PENDING only", "RUNNING only"), fixture.states());
assertEquals(List.of(created.plusSeconds(70)), fixture.wakeupTimes());
fixture.pass(Duration.ofSeconds(60));
assertEquals(List.of("STARTING", "PENDING only", "RUNNING only", "COMPLETED only"), fixture.states());
fixture.pass(Duration.ofSeconds(30));
assertEquals(List.of("STARTING", "PENDING only", "RUNNING only", "COMPLETED only", "TERMINATED"),
fixture.states());
assertEquals(List.of(), fixture.wakeupTimes());
EmrCluster ended = fixture.service.describeCluster(cluster.getId());
assertEquals("TERMINATED", ended.getState());
assertEquals("ALL_STEPS_COMPLETED", ended.getStateChangeReasonCode());
assertEquals(created.plusSeconds(100), ended.getEndDateTime());
}
@Test
void stepsRunOneAtATimeInTheOrderTheyWereAdded() {
EmrServiceFixture fixture = new EmrServiceFixture(0, 60, 0);
EmrService service = fixture.service;
EmrCluster cluster = service.runJobFlow(cluster("serial", true, step("a"), step("b")), REGION);
String id = cluster.getId();
EmrStep a = cluster.getSteps().get(0);
EmrStep b = cluster.getSteps().get(1);
assertEquals("RUNNING", service.describeCluster(id).getState());
assertEquals(List.of("PENDING", "RUNNING"), states(service.listSteps(id, null, null)));
assertEquals(List.of(b.getId()), ids(service.listSteps(id, List.of("PENDING"), null)));
fixture.clock.advance(Duration.ofSeconds(60));
assertEquals(List.of("RUNNING", "COMPLETED"), states(service.listSteps(id, null, null)));
assertEquals(a.getStartDateTime().plusSeconds(60), a.getEndDateTime());
assertEquals(a.getEndDateTime(), b.getStartDateTime());
fixture.clock.advance(Duration.ofSeconds(60));
assertEquals("WAITING", service.describeCluster(id).getState());
assertEquals(List.of("STARTING", "PENDING a", "PENDING b", "RUNNING a", "COMPLETED a", "RUNNING b",
"COMPLETED b", "WAITING"), fixture.states());
assertTrue(fixture.published.get(4).at("/detail/message").asText()
.endsWith(" and took 1 minutes to complete."));
}
@Test
void aClusterRunsAsManyStepsAtOnceAsItsConcurrencyLevelAllows() {
EmrServiceFixture fixture = new EmrServiceFixture(0, 60, 0);
EmrService service = fixture.service;
EmrCluster parallel = cluster("parallel", true, step("a"), step("b"), step("c"));
parallel.setStepConcurrencyLevel(2);
String id = service.runJobFlow(parallel, REGION).getId();
assertEquals(List.of("PENDING", "RUNNING", "RUNNING"), states(service.listSteps(id, null, null)));
fixture.clock.advance(Duration.ofSeconds(10));
service.modifyCluster(id, 3);
assertEquals(List.of("RUNNING", "RUNNING", "RUNNING"), states(service.listSteps(id, null, null)));
// Lowering the level lets the steps already running complete.
service.modifyCluster(id, 1);
fixture.clock.advance(Duration.ofSeconds(60));
assertEquals(List.of("COMPLETED", "COMPLETED", "COMPLETED"), states(service.listSteps(id, null, null)));
assertEquals("WAITING", service.describeCluster(id).getState());
}
@Test
void stepsAddedWhileAClusterStartsRunOnceItIsReady() {
EmrServiceFixture fixture = new EmrServiceFixture(10, 60, 0);
EmrService service = fixture.service;
EmrCluster cluster = service.runJobFlow(cluster("early", true), REGION);
EmrStep early = step("early");
service.addJobFlowSteps(cluster.getId(), List.of(early));
assertEquals("PENDING", early.getState());
fixture.clock.advance(Duration.ofSeconds(10));
assertEquals("RUNNING", service.describeStep(cluster.getId(), early.getId()).getState());
assertEquals(cluster.getCreationDateTime().plusSeconds(10), early.getStartDateTime());
assertEquals("RUNNING", service.describeCluster(cluster.getId()).getState());
}
@Test
void aWaitingClusterIsRunningWhileItRunsAddedStepsAndWaitsAgainAfter() {
EmrServiceFixture fixture = new EmrServiceFixture(0, 60, 0);
EmrService service = fixture.service;
String id = service.runJobFlow(cluster("kept", true), REGION).getId();
assertEquals("Cluster ready to run steps.", service.describeCluster(id).getStateChangeMessage());
service.addJobFlowSteps(id, List.of(step("late")));
EmrCluster running = service.describeCluster(id);
assertEquals("RUNNING", running.getState());
assertNull(running.getStateChangeReasonCode());
assertNull(running.getStateChangeMessage());
fixture.clock.advance(Duration.ofSeconds(60));
EmrCluster waiting = service.describeCluster(id);
assertEquals("WAITING", waiting.getState());
assertEquals("ALL_STEPS_COMPLETED", waiting.getStateChangeReasonCode());
assertEquals(List.of("STARTING", "WAITING", "PENDING late", "RUNNING late", "COMPLETED late", "WAITING"),
fixture.states());
}
@Test
void addingNoStepsLeavesAWaitingClusterAsItIs() {
EmrServiceFixture fixture = new EmrServiceFixture(0, 60, 0);
EmrService service = fixture.service;
String fresh = service.runJobFlow(cluster("fresh", true), REGION).getId();
String done = service.runJobFlow(cluster("done", true, step("only")), REGION).getId();
fixture.clock.advance(Duration.ofSeconds(60));
// Set to end after its steps: a cluster that already waits ends only after the next ones it runs.
service.setKeepJobFlowAliveWhenNoSteps(List.of(done), false);
fixture.published.clear();
assertEquals(List.of(), service.addJobFlowSteps(fresh, List.of()));
assertEquals(List.of(), service.addJobFlowSteps(done, List.of()));
assertEquals("Cluster ready to run steps.", service.describeCluster(fresh).getStateChangeMessage());
EmrCluster waiting = service.describeCluster(done);
assertEquals("WAITING", waiting.getState());
assertEquals("ALL_STEPS_COMPLETED", waiting.getStateChangeReasonCode());
assertEquals(List.of(), fixture.states());
}
@Test
void cancellingAPendingStepLeavesTheRunningOneRunning() {
EmrServiceFixture fixture = new EmrServiceFixture(0, 60, 0);
EmrService service = fixture.service;
EmrCluster cluster = service.runJobFlow(cluster("cancel", true, step("a"), step("b")), REGION);
EmrStep b = cluster.getSteps().get(1);
List<EmrService.CancelStepInfo> infos = service.cancelSteps(cluster.getId(), List.of(b.getId()));
assertEquals(List.of(new EmrService.CancelStepInfo(b.getId(), "SUBMITTED", null)), infos);
assertEquals(List.of("CANCELLED", "RUNNING"), states(service.listSteps(cluster.getId(), null, null)));
assertEquals("CANCELLED b", fixture.states().get(fixture.states().size() - 1));
}
@Test
void cancellingARunningStepLetsTheNextOneRun() {
EmrServiceFixture fixture = new EmrServiceFixture(0, 60, 0);
EmrService service = fixture.service;
EmrCluster cluster = service.runJobFlow(cluster("cancel", true, step("a"), step("b")), REGION);
EmrStep a = cluster.getSteps().get(0);
fixture.clock.advance(Duration.ofSeconds(10));
List<EmrService.CancelStepInfo> infos = service.cancelSteps(cluster.getId(), List.of(a.getId()));
assertEquals(List.of(new EmrService.CancelStepInfo(a.getId(), "SUBMITTED", null)), infos);
assertEquals(List.of("RUNNING", "CANCELLED"), states(service.listSteps(cluster.getId(), null, null)));
assertEquals(a.getEndDateTime(), cluster.getSteps().get(1).getStartDateTime());
assertEquals(List.of("CANCELLED a", "RUNNING b"),
fixture.states().subList(fixture.states().size() - 2, fixture.states().size()));
}
@Test
void aReleaseBefore528CancelsOnlyPendingSteps() {
EmrServiceFixture fixture = new EmrServiceFixture(0, 60, 0);
EmrService service = fixture.service;
EmrCluster old = cluster("old", true, step("a"), step("b"));
old.setReleaseLabel("emr-5.27.0");
EmrCluster cluster = service.runJobFlow(old, REGION);
String a = cluster.getSteps().get(0).getId();
String b = cluster.getSteps().get(1).getId();
List<EmrService.CancelStepInfo> infos = service.cancelSteps(cluster.getId(), List.of(a, b));
assertEquals(List.of(
new EmrService.CancelStepInfo(a, "FAILED", "Step is not in a cancellable state: RUNNING"),
new EmrService.CancelStepInfo(b, "SUBMITTED", null)), infos);
assertTrue(EmrClusterLifecycle.cancelsRunningSteps("emr-5.28.0"));
assertTrue(EmrClusterLifecycle.cancelsRunningSteps("emr-7.5.0"));
assertFalse(EmrClusterLifecycle.cancelsRunningSteps("emr-4.9.6"));
}
@Test
void terminatingCancelsTheStepsNotYetCompletedAndEndsAfterTheDelay() {
EmrServiceFixture fixture = new EmrServiceFixture(0, 60, 30);
EmrService service = fixture.service;
EmrCluster kept = cluster("ending", true, step("a"), step("b"));
kept.getInstanceGroups().add(group("CORE", 2));
EmrCluster cluster = service.runJobFlow(kept, REGION);
String id = cluster.getId();
fixture.clock.advance(Duration.ofSeconds(10));
fixture.published.clear();
service.terminateJobFlows(List.of(id));
EmrCluster terminating = service.describeCluster(id);
assertEquals("TERMINATING", terminating.getState());
assertEquals("USER_REQUEST", terminating.getStateChangeReasonCode());
assertNull(terminating.getEndDateTime());
assertEquals(List.of("CANCELLED", "CANCELLED"), states(service.listSteps(id, null, null)));
assertEquals("RUNNING", service.listInstanceGroups(id).get(0).getState());
AwsException refused = assertThrows(AwsException.class,
() -> service.addJobFlowSteps(id, List.of(step("late"))));
assertEquals(SHUT_DOWN, refused.getMessage());
service.terminateJobFlows(List.of(id));
assertEquals(List.of("CANCELLED a", "CANCELLED b"), fixture.states());
fixture.clock.advance(Duration.ofSeconds(30));
EmrCluster ended = service.describeCluster(id);
assertEquals("TERMINATED", ended.getState());
assertEquals(terminating.getTerminatingDateTime().plusSeconds(30), ended.getEndDateTime());
assertEquals("TERMINATED", service.listInstanceGroups(id).get(0).getState());
assertEquals(0, service.listInstanceGroups(id).get(0).getRunningInstanceCount());
assertEquals(List.of("CANCELLED a", "CANCELLED b", "TERMINATED"), fixture.states());
}
@Test
void instanceGroupsChangeOnlyWhileTheClusterRunsOrWaits() {
EmrServiceFixture fixture = new EmrServiceFixture(10, 0, 30);
EmrService service = fixture.service;
EmrCluster withGroup = cluster("groups", true);
withGroup.getInstanceGroups().add(group("CORE", 2));
EmrCluster cluster = service.runJobFlow(withGroup, REGION);
String groupId = cluster.getInstanceGroups().get(0).getId();
List<EmrService.InstanceGroupModification> resize =
List.of(new EmrService.InstanceGroupModification(groupId, 3, null));
AwsException starting = assertThrows(AwsException.class,
() -> service.modifyInstanceGroups(cluster.getId(), REGION, resize));
assertEquals("An instance group may only be modified when the cluster is running or waiting.",
starting.getMessage());
fixture.clock.advance(Duration.ofSeconds(10));
service.modifyInstanceGroups(null, REGION, resize);
assertEquals(3, service.listInstanceGroups(cluster.getId()).get(0).getRequestedInstanceCount());
service.terminateJobFlows(List.of(cluster.getId()));
assertThrows(AwsException.class, () -> service.modifyInstanceGroups(cluster.getId(), REGION, resize));
AwsException adding = assertThrows(AwsException.class,
() -> service.addInstanceGroups(cluster.getId(), List.of(group("TASK", 1))));
assertEquals("ValidationException", adding.getErrorCode());
assertEquals(SHUT_DOWN, adding.getMessage());
assertEquals(1, service.listInstanceGroups(cluster.getId()).size());
}
@Test
void anInstanceFleetIsResizedOnlyOnceTheClusterRunsOrWaits() {
EmrServiceFixture fixture = new EmrServiceFixture(10, 0, 0);
EmrService service = fixture.service;
EmrCluster withFleet = cluster("starting", true);
EmrInstanceFleet fleet = fleet("CORE", 2);
withFleet.getInstanceFleets().add(fleet);
String id = service.runJobFlow(withFleet, REGION).getId();
AwsException starting = assertThrows(AwsException.class,
() -> service.modifyInstanceFleet(id, fleet.getId(), 3, null));
fixture.clock.advance(Duration.ofSeconds(5));
AwsException bootstrapping = assertThrows(AwsException.class,
() -> service.modifyInstanceFleet(id, fleet.getId(), 3, null));
fixture.clock.advance(Duration.ofSeconds(5));
service.modifyInstanceFleet(id, fleet.getId(), 3, null);
assertNotRunningOrWaiting(starting);
assertNotRunningOrWaiting(bootstrapping);
assertEquals(3, service.listInstanceFleets(id).get(0).getTargetOnDemandCapacity());
}
@Test
void anInstanceFleetIsNotAddedOrResizedWhileTheClusterShutsDown() {
EmrServiceFixture fixture = new EmrServiceFixture(0, 0, 30);
EmrService service = fixture.service;
EmrCluster withFleet = cluster("fleets", true);
EmrInstanceFleet fleet = fleet("CORE", 2);
withFleet.getInstanceFleets().add(fleet);
EmrCluster cluster = service.runJobFlow(withFleet, REGION);
service.terminateJobFlows(List.of(cluster.getId()));
AwsException resizing = assertThrows(AwsException.class,
() -> service.modifyInstanceFleet(cluster.getId(), fleet.getId(), 3, null));
AwsException adding = assertThrows(AwsException.class,
() -> service.addInstanceFleet(cluster.getId(), new EmrInstanceFleet()));
assertShutDown(resizing);
assertShutDown(adding);
assertEquals(1, service.listInstanceFleets(cluster.getId()).size());
}
@Test
void listingClustersByStateFindsThemAsTheyStandNow() {
EmrServiceFixture fixture = new EmrServiceFixture(10, 0, 0);
EmrService service = fixture.service;
String id = service.runJobFlow(cluster("listed", true), REGION).getId();
assertEquals(List.of(), service.listClusters(REGION, List.of("WAITING"), null, null));
fixture.clock.advance(Duration.ofSeconds(10));
assertEquals(List.of(id),
service.listClusters(REGION, List.of("WAITING"), null, null).stream().map(EmrCluster::getId).toList());
}
@Test
void aClusterLeftMidChangeByARestartMovesOnWhenItFallsDue() {
EmrServiceFixture fixture = new EmrServiceFixture(10, 0, 0);
EmrCluster cluster = fixture.service.runJobFlow(cluster("restarted", true), REGION);
EmrServiceFixture restarted = fixture.restart();
assertEquals(List.of(cluster.getCreationDateTime().plusSeconds(5)), restarted.wakeupTimes());
restarted.pass(Duration.ofSeconds(10));
assertEquals(List.of("WAITING"), restarted.states());
}
@Test
void whatACallReturnsStaysAsItWasWhenTheClusterMovesOn() {
EmrServiceFixture fixture = new EmrServiceFixture(0, 60, 30);
EmrService service = fixture.service;
EmrCluster read = cluster("read", true, step("only"));
read.getInstanceGroups().add(group("CORE", 2));
read.getInstanceFleets().add(fleet("TASK", 2));
EmrCluster created = service.runJobFlow(read, REGION);
String id = created.getId();
String stepId = created.getSteps().get(0).getId();
List<EmrCluster> clusters = List.of(service.describeCluster(id),
service.listClusters(REGION, null, null, null).get(0), service.getClusterForInstances(id));
List<EmrStep> steps = List.of(service.describeStep(id, stepId), service.listSteps(id, null, null).get(0));
EmrInstanceGroup group = service.listInstanceGroups(id).get(0);
EmrInstanceFleet fleet = service.listInstanceFleets(id).get(0);
fixture.pass(Duration.ofSeconds(60));
service.terminateJobFlows(List.of(id));
fixture.pass(Duration.ofSeconds(30));
assertEquals("TERMINATED", service.describeCluster(id).getState());
assertEquals(List.of("RUNNING", "RUNNING", "RUNNING"), clusters.stream().map(EmrCluster::getState).toList());
assertEquals(List.of("RUNNING", "RUNNING"), states(steps));
assertNull(steps.get(0).getEndDateTime());
assertEquals(2, group.getRunningInstanceCount());
assertEquals(2, fleet.getProvisionedOnDemandCapacity());
}
@Test
void aSlowDeliveryDoesNotHoldUpTheTimer() throws InterruptedException {
EmrService.Wakeups timer = EmrService.Wakeups.timer(new MutableClock());
CountDownLatch woken = new CountDownLatch(1);
CountDownLatch delivered = new CountDownLatch(1);
try {
// Like a rule's target that answers only once the next cluster has changed.
timer.deliver(() -> {
try {
if (woken.await(10, TimeUnit.SECONDS)) {
delivered.countDown();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
timer.at(Instant.EPOCH, woken::countDown);
assertTrue(delivered.await(10, TimeUnit.SECONDS));
} finally {
timer.close();
}
}
@Test
void aNegativeDurationIsRefused() {
IllegalArgumentException refused = assertThrows(IllegalArgumentException.class,
() -> new EmrServiceFixture(0, -1, 0));
assertEquals("floci.services.emr.step-duration-seconds must not be negative: -1", refused.getMessage());
}
/** ModifyInstanceFleet's answer for a job flow that is shutting down, which AddInstanceFleet shares. */
private static void assertShutDown(AwsException refused) {
assertEquals("InvalidRequestException", refused.getErrorCode());
assertEquals(SHUT_DOWN, refused.getMessage());
assertEquals(Map.of("ErrorCode", "INVALID_JOB_SHUT_DOWN"), refused.getExtendedData());
}
/** ModifyInstanceFleet's answer for a cluster that is starting or bootstrapping. */
private static void assertNotRunningOrWaiting(AwsException refused) {
assertEquals("InvalidRequestException", refused.getErrorCode());
assertEquals("An instance fleet may only be modified when the cluster is running or waiting.",
refused.getMessage());
assertEquals(Map.of("ErrorCode", "MODIFY_INSTANCE_FLEET_OF_RUNNING_JOBFLOW_ONLY"), refused.getExtendedData());
}
private static EmrInstanceGroup group(String type, int count) {
EmrInstanceGroup group = new EmrInstanceGroup();
group.setInstanceGroupType(type);
group.setInstanceType("m5.xlarge");
group.setRequestedInstanceCount(count);
return group;
}
private static EmrInstanceFleet fleet(String type, int onDemandCapacity) {
EmrInstanceFleet fleet = new EmrInstanceFleet();
fleet.setInstanceFleetType(type);
fleet.setTargetOnDemandCapacity(onDemandCapacity);
return fleet;
}
/** ListSteps' states, newest step first, as it lists them. */
private static List<String> states(List<EmrStep> steps) {
return steps.stream().map(EmrStep::getState).toList();
}
private static List<String> ids(List<EmrStep> steps) {
return steps.stream().map(EmrStep::getId).toList();
}
}
@@ -0,0 +1,77 @@
package io.github.hectorvent.floci.services.emr;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static io.github.hectorvent.floci.testing.EmrRequests.emr;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.nullValue;
/**
* With the lifecycle durations set, a cluster is seen STARTING and TERMINATING, and its steps PENDING,
* over the wire. They are an hour long here, so nothing moves on while the test runs.
*/
@QuarkusTest
@TestProfile(EmrTimedLifecycleIntegrationTest.HourLong.class)
class EmrTimedLifecycleIntegrationTest {
public static class HourLong implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of(
"floci.services.emr.cluster-startup-delay-seconds", "3600",
"floci.services.emr.step-duration-seconds", "3600",
"floci.services.emr.cluster-termination-delay-seconds", "3600");
}
}
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void aStartingClusterKeepsItsStepsPendingAndShutsDownWhenTerminated() {
String clusterId = emr("RunJobFlow", "{\"Name\":\"hour-long\","
+ "\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true},"
+ "\"Steps\":[{\"Name\":\"first\",\"HadoopJarStep\":{\"Jar\":\"command-runner.jar\"}},"
+ "{\"Name\":\"second\",\"HadoopJarStep\":{\"Jar\":\"command-runner.jar\"}}]}")
.then().statusCode(200).extract().path("JobFlowId");
String firstId = emr("ListSteps", "{\"ClusterId\":\"" + clusterId + "\"}").then().statusCode(200)
.body("Steps.Status.State", equalTo(List.of("PENDING", "PENDING")))
.extract().path("Steps[1].Id");
emr("DescribeCluster", "{\"ClusterId\":\"" + clusterId + "\"}").then().statusCode(200)
.body("Cluster.Status.State", equalTo("STARTING"))
.body("Cluster.Status.Timeline.ReadyDateTime", nullValue());
emr("ListClusters", "{\"ClusterStates\":[\"STARTING\"]}").then().statusCode(200)
.body("Clusters.Id", hasItem(clusterId));
emr("CancelSteps", "{\"ClusterId\":\"" + clusterId + "\",\"StepIds\":[\"" + firstId + "\"]}")
.then().statusCode(200)
.body("CancelStepsInfoList[0].Status", equalTo("SUBMITTED"));
emr("DescribeStep", "{\"ClusterId\":\"" + clusterId + "\",\"StepId\":\"" + firstId + "\"}")
.then().statusCode(200)
.body("Step.Status.State", equalTo("CANCELLED"));
emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + clusterId + "\"]}").then().statusCode(200);
emr("DescribeCluster", "{\"ClusterId\":\"" + clusterId + "\"}").then().statusCode(200)
.body("Cluster.Status.State", equalTo("TERMINATING"))
.body("Cluster.Status.StateChangeReason.Code", equalTo("USER_REQUEST"));
emr("ListSteps", "{\"ClusterId\":\"" + clusterId + "\"}").then().statusCode(200)
.body("Steps.Status.State", equalTo(List.of("CANCELLED", "CANCELLED")));
emr("AddJobFlowSteps", "{\"JobFlowId\":\"" + clusterId + "\",\"Steps\":[{\"Name\":\"late\","
+ "\"HadoopJarStep\":{\"Jar\":\"command-runner.jar\"}}]}")
.then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo(
"A job flow that is shutting down, terminated, or finished may not be modified."));
}
}