mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(emr): keep Spark Connect sessions on a cluster (#8699)
EMR's session operations, StartSession, GetSession, ListSessions, TerminateSession and GetSessionEndpoint, were not served, and RunJobFlow dropped SessionEnabled. Floci now keeps a cluster's sessions and their lifecycle, without starting a Spark Connect server for them. RunJobFlow keeps SessionEnabled and DescribeCluster reports it. StartSession needs a cluster with sessions enabled, on emr-spark-8.0.0 or later, with Spark, RUNNING or WAITING, with one primary node and fewer than 1000 sessions that have not ended, as the Management Guide's "Interactive sessions" gives them; a request needs a Name and an idle timeout within 24 hours. It answers SUBMITTED, and the session is IDLE from then on until its idle timeout (60 minutes by default), TerminateSession, or its cluster shutting down ends it. A retry with the same client request token that asks for the same session answers as the first call did. Sessions are kept apart from their clusters, so ended ones weigh on no cluster read or write. GetSessionEndpoint gives an endpoint on Floci's address and a token valid for an hour. ListSessions gives the newest first, by state, a page at a time. A request member of the wrong JSON type is refused with SerializationException. The cluster's installed applications are read by one helper, which the Hive and Pig checks now share with the Spark one. GetSessionEndpoint's endpoint and token come from core.common.SparkConnectEndpoint, which EMR Serverless's GetSessionEndpoint now uses too.
This commit is contained in:
1 parent
3313a5a9f0
commit
bb57e63b8e
17 files changed
+1383
-26
No files matched your search
@@ -0,0 +1,35 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class SparkConnectEndpointTest {
|
||||
|
||||
private static final Instant NOW = Instant.parse("2026-01-01T00:00:00Z");
|
||||
|
||||
@Test
|
||||
void theEndpointIsThePathOnFlocisAddressWithOrWithoutItsTrailingSlash() {
|
||||
assertEquals("http://localhost:4566/_aws/emr/sessions/j-1/is-1", SparkConnectEndpoint.issue(
|
||||
"http://localhost:4566/", "/_aws/emr/sessions/j-1/is-1", NOW, Duration.ofHours(1)).url());
|
||||
assertEquals("http://localhost:4566/_aws/emr/sessions/j-1/is-1", SparkConnectEndpoint.issue(
|
||||
"http://localhost:4566", "/_aws/emr/sessions/j-1/is-1", NOW, Duration.ofHours(1)).url());
|
||||
}
|
||||
|
||||
@Test
|
||||
void eachIssueGivesANewTokenThatExpiresAfterItsValidity() {
|
||||
SparkConnectEndpoint first = SparkConnectEndpoint.issue("http://localhost:4566", "/s", NOW,
|
||||
Duration.ofHours(1));
|
||||
SparkConnectEndpoint second = SparkConnectEndpoint.issue("http://localhost:4566", "/s", NOW,
|
||||
Duration.ofHours(1));
|
||||
|
||||
assertTrue(first.authToken().matches("[0-9a-f]{64}"), first.authToken());
|
||||
assertNotEquals(first.authToken(), second.authToken());
|
||||
assertEquals(NOW.plus(Duration.ofHours(1)), first.authTokenExpiresAt());
|
||||
}
|
||||
}
|
||||
@@ -345,6 +345,7 @@ final class EmrServiceFixture {
|
||||
private EmulatorConfig config(boolean reconcile) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().emr().defaultReleaseLabel()).thenReturn("emr-7.5.0");
|
||||
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566/");
|
||||
when(config.services().emr().clusterStartupDelaySeconds()).thenReturn(durations[0]);
|
||||
when(config.services().emr().stepDurationSeconds()).thenReturn(durations[1]);
|
||||
when(config.services().emr().clusterTerminationDelaySeconds()).thenReturn(durations[2]);
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
package io.floci.aws.services.emr;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.EmrRequests.emr;
|
||||
import static org.hamcrest.Matchers.endsWith;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.matchesPattern;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* A cluster's Spark Connect sessions over the AWS JSON 1.1 wire protocol: StartSession, GetSession, ListSessions,
|
||||
* GetSessionEndpoint and TerminateSession, and RunJobFlow's and DescribeCluster's {@code SessionEnabled}.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class EmrSessionIntegrationTest {
|
||||
|
||||
private static final String ROLE = "arn:aws:iam::000000000000:role/emr-session";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@BeforeAll
|
||||
static void configure() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSessionStartsSubmittedIsIdleOnceReadAndIsListedConnectedToAndTerminated() throws Exception {
|
||||
String clusterId = cluster(true);
|
||||
emr("DescribeCluster", "{\"ClusterId\":\"" + clusterId + "\"}")
|
||||
.then().statusCode(200)
|
||||
.body("Cluster.SessionEnabled", equalTo(true));
|
||||
|
||||
String sessionId = emr("StartSession", """
|
||||
{"ClusterId": "%s", "Name": "notebook", "ExecutionRoleArn": "%s", "SessionIdleTimeoutInMinutes": 30,
|
||||
"ClientRequestToken": "%s",
|
||||
"EngineConfigurations": [{"Classification": "spark-defaults",
|
||||
"Properties": {"spark.executor.memory": "4g"}}],
|
||||
"MonitoringConfiguration": {"S3LoggingConfiguration": {"LogUri": "s3://bucket/sessions/"}},
|
||||
"Tags": [{"Key": "team", "Value": "data"}]}
|
||||
""".formatted(clusterId, ROLE, UUID.randomUUID()))
|
||||
.then().statusCode(200)
|
||||
.body("Id", startsWith("is-"))
|
||||
.body("ClusterId", equalTo(clusterId))
|
||||
.body("Arn", matchesPattern("arn:aws:elasticmapreduce:us-east-1:000000000000:cluster/" + clusterId
|
||||
+ "/session/is-[A-Z0-9]{13}"))
|
||||
.body("AccountId", equalTo("000000000000"))
|
||||
.body("State", equalTo("SUBMITTED"))
|
||||
.extract().path("Id");
|
||||
|
||||
String session = emr("GetSession", "{\"ClusterId\":\"" + clusterId + "\",\"SessionId\":\"" + sessionId
|
||||
+ "\"}")
|
||||
.then().statusCode(200)
|
||||
.body("Session.Id", equalTo(sessionId))
|
||||
.body("Session.Name", equalTo("notebook"))
|
||||
.body("Session.State", equalTo("IDLE"))
|
||||
.body("Session.ReleaseLabel", equalTo("emr-spark-8.0.0"))
|
||||
.body("Session.ExecutionRoleArn", equalTo(ROLE))
|
||||
.body("Session.SessionIdleTimeoutInMinutes", equalTo(30))
|
||||
.body("Session.EngineConfigurations[0].Classification", equalTo("spark-defaults"))
|
||||
.body("Session.MonitoringConfiguration.S3LoggingConfiguration.LogUri",
|
||||
equalTo("s3://bucket/sessions/"))
|
||||
.body("Session.Tags[0].Key", equalTo("team"))
|
||||
.body("Session.CreatedAt", notNullValue())
|
||||
.body("Session.IdleSince", notNullValue())
|
||||
.extract().asString();
|
||||
// Read by JSON Pointer: a JSON path's "Properties" reads Groovy's own properties of the map, not the member.
|
||||
assertEquals("4g", MAPPER.readTree(session)
|
||||
.at("/Session/EngineConfigurations/0/Properties/spark.executor.memory").asText());
|
||||
|
||||
emr("ListSessions", "{\"ClusterId\":\"" + clusterId + "\",\"SessionStates\":[\"IDLE\"]}")
|
||||
.then().statusCode(200)
|
||||
.body("Sessions", hasSize(1))
|
||||
.body("Sessions[0].Id", equalTo(sessionId));
|
||||
|
||||
emr("GetSessionEndpoint", "{\"ClusterId\":\"" + clusterId + "\",\"SessionId\":\"" + sessionId + "\"}")
|
||||
.then().statusCode(200)
|
||||
.body("Endpoint", endsWith("/_aws/emr/sessions/" + clusterId + "/" + sessionId))
|
||||
.body("AuthToken", matchesPattern("[0-9a-f]{64}"))
|
||||
.body("AuthTokenExpirationTime", notNullValue());
|
||||
|
||||
emr("TerminateSession", "{\"ClusterId\":\"" + clusterId + "\",\"SessionId\":\"" + sessionId + "\"}")
|
||||
.then().statusCode(200)
|
||||
.body("ClusterId", equalTo(clusterId))
|
||||
.body("SessionId", equalTo(sessionId))
|
||||
.body("State", equalTo("TERMINATED"));
|
||||
emr("ListSessions", "{\"ClusterId\":\"" + clusterId + "\",\"SessionStates\":[\"IDLE\"]}")
|
||||
.then().statusCode(200)
|
||||
.body("Sessions", hasSize(0));
|
||||
terminate(clusterId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSessionIsRefusedOnAClusterWithoutSessionsOrForAMalformedRequest() {
|
||||
String disabled = cluster(false);
|
||||
emr("StartSession", "{\"ClusterId\":\"" + disabled + "\",\"Name\":\"n\"}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("InvalidRequestException"));
|
||||
emr("DescribeCluster", "{\"ClusterId\":\"" + disabled + "\"}")
|
||||
.then().statusCode(200)
|
||||
.body("Cluster.SessionEnabled", equalTo(false));
|
||||
|
||||
String clusterId = cluster(true);
|
||||
emr("StartSession", "{\"ClusterId\":\"" + clusterId + "\"}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("InvalidRequestException"));
|
||||
emr("StartSession", "{\"ClusterId\":\"" + clusterId + "\",\"Name\":\"n\",\"EngineConfigurations\":\"x\"}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("SerializationException"));
|
||||
emr("StartSession", "{\"ClusterId\":\"" + clusterId + "\",\"Name\":\"n\",\"EngineConfigurations\":"
|
||||
+ "[{\"Classification\":\"spark-defaults\",\"Properties\":{\"a\":1}}]}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("SerializationException"));
|
||||
emr("StartSession", "{\"ClusterId\":\"" + clusterId + "\",\"Name\":\"n\",\"Tags\":{\"Key\":\"k\"}}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("SerializationException"));
|
||||
emr("StartSession", "{\"ClusterId\":\"" + clusterId + "\",\"Name\":\"n\",\"MonitoringConfiguration\":"
|
||||
+ "{\"S3LoggingConfiguration\":\"not-a-structure\"}}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("SerializationException"));
|
||||
emr("StartSession", "{\"ClusterId\":7,\"Name\":\"n\"}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("SerializationException"));
|
||||
emr("ListSessions", "{\"ClusterId\":\"" + clusterId + "\",\"SessionStates\":\"IDLE\"}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("SerializationException"));
|
||||
emr("GetSession", "{\"ClusterId\":\"" + clusterId + "\",\"SessionId\":\"is-NONE\"}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("InvalidRequestException"));
|
||||
terminate(disabled);
|
||||
terminate(clusterId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRetryThatAsksForTheSameSessionGetsTheFirstAnswer() {
|
||||
String clusterId = cluster(true);
|
||||
String token = UUID.randomUUID().toString();
|
||||
String first = emr("StartSession", "{\"ClusterId\":\"" + clusterId + "\",\"Name\":\"n\",\"Tags\":[],"
|
||||
+ "\"ClientRequestToken\":\"" + token + "\"}")
|
||||
.then().statusCode(200).extract().path("Id");
|
||||
emr("StartSession", "{\"ClientRequestToken\":\"" + token + "\",\"Name\":\"n\",\"ClusterId\":\"" + clusterId
|
||||
+ "\",\"SessionIdleTimeoutInMinutes\":60}")
|
||||
.then().statusCode(200)
|
||||
.body("Id", equalTo(first))
|
||||
.body("State", equalTo("SUBMITTED"));
|
||||
emr("StartSession", "{\"ClusterId\":\"" + clusterId + "\",\"Name\":\"other\",\"ClientRequestToken\":\""
|
||||
+ token + "\"}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("InvalidRequestException"));
|
||||
terminate(clusterId);
|
||||
}
|
||||
|
||||
private static String cluster(boolean sessionEnabled) {
|
||||
return emr("RunJobFlow", """
|
||||
{"Name": "sessions", "ReleaseLabel": "emr-spark-8.0.0", "Applications": [{"Name": "Spark"}],
|
||||
"SessionEnabled": %s,
|
||||
"Instances": {"KeepJobFlowAliveWhenNoSteps": true,
|
||||
"InstanceGroups": [{"Name": "primary", "InstanceRole": "MASTER", "InstanceType": "m5.xlarge",
|
||||
"InstanceCount": 1}]}}
|
||||
""".formatted(sessionEnabled))
|
||||
.then().statusCode(200).extract().path("JobFlowId");
|
||||
}
|
||||
|
||||
private static void terminate(String clusterId) {
|
||||
emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + clusterId + "\"]}").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
package io.floci.aws.services.emr;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.PaginatedResult;
|
||||
import io.floci.aws.core.common.SparkConnectEndpoint;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.services.emr.model.EmrCluster;
|
||||
import io.floci.aws.services.emr.model.EmrInstanceGroup;
|
||||
import io.floci.aws.services.emr.model.EmrSession;
|
||||
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.UUID;
|
||||
|
||||
import static io.floci.aws.services.emr.EmrServiceFixture.REGION;
|
||||
import static io.floci.aws.services.emr.EmrServiceFixture.cluster;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** A cluster's Spark Connect sessions, through {@link EmrService}: their lifecycle and what refuses one. */
|
||||
class EmrSessionsTest {
|
||||
|
||||
private static final String RELEASE = "emr-spark-8.0.0";
|
||||
private static final String SPARK = "[{\"Name\":\"Spark\"}]";
|
||||
|
||||
private final EmrServiceFixture fixture = new EmrServiceFixture(0, 0, 0);
|
||||
private final EmrService service = fixture.service;
|
||||
|
||||
@Test
|
||||
void aSessionIsSubmittedAsItStartsAndIdleOnceRead() {
|
||||
String clusterId = sessionCluster();
|
||||
|
||||
EmrSession started = service.startSession(clusterId, request("notebook"));
|
||||
|
||||
assertEquals("SUBMITTED", started.getState());
|
||||
assertTrue(started.getId().matches("is-[A-Z0-9]{13}"), started.getId());
|
||||
assertEquals("arn:aws:elasticmapreduce:us-east-1:000000000000:cluster/" + clusterId + "/session/"
|
||||
+ started.getId(), started.getArn());
|
||||
assertEquals("000000000000", started.getAccountId());
|
||||
EmrSession read = service.getSession(clusterId, started.getId());
|
||||
assertEquals("IDLE", read.getState());
|
||||
assertEquals(read.getCreatedAt(), read.getStartedAt());
|
||||
assertEquals(read.getCreatedAt(), read.getIdleSince());
|
||||
assertEquals(60, read.getSessionIdleTimeoutInMinutes());
|
||||
assertEquals(RELEASE, read.getReleaseLabel());
|
||||
assertEquals("notebook", read.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIdleSessionEndsOnceItsIdleTimeoutHasPassed() {
|
||||
String clusterId = sessionCluster();
|
||||
EmrSessions.Request request = request("short", 30L, null);
|
||||
String sessionId = service.startSession(clusterId, request).getId();
|
||||
Instant idleSince = service.getSession(clusterId, sessionId).getIdleSince();
|
||||
|
||||
fixture.clock.advance(Duration.ofMinutes(29));
|
||||
assertEquals("IDLE", service.getSession(clusterId, sessionId).getState());
|
||||
fixture.clock.advance(Duration.ofMinutes(1));
|
||||
EmrSession ended = service.getSession(clusterId, sessionId);
|
||||
|
||||
assertEquals("TERMINATED", ended.getState());
|
||||
assertEquals(EmrSessions.IDLE_TIMED_OUT, ended.getStateChangeReason());
|
||||
assertEquals(idleSince.plus(Duration.ofMinutes(30)), ended.getEndedAt());
|
||||
assertNull(ended.getIdleSince());
|
||||
}
|
||||
|
||||
@Test
|
||||
void terminatingTheClusterEndsItsSessions() {
|
||||
String clusterId = sessionCluster();
|
||||
String sessionId = service.startSession(clusterId, request("on-a-cluster")).getId();
|
||||
service.getSession(clusterId, sessionId);
|
||||
|
||||
service.terminateJobFlows(List.of(clusterId));
|
||||
|
||||
EmrSession ended = service.getSession(clusterId, sessionId);
|
||||
assertEquals("TERMINATED", ended.getState());
|
||||
assertEquals(EmrSessions.CLUSTER_ENDED, ended.getStateChangeReason());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterThatCannotHoldASessionRefusesIt() {
|
||||
assertInvalid(clusterOf(RELEASE, SPARK, false), "does not have sessions enabled");
|
||||
assertInvalid(clusterOf("emr-7.5.0", SPARK, true), "emr-spark-8.0.0");
|
||||
assertInvalid(clusterOf("emr-spark-7.9.0", SPARK, true), "emr-spark-8.0.0");
|
||||
assertInvalid(clusterOf(RELEASE, "[{\"Name\":\"Hadoop\"}]", true), "does not have Spark installed");
|
||||
|
||||
EmrCluster highlyAvailable = clusterSpec(RELEASE, SPARK, true);
|
||||
EmrInstanceGroup primaries = new EmrInstanceGroup();
|
||||
primaries.setInstanceGroupType("MASTER");
|
||||
primaries.setInstanceType("m5.xlarge");
|
||||
primaries.setRequestedInstanceCount(3);
|
||||
highlyAvailable.getInstanceGroups().add(primaries);
|
||||
assertInvalid(service.runJobFlow(highlyAvailable, REGION).getId(), "multiple primary nodes");
|
||||
|
||||
EmrServiceFixture starting = new EmrServiceFixture(600, 0, 0);
|
||||
String startingId = starting.service.runJobFlow(clusterSpec(RELEASE, SPARK, true), REGION).getId();
|
||||
AwsException notReady = assertThrows(AwsException.class,
|
||||
() -> starting.service.startSession(startingId, request("early")));
|
||||
assertTrue(notReady.getMessage().contains("RUNNING or WAITING"), notReady.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestIsRefusedWithoutANameOrWithAnIdleTimeoutPastADayOrAMalformedRole() {
|
||||
String clusterId = sessionCluster();
|
||||
|
||||
assertEquals("InvalidRequestException", assertThrows(AwsException.class,
|
||||
() -> service.startSession(clusterId, request(null))).getErrorCode());
|
||||
assertEquals("InvalidRequestException", assertThrows(AwsException.class,
|
||||
() -> service.startSession(clusterId, request(" "))).getErrorCode());
|
||||
for (long minutes : new long[]{0, 1441}) {
|
||||
assertEquals("InvalidRequestException", assertThrows(AwsException.class,
|
||||
() -> service.startSession(clusterId, request("t", minutes, null))).getErrorCode());
|
||||
}
|
||||
assertEquals(1440, service.getSession(clusterId,
|
||||
service.startSession(clusterId, request("t", 1440L, null)).getId()).getSessionIdleTimeoutInMinutes());
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class,
|
||||
() -> service.startSession(clusterId, request("r", null, "arn:aws:iam::000000000000:user/u")))
|
||||
.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRetryWithTheSameTokenReturnsTheOriginalAnswerAndADifferentRequestIsRefused() {
|
||||
String clusterId = sessionCluster();
|
||||
String token = UUID.randomUUID().toString();
|
||||
EmrSession started = service.startSession(clusterId,
|
||||
new EmrSessions.Request("retried", null, null, null, null, token, null));
|
||||
service.getSession(clusterId, started.getId());
|
||||
|
||||
// The same session asked for again, its idle timeout and tags now given at what they were.
|
||||
EmrSession retried = service.startSession(clusterId,
|
||||
new EmrSessions.Request("retried", null, null, null, 60L, token, Map.of()));
|
||||
assertEquals(started.getId(), retried.getId());
|
||||
assertEquals("SUBMITTED", retried.getState());
|
||||
|
||||
AwsException conflict = assertThrows(AwsException.class, () -> service.startSession(clusterId,
|
||||
new EmrSessions.Request("other", null, null, null, null, token, Map.of())));
|
||||
assertEquals("InvalidRequestException", conflict.getErrorCode());
|
||||
assertEquals(1, service.listSessions(clusterId, null, null, null).items().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterHoldsAtMostAThousandSessionsThatHaveNotEnded() {
|
||||
String clusterId = sessionCluster();
|
||||
Instant now = fixture.clock.instant();
|
||||
for (int i = 0; i < EmrSessions.MAX_CONCURRENT_SESSIONS; i++) {
|
||||
storeSession(clusterId, "is-" + String.format("%013d", i), i + 1, now);
|
||||
}
|
||||
|
||||
AwsException full = assertThrows(AwsException.class, () -> service.startSession(clusterId, request("one")));
|
||||
assertTrue(full.getMessage().contains("1000 concurrent active sessions"), full.getMessage());
|
||||
|
||||
service.terminateSession(clusterId, "is-0000000000000");
|
||||
assertEquals("SUBMITTED", service.startSession(clusterId, request("one")).getState());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sessionsMadeInTheSameMillisecondListTheNewerFirst() {
|
||||
String clusterId = sessionCluster();
|
||||
Instant now = fixture.clock.instant();
|
||||
storeSession(clusterId, "is-FIRST0000000", 1, now);
|
||||
storeSession(clusterId, "is-SECOND000000", 2, now);
|
||||
|
||||
assertEquals(List.of("is-SECOND000000", "is-FIRST0000000"),
|
||||
ids(service.listSessions(clusterId, null, null, null)));
|
||||
String third = service.startSession(clusterId, request("third")).getId();
|
||||
assertEquals(List.of(third, "is-SECOND000000", "is-FIRST0000000"),
|
||||
ids(service.listSessions(clusterId, null, null, null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSessionThatHasEndedCannotBeTerminatedAgainNorConnectedTo() {
|
||||
String clusterId = sessionCluster();
|
||||
String sessionId = service.startSession(clusterId, request("once")).getId();
|
||||
|
||||
EmrSession terminated = service.terminateSession(clusterId, sessionId);
|
||||
|
||||
assertEquals("TERMINATED", terminated.getState());
|
||||
assertEquals(EmrSessions.USER_REQUEST, terminated.getStateChangeReason());
|
||||
assertEquals("InvalidRequestException", assertThrows(AwsException.class,
|
||||
() -> service.terminateSession(clusterId, sessionId)).getErrorCode());
|
||||
assertEquals("InvalidRequestException", assertThrows(AwsException.class,
|
||||
() -> service.sessionEndpoint(clusterId, sessionId)).getErrorCode());
|
||||
assertEquals("InvalidRequestException", assertThrows(AwsException.class,
|
||||
() -> service.getSession(clusterId, "is-NONE")).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEndpointsTokenLastsAnHourAndEachCallGivesANewOne() {
|
||||
String clusterId = sessionCluster();
|
||||
String sessionId = service.startSession(clusterId, request("connect")).getId();
|
||||
|
||||
SparkConnectEndpoint endpoint = service.sessionEndpoint(clusterId, sessionId);
|
||||
|
||||
assertEquals("http://localhost:4566/_aws/emr/sessions/" + clusterId + "/" + sessionId, endpoint.url());
|
||||
assertTrue(endpoint.authToken().matches("[0-9a-f]{64}"), endpoint.authToken());
|
||||
assertTrue(Duration.between(fixture.clock.instant(), endpoint.authTokenExpiresAt())
|
||||
.compareTo(Duration.ofMinutes(59)) > 0);
|
||||
assertNotEquals(endpoint.authToken(), service.sessionEndpoint(clusterId, sessionId).authToken());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listSessionsGivesTheNewestFirstFilteredByStateAPageAtATime() {
|
||||
String clusterId = sessionCluster();
|
||||
String older = service.startSession(clusterId, request("older")).getId();
|
||||
fixture.clock.advance(Duration.ofSeconds(1));
|
||||
String newer = service.startSession(clusterId, request("newer")).getId();
|
||||
fixture.clock.advance(Duration.ofSeconds(1));
|
||||
String ended = service.startSession(clusterId, request("ended")).getId();
|
||||
service.terminateSession(clusterId, ended);
|
||||
|
||||
assertEquals(List.of(ended, newer, older), ids(service.listSessions(clusterId, null, null, null)));
|
||||
assertEquals(List.of(newer, older), ids(service.listSessions(clusterId, List.of("IDLE"), null, null)));
|
||||
PaginatedResult<EmrSession> first = service.listSessions(clusterId, null, 2, null);
|
||||
assertEquals(List.of(ended, newer), ids(first));
|
||||
assertEquals(List.of(older), ids(service.listSessions(clusterId, null, 2, first.nextToken())));
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class,
|
||||
() -> service.listSessions(clusterId, List.of("RUNNING"), null, null)).getErrorCode());
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class,
|
||||
() -> service.listSessions(clusterId, null, 101, null)).getErrorCode());
|
||||
assertEquals("InvalidRequestException", assertThrows(AwsException.class,
|
||||
() -> service.listSessions(clusterId, null, null, "not-a-token")).getErrorCode());
|
||||
}
|
||||
|
||||
private void assertInvalid(String clusterId, String message) {
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.startSession(clusterId, request("refused")));
|
||||
assertEquals("InvalidRequestException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains(message), refused.getMessage());
|
||||
}
|
||||
|
||||
private static List<String> ids(PaginatedResult<EmrSession> page) {
|
||||
return page.items().stream().map(EmrSession::getId).toList();
|
||||
}
|
||||
|
||||
private String sessionCluster() {
|
||||
return clusterOf(RELEASE, SPARK, true);
|
||||
}
|
||||
|
||||
private String clusterOf(String releaseLabel, String applications, boolean sessionEnabled) {
|
||||
return service.runJobFlow(clusterSpec(releaseLabel, applications, sessionEnabled), REGION).getId();
|
||||
}
|
||||
|
||||
private static EmrCluster clusterSpec(String releaseLabel, String applications, boolean sessionEnabled) {
|
||||
EmrCluster cluster = cluster("sessions", true);
|
||||
cluster.setReleaseLabel(releaseLabel);
|
||||
cluster.setApplications(applications);
|
||||
cluster.setSessionEnabled(sessionEnabled);
|
||||
return cluster;
|
||||
}
|
||||
|
||||
private static EmrSessions.Request request(String name) {
|
||||
return request(name, null, null);
|
||||
}
|
||||
|
||||
private static EmrSessions.Request request(String name, Long idleTimeoutMinutes, String role) {
|
||||
return new EmrSessions.Request(name, role, null, null, idleTimeoutMinutes, null, Map.of());
|
||||
}
|
||||
|
||||
// An IDLE session of the cluster, stored as made, the cluster's sequence-th.
|
||||
private void storeSession(String clusterId, String id, long sequence, Instant createdAt) {
|
||||
AccountAwareStorageBackend<EmrSession> sessions = fixture.storage.create("emr", "emr-sessions.json",
|
||||
new TypeReference<Map<String, EmrSession>>() {});
|
||||
EmrSession session = new EmrSession();
|
||||
session.setId(id);
|
||||
session.setClusterId(clusterId);
|
||||
session.setSequence(sequence);
|
||||
session.setState("IDLE");
|
||||
session.setCreatedAt(createdAt);
|
||||
session.setIdleSince(createdAt);
|
||||
session.setSessionIdleTimeoutInMinutes(EmrSessions.MAX_IDLE_TIMEOUT_MINUTES);
|
||||
sessions.put(id, session);
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.SparkConnectEndpoint;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.services.emrserverless.model.AutoStartConfiguration;
|
||||
import io.floci.aws.services.emrserverless.model.CreateApplicationRequest;
|
||||
@@ -237,7 +238,7 @@ class EmrServerlessSessionServiceTest {
|
||||
String applicationId = application("emr-7.13.0", "SPARK", true);
|
||||
String sessionId = sessions.startSession(applicationId, request()).getSessionId();
|
||||
|
||||
EmrServerlessSessionService.Endpoint endpoint = sessions.sessionEndpoint(applicationId, sessionId);
|
||||
SparkConnectEndpoint endpoint = sessions.sessionEndpoint(applicationId, sessionId);
|
||||
|
||||
assertEquals("http://localhost:4566/_aws/emr-serverless/sessions/" + applicationId + "/" + sessionId,
|
||||
endpoint.url());
|
||||
|
||||
Reference in new issue
Block a user