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:
Priamo Germosen authored and GitHub committed 2026-11-16 23:15:08 -04:00
1 parent 3313a5a9f0
commit bb57e63b8e
17 files changed
+1383 -26

No files matched your search

+43 -1
View File
@@ -4,7 +4,7 @@
**Endpoint:** `http://localhost:4566/`
**Target prefix:** `X-Amz-Target: ElasticMapReduce.*`
Floci emulates the Amazon EMR (Elastic MapReduce) management API. Clusters (job flows), instance groups and fleets, steps, security configurations, and tags are tracked in Floci's storage backend so the AWS CLI and SDK clients can drive the full cluster lifecycle locally. EMR does not launch real Hadoop/Spark clusters. Clusters transition through their lifecycle states as a state machine. In the `docker` runner mode Spark steps, commands and scripts run for real, each in a container of its own, after the cluster's bootstrap actions (see [Running steps](#running-steps)).
Floci emulates the Amazon EMR (Elastic MapReduce) management API. Clusters (job flows), instance groups and fleets, steps, Spark Connect sessions, security configurations, and tags are tracked in Floci's storage backend so the AWS CLI and SDK clients can drive the full cluster lifecycle locally. EMR does not launch real Hadoop/Spark clusters. Clusters transition through their lifecycle states as a state machine. In the `docker` runner mode Spark steps, commands and scripts run for real, each in a container of its own, after the cluster's bootstrap actions (see [Running steps](#running-steps)).
## Supported Actions
@@ -24,6 +24,11 @@ Floci emulates the Amazon EMR (Elastic MapReduce) management API. Clusters (job
| `DescribeStep` | Returns the detail and status of a single step |
| `ListSteps` | Lists the steps of a cluster, filterable by state |
| `CancelSteps` | Cancels pending steps |
| `StartSession` | Starts a Spark Connect session on a cluster with sessions enabled; see [Sessions](#sessions) |
| `GetSession` | Returns a session's state, times and configuration |
| `ListSessions` | Lists a cluster's sessions, newest first, filterable by state |
| `TerminateSession` | Terminates a session that has not ended |
| `GetSessionEndpoint` | Returns a session's endpoint and an authentication token valid for an hour |
| `AddInstanceGroups` | Adds instance groups to a running cluster |
| `ListInstanceGroups` | Lists the instance groups of a cluster |
| `AddInstanceFleet` | Adds an instance fleet to a cluster |
@@ -181,6 +186,43 @@ still accepted.
A state machine drives clusters and steps through the `elasticmapreduce:` integrations, `.sync`
included; see [Step Functions: Amazon EMR tasks](step-functions.md#amazon-emr-tasks).
## Sessions
A session is "a managed connection between your local PySpark client and a Spark Connect Server running on your Amazon
EMR cluster" (Management Guide, "Interactive sessions"). Floci keeps a session and its lifecycle on its cluster, but
starts no Spark Connect server for it, in either runner mode, so nothing answers Spark Connect at its endpoint.
* **Starting**: `StartSession` needs a cluster created with `SessionEnabled` (which `DescribeCluster` reports), on
"release emr-spark-8.0.0 or later", with "The Spark application installed on the cluster", that is `RUNNING` or
`WAITING`. A cluster with more than one primary node is refused, as "High Availability (HA) clusters with multiple
primary nodes are not supported for Spark Connect sessions", and so is a session past a cluster's 1000 that have not
ended ("Amazon EMR enforces a limit of 1000 concurrent active sessions per cluster"). A request without a `Name` is
refused, as "The `--name` parameter is required and must be a non-empty value", and so is a
`SessionIdleTimeoutInMinutes` outside 1 to 1440, as the idle timeout has "a maximum of 24 hours". Each of these
refusals is `InvalidRequestException`, the one error the model declares, in Floci's own wording, as AWS's is not
recorded. A member of the wrong JSON type, such as `EngineConfigurations` that is not a list of configurations,
`Properties` that are not strings, a `MonitoringConfiguration` member that is not a structure, or a `ClusterId`
that is not a string, is refused with `SerializationException`, and the model's length and pattern constraints with
`ValidationException`. A retry with the same `ClientRequestToken` that asks for the same session answers as the
first call did, a member left out, empty or at its default counting as the same; the token reused for a different
session is refused with `InvalidRequestException`.
* **States**: `StartSession` answers `SUBMITTED`, as "When a session is first created, it enters the SUBMITTED state",
and the session is `IDLE` from then on, with `StartedAt` and `IdleSince` its creation time. It is `TERMINATED` once
it has been idle for its `SessionIdleTimeoutInMinutes` (60 when not given: "The default timeout is 60 minutes"), when
`TerminateSession` ends it, or when its cluster shuts down, its `StateChangeReason` saying which. Floci never reports
`STARTING`, `STARTED`, `BUSY`, `TERMINATING` or `FAILED`.
* **TerminateSession** ends a session at once as `TERMINATED`; AWS's passes through `TERMINATING` first. A session that
has already ended is refused with `InvalidRequestException`, in Floci's own wording.
* **GetSessionEndpoint** answers for a session that has not ended with an endpoint on Floci's own address
(`/_aws/emr/sessions/<clusterId>/<sessionId>`) and a fresh `AuthToken` that expires in an hour, as "Authentication
tokens expire after 1 hour". Nothing answers Spark Connect there, and no `Credentials` are given. A session that has
ended is refused with `InvalidRequestException`, in Floci's own wording.
* **ListSessions** returns the newest sessions first, as "Newer sessions are returned first", the later of two started
in the same millisecond first too, filtered by `SessionStates`, at most `MaxResults` (1 to 100, 100 by default) to a
page.
* A session's `EngineConfigurations`, `MonitoringConfiguration` and `Tags` are kept as given and reported by
`GetSession`; none of them configures anything, and no session logs are written.
## Running steps
With `runner-mode` set to `docker` (`FLOCI_SERVICES_EMR_RUNNER_MODE=docker`), a step runs. Floci starts
+1 -1
View File
@@ -84,7 +84,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 65 |
| [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 12 |
| [Redshift Serverless](redshift-serverless.md) | `POST /` + `X-Amz-Target: RedshiftServerless.*` | JSON 1.1 | 58 |
| [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 40 |
| [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 45 |
| [EMR on EKS](emr-containers.md) | `/virtualclusters/*`, `/jobtemplates/*`, `/securityconfigurations/*`, `/tags/*` | REST JSON | 25 |
| [EMR Serverless](emr-serverless.md) | `/applications/*`, `/tags/*` | REST JSON | 15 |
| [Data Firehose](firehose.md) | `POST /` + `X-Amz-Target: Firehose_20150804.*` | JSON 1.1 | 12 |
@@ -0,0 +1,30 @@
package io.floci.aws.core.common;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.HexFormat;
/**
* What GetSessionEndpoint answers for a Spark Connect session, EMR Serverless's and EMR's alike: the endpoint a client
* connects to and an authentication token, with when it expires. Each call gives a new token; Floci runs no Spark
* Connect server behind the endpoint, so nothing checks one.
*/
public record SparkConnectEndpoint(String url, String authToken, Instant authTokenExpiresAt) {
private static final int TOKEN_BYTES = 32;
/**
* The endpoint at {@code path} on Floci's {@code baseUrl}, a trailing slash of which is dropped, with a new random
* token that expires {@code validity} after {@code now}.
*/
public static SparkConnectEndpoint issue(String baseUrl, String path, Instant now, Duration validity) {
String base = baseUrl == null ? "" : baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1)
: baseUrl;
byte[] token = new byte[TOKEN_BYTES];
// A SecureRandom of the call's own: one held in a static field would be built into the native image's heap,
// which its build refuses.
new SecureRandom().nextBytes(token);
return new SparkConnectEndpoint(base + path, HexFormat.of().formatHex(token), now.plus(validity));
}
}
@@ -13,11 +13,13 @@ import io.floci.aws.core.common.AwsRegions;
import io.floci.aws.core.common.JsonErrorResponseUtils;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.SmithyValidationErrors;
import io.floci.aws.core.common.SparkConnectEndpoint;
import io.floci.aws.services.emr.model.EmrBlockPublicAccess;
import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrErrorDetail;
import io.floci.aws.services.emr.model.EmrInstanceFleet;
import io.floci.aws.services.emr.model.EmrInstanceGroup;
import io.floci.aws.services.emr.model.EmrSession;
import io.floci.aws.services.emr.model.EmrStep;
import io.floci.aws.services.emr.model.SecurityConfiguration;
import jakarta.enterprise.context.ApplicationScoped;
@@ -73,6 +75,11 @@ public class EmrHandler {
case "DescribeStep" -> handleDescribeStep(request);
case "ListSteps" -> handleListSteps(request);
case "CancelSteps" -> handleCancelSteps(request);
case "StartSession" -> handleStartSession(request);
case "GetSession" -> handleGetSession(request);
case "ListSessions" -> handleListSessions(request);
case "TerminateSession" -> handleTerminateSession(request);
case "GetSessionEndpoint" -> handleGetSessionEndpoint(request);
case "AddInstanceGroups" -> handleAddInstanceGroups(request);
case "ListInstanceGroups" -> handleListInstanceGroups(request);
case "AddInstanceFleet" -> handleAddInstanceFleet(request);
@@ -160,6 +167,7 @@ public class EmrHandler {
cluster.setKeepJobFlowAliveWhenNoSteps(instances.path("KeepJobFlowAliveWhenNoSteps").asBoolean(false));
cluster.setTerminationProtected(instances.path("TerminationProtected").asBoolean(false));
cluster.setUnhealthyNodeReplacement(instances.path("UnhealthyNodeReplacement").asBoolean(false));
cluster.setSessionEnabled(request.path("SessionEnabled").asBoolean(false));
cluster.setEc2Attributes(buildEc2Attributes(instances, region));
cluster.setInstanceGroups(parseInstanceGroups(instances.path("InstanceGroups")));
cluster.setInstanceFleets(parseInstanceFleets(instances.path("InstanceFleets")));
@@ -278,6 +286,249 @@ public class EmrHandler {
return Response.ok(response).build();
}
// ──────────────────────────── Sessions ────────────────────────────
private Response handleStartSession(JsonNode request) {
EmrSessions.Request start = new EmrSessions.Request(string(request, "Name"),
string(request, "ExecutionRoleArn"), configurationList(request.path("EngineConfigurations"),
"EngineConfigurations"), monitoringConfiguration(request.path("MonitoringConfiguration")),
longOrNull(request.path("SessionIdleTimeoutInMinutes"), "SessionIdleTimeoutInMinutes"),
string(request, "ClientRequestToken"), tagList(request.path("Tags"), "Tags"));
EmrSession session = service.startSession(string(request, "ClusterId"), start);
ObjectNode response = objectMapper.createObjectNode();
response.put("Id", session.getId());
response.put("ClusterId", session.getClusterId());
response.put("Arn", session.getArn());
response.put("AccountId", session.getAccountId());
response.put("State", session.getState());
return Response.ok(response).build();
}
private Response handleGetSession(JsonNode request) {
ObjectNode response = objectMapper.createObjectNode();
response.set("Session", sessionNode(service.getSession(string(request, "ClusterId"),
string(request, "SessionId"))));
return Response.ok(response).build();
}
private Response handleListSessions(JsonNode request) {
PaginatedResult<EmrSession> page = service.listSessions(string(request, "ClusterId"),
strings(request.path("SessionStates"), "SessionStates"), intOrNull(request.path("MaxResults")),
string(request, "NextToken"));
ObjectNode response = objectMapper.createObjectNode();
ArrayNode sessions = response.putArray("Sessions");
page.items().forEach(session -> sessions.add(sessionNode(session)));
if (page.nextToken() != null) {
response.put("NextToken", page.nextToken());
}
return Response.ok(response).build();
}
private Response handleTerminateSession(JsonNode request) {
EmrSession session = service.terminateSession(string(request, "ClusterId"), string(request, "SessionId"));
ObjectNode response = objectMapper.createObjectNode();
response.put("ClusterId", session.getClusterId());
response.put("SessionId", session.getId());
response.put("State", session.getState());
return Response.ok(response).build();
}
private Response handleGetSessionEndpoint(JsonNode request) {
SparkConnectEndpoint endpoint = service.sessionEndpoint(string(request, "ClusterId"),
string(request, "SessionId"));
ObjectNode response = objectMapper.createObjectNode();
response.put("Endpoint", endpoint.url());
response.put("AuthToken", endpoint.authToken());
putEpoch(response, "AuthTokenExpirationTime", endpoint.authTokenExpiresAt());
return Response.ok(response).build();
}
private ObjectNode sessionNode(EmrSession session) {
ObjectNode node = objectMapper.createObjectNode();
node.put("Id", session.getId());
node.put("ClusterId", session.getClusterId());
if (session.getName() != null) {
node.put("Name", session.getName());
}
node.put("Arn", session.getArn());
node.put("State", session.getState());
if (session.getStateChangeReason() != null) {
node.put("StateChangeReason", session.getStateChangeReason());
}
node.put("ReleaseLabel", session.getReleaseLabel());
if (session.getExecutionRoleArn() != null) {
node.put("ExecutionRoleArn", session.getExecutionRoleArn());
}
node.put("AccountId", session.getAccountId());
putEpoch(node, "CreatedAt", session.getCreatedAt());
putEpoch(node, "UpdatedAt", session.getUpdatedAt());
putEpoch(node, "StartedAt", session.getStartedAt());
putEpoch(node, "EndedAt", session.getEndedAt());
putEpoch(node, "IdleSince", session.getIdleSince());
setRawJson(node, "EngineConfigurations", session.getEngineConfigurations());
setRawJson(node, "MonitoringConfiguration", session.getMonitoringConfiguration());
node.put("SessionIdleTimeoutInMinutes", session.getSessionIdleTimeoutInMinutes());
node.set("Tags", tagArray(session.getTags()));
return node;
}
/**
* A member a string where the model has one; another JSON type is refused with SerializationException, as an
* awsJson1_1 service refuses a member of the wrong type (Smithy's malformed-request tests), in Floci's own wording.
*/
private static String string(JsonNode request, String member) {
JsonNode value = request.path(member);
if (value.isMissingNode() || value.isNull()) {
return null;
}
if (!value.isTextual()) {
throw malformed(member + " must be a string");
}
return value.asText();
}
private static Long longOrNull(JsonNode value, String member) {
if (value.isMissingNode() || value.isNull()) {
return null;
}
if (!value.isIntegralNumber() || !value.canConvertToLong()) {
throw malformed(member + " must be an integer");
}
return value.asLong();
}
/**
* StartSession's SessionMonitoringConfiguration, kept as its raw JSON; null when it is not there or empty. Each of
* its S3, CloudWatch and managed logging configurations is a structure of an {@code Enabled} boolean, strings, and
* {@code LogTypes}, a map of lists of strings.
*/
private static String monitoringConfiguration(JsonNode value) {
String member = "MonitoringConfiguration";
if (value.isMissingNode() || value.isNull()) {
return null;
}
requireStructure(value, member);
for (String logging : List.of("S3LoggingConfiguration", "CloudWatchLoggingConfiguration",
"ManagedLoggingConfiguration")) {
JsonNode configuration = value.path(logging);
if (configuration.isMissingNode() || configuration.isNull()) {
continue;
}
String path = member + "." + logging;
requireStructure(configuration, path);
configuration.properties().forEach(entry -> {
JsonNode field = entry.getValue();
if (field.isNull()) {
return;
}
// Not a switch on the member names: the action tables read a string case here as an EMR action.
if ("Enabled".equals(entry.getKey())) {
if (!field.isBoolean()) {
throw malformed(path + ".Enabled must be a boolean");
}
} else if ("LogTypes".equals(entry.getKey())) {
requireStructure(field, path + ".LogTypes");
field.forEach(types -> strings(types, path + ".LogTypes"));
} else if (!field.isTextual()) {
throw malformed(path + "." + entry.getKey() + " must be a string");
}
});
}
return value.isEmpty() ? null : value.toString();
}
private static void requireStructure(JsonNode value, String member) {
if (!value.isObject()) {
throw malformed(member + " must be a structure");
}
}
// A list of strings; null when it is not there.
private static List<String> strings(JsonNode value, String member) {
if (value.isMissingNode() || value.isNull()) {
return null;
}
if (!value.isArray()) {
throw malformed(member + " must be a list of strings");
}
List<String> values = new ArrayList<>();
for (JsonNode element : value) {
if (!element.isTextual()) {
throw malformed(member + " must be a list of strings");
}
values.add(element.asText());
}
return values;
}
/**
* A ConfigurationList member, kept as its raw JSON; null when it is not there or empty. Each Configuration's
* {@code Classification} is a string, its {@code Properties} a map of strings, and its {@code Configurations}
* a ConfigurationList in turn.
*/
private static String configurationList(JsonNode value, String member) {
if (value.isMissingNode() || value.isNull()) {
return null;
}
checkConfigurations(value, member);
return value.isEmpty() ? null : value.toString();
}
private static void checkConfigurations(JsonNode value, String member) {
if (!value.isArray()) {
throw malformed(member + " must be a list of configurations");
}
for (JsonNode configuration : value) {
if (!configuration.isObject()) {
throw malformed(member + " must be a list of configurations");
}
JsonNode classification = configuration.path("Classification");
if (!classification.isMissingNode() && !classification.isNull() && !classification.isTextual()) {
throw malformed(member + "'s Classification must be a string");
}
JsonNode properties = configuration.path("Properties");
if (!properties.isMissingNode() && !properties.isNull()) {
if (!properties.isObject()) {
throw malformed(member + "'s Properties must be a map of strings");
}
properties.forEach(property -> {
if (!property.isTextual()) {
throw malformed(member + "'s Properties must be a map of strings");
}
});
}
JsonNode nested = configuration.path("Configurations");
if (!nested.isMissingNode() && !nested.isNull()) {
checkConfigurations(nested, member);
}
}
}
// A TagList member: each Tag's Key and Value strings.
private static Map<String, String> tagList(JsonNode value, String member) {
Map<String, String> tags = new LinkedHashMap<>();
if (value.isMissingNode() || value.isNull()) {
return tags;
}
if (!value.isArray()) {
throw malformed(member + " must be a list of tags");
}
for (JsonNode tag : value) {
if (!tag.isObject()) {
throw malformed(member + " must be a list of tags");
}
String key = string(tag, "Key");
if (key != null) {
tags.put(key, string(tag, "Value"));
}
}
return tags;
}
private static AwsException malformed(String message) {
return new AwsException("SerializationException", message, 400);
}
// ──────────────────────────── Instance groups / fleets ────────────────────────────
private Response handleAddInstanceGroups(JsonNode request) {
@@ -759,6 +1010,7 @@ public class EmrHandler {
node.put("EbsRootVolumeSize", c.getEbsRootVolumeSize());
node.put("StepConcurrencyLevel", c.getStepConcurrencyLevel());
node.put("ClusterArn", c.getClusterArn());
node.put("SessionEnabled", c.isSessionEnabled());
return node;
}
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsArnUtils;
@@ -18,6 +19,7 @@ import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.Resettable;
import io.floci.aws.core.common.SmithyValidationErrors;
import io.floci.aws.core.common.SparkConnectEndpoint;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageBackend;
@@ -31,6 +33,7 @@ import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrErrorDetail;
import io.floci.aws.services.emr.model.EmrInstanceFleet;
import io.floci.aws.services.emr.model.EmrInstanceGroup;
import io.floci.aws.services.emr.model.EmrSession;
import io.floci.aws.services.emr.model.EmrStep;
import io.floci.aws.services.emr.model.SecurityConfiguration;
import io.floci.aws.services.emrserverless.EmrServerlessSparkRunner;
@@ -51,6 +54,7 @@ import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
@@ -134,6 +138,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
private static final String KEY_SEPARATOR = "::";
private final AccountAwareStorageBackend<EmrCluster> clusterStore;
// Clusters' Spark Connect sessions, by session id.
private final AccountAwareStorageBackend<EmrSession> sessionStore;
// A security configuration is Regional: keyed by Region and name (securityConfigurationKey).
private final AccountAwareStorageBackend<SecurityConfiguration> secConfigStore;
// Block public access is an account setting per Region, so this store is keyed by Region.
@@ -209,6 +215,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
"{\"BlockPublicSecurityGroupRules\":true,"
+ "\"PermittedPublicSecurityGroupRuleRanges\":[{\"MinRange\":22,\"MaxRange\":22}]}";
private final String defaultReleaseLabel;
// Floci's own address, which GetSessionEndpoint's endpoint is on.
private final String baseUrl;
/**
* When the service next brings a cluster up to date by itself, and where it then sends the events
@@ -284,6 +292,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
Executor stepExecutor, IamService iamService) {
this.clusterStore = storageFactory.create("emr", "emr-clusters.json",
new TypeReference<Map<String, EmrCluster>>() {});
this.sessionStore = storageFactory.create("emr", "emr-sessions.json",
new TypeReference<Map<String, EmrSession>>() {});
this.secConfigStore = storageFactory.create("emr", "emr-security-configs.json",
new TypeReference<Map<String, SecurityConfiguration>>() {});
this.blockPublicAccessStore = storageFactory.create("emr", "emr-block-public-access.json",
@@ -292,6 +302,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
migrateLegacySecurityConfigurations();
this.eventPublisher = eventPublisher;
this.defaultReleaseLabel = config.services().emr().defaultReleaseLabel();
this.baseUrl = config.effectiveBaseUrl();
this.sparkRunner = sparkRunner;
this.bootstrapRunner = bootstrapRunner;
this.clusterStorage = clusterStorage;
@@ -664,6 +675,162 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
});
}
// ──────────────────────────── Sessions ────────────────────────────
/**
* Starts a Spark Connect session on the cluster ({@link EmrSessions}), or, for a retry with the same client
* request token, returns the one it started: "If you retry a request that completed successfully using the same
* client request token, the service returns the original response", which said SUBMITTED. A retry is the same
* request when it asks for the same session, whatever members it leaves at their defaults; a token reused for a
* different one is refused, in Floci's own wording, as the model declares no conflict error. The answer is a copy
* of the session, in the state StartSession reports.
*/
public EmrSession startSession(String clusterId, EmrSessions.Request request) {
EmrSessions.validate(request);
return call(() -> {
EmrCluster cluster = requireCluster(clusterId);
List<EmrSession> sessions = settledSessions(cluster);
String parameters = sessionParameters(cluster.getId(), request);
EmrSession existing = EmrSessions.startedWithToken(sessions, request.clientRequestToken());
if (existing != null) {
if (!sameRequest(existing.getRequest(), parameters)) {
throw invalid("ClientRequestToken " + request.clientRequestToken()
+ " was used with a different request.");
}
EmrSession original = sessionCopy(existing);
original.setState(EmrSessions.SUBMITTED);
return original;
}
EmrSessions.checkStartable(cluster, sessions, SNAPSHOT_MAPPER);
String id = "is-" + randomId(13);
long sequence = sessions.stream().mapToLong(EmrSession::getSequence).max().orElse(0) + 1;
EmrSession session = EmrSessions.start(cluster, request, id,
regionResolver.buildArn("elasticmapreduce", regionOf(cluster),
"cluster/" + cluster.getId() + "/session/" + id),
regionResolver.getAccountId(), now(), sequence, parameters);
sessionStore.put(id, session);
return sessionCopy(session);
});
}
public EmrSession getSession(String clusterId, String sessionId) {
return call(() -> {
EmrCluster cluster = requireCluster(clusterId);
return sessionCopy(EmrSessions.find(cluster, settledSessions(cluster), sessionId));
});
}
/**
* The cluster's sessions, "Newer sessions are returned first", filtered by {@code states}, at most
* {@code maxResults} (1 to 100) to a page. A {@code nextToken} resumes only the listing it came from.
*/
public PaginatedResult<EmrSession> listSessions(String clusterId, List<String> states, Integer maxResults,
String nextToken) {
if (maxResults != null) {
String violation = SmithyValidationErrors.outOfRange("maxResults", maxResults, 1,
EmrSessions.MAX_LIST_RESULTS);
if (violation != null) {
throw SmithyValidationErrors.validationException(violation);
}
}
EmrSessions.validateStates(states);
return call(() -> {
EmrCluster cluster = requireCluster(clusterId);
List<EmrSession> matching = settledSessions(cluster).stream()
.filter(session -> states == null || states.isEmpty() || states.contains(session.getState()))
.toList();
String namespace = String.join("|", "ListSessions", cluster.getId(),
String.valueOf(states != null ? states : List.of()));
// Newest first: the later of a cluster's sessions has the higher sequence.
PaginatedResult<EmrSession> page = Pagination.paginate(matching,
session -> String.format("%020d", Long.MAX_VALUE - session.getSequence()),
maxResults != null ? maxResults : EmrSessions.MAX_LIST_RESULTS, nextToken, namespace,
token -> invalid("Invalid NextToken."));
return new PaginatedResult<>(page.items().stream().map(EmrService::sessionCopy).toList(),
page.nextToken());
});
}
public EmrSession terminateSession(String clusterId, String sessionId) {
return call(() -> {
EmrCluster cluster = requireCluster(clusterId);
EmrSession session = EmrSessions.find(cluster, settledSessions(cluster), sessionId);
EmrSessions.terminate(session, now());
sessionStore.put(session.getId(), session);
return sessionCopy(session);
});
}
/**
* Where a client connects to a session that has not ended, with a token that expires in an hour, as
* "Authentication tokens expire after 1 hour". The endpoint is on Floci's own address, where nothing answers
* Spark Connect, as Floci runs no Spark Connect server for a session.
*/
public SparkConnectEndpoint sessionEndpoint(String clusterId, String sessionId) {
return call(() -> {
EmrCluster cluster = requireCluster(clusterId);
EmrSession session = EmrSessions.find(cluster, settledSessions(cluster), sessionId);
EmrSessions.requireNotEnded(session);
return SparkConnectEndpoint.issue(baseUrl, EmrSessions.ENDPOINT_PATH + cluster.getId() + "/"
+ session.getId(), now(), EmrSessions.TOKEN_VALIDITY);
});
}
/**
* The cluster's sessions, as stored, oldest first, once the cluster and each of them is brought up to date: kept
* apart from the cluster, so that its sessions, ended ones included, weigh on no other read or write of it.
*/
private List<EmrSession> settledSessions(EmrCluster cluster) {
settle(cluster);
Instant now = now();
List<EmrSession> sessions = sessionStore.scan(key -> true).stream()
.filter(session -> cluster.getId().equals(session.getClusterId()))
.sorted(Comparator.comparingLong(EmrSession::getSequence))
.toList();
for (EmrSession session : sessions) {
if (EmrSessions.settle(cluster, session, now)) {
sessionStore.put(session.getId(), session);
}
}
return sessions;
}
/**
* What a retry must ask for: the cluster and the session's parameters as the session would hold them, a member
* left out, given as null or empty, or at its default, alike.
*/
private static String sessionParameters(String clusterId, EmrSessions.Request request) {
ObjectNode parameters = SNAPSHOT_MAPPER.createObjectNode();
parameters.put("ClusterId", clusterId);
parameters.put("Name", request.name());
parameters.put("ExecutionRoleArn", request.executionRoleArn());
parameters.set("EngineConfigurations", rawJson(request.engineConfigurations()));
parameters.set("MonitoringConfiguration", rawJson(request.monitoringConfiguration()));
parameters.put("SessionIdleTimeoutInMinutes", request.idleTimeoutMinutes());
parameters.set("Tags", SNAPSHOT_MAPPER.valueToTree(request.tags() != null ? request.tags() : Map.of()));
return parameters.toString();
}
private static JsonNode rawJson(String json) {
if (json == null) {
return null;
}
try {
return SNAPSHOT_MAPPER.readTree(json);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Cannot read a session's stored configuration", e);
}
}
// Whether a retry's parameters are the original's, member for member whatever their order.
private static boolean sameRequest(String stored, String retried) {
return Objects.equals(rawJson(stored), rawJson(retried));
}
private static EmrSession sessionCopy(EmrSession session) {
return SNAPSHOT_MAPPER.convertValue(session, EmrSession.class);
}
// ──────────────────────────── Instance groups / fleets ────────────────────────────
public List<String> addInstanceGroups(String clusterId, List<EmrInstanceGroup> groups) {
@@ -1324,7 +1491,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
.findFirst();
}
private static AwsException invalid(String message) {
static AwsException invalid(String message) {
return new AwsException("InvalidRequestException", message, 400);
}
@@ -1453,7 +1620,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
}
/** Shutting down or ended: "A job flow that is shutting down, terminated, or finished may not be modified." */
private static boolean isShutDown(EmrCluster cluster) {
static boolean isShutDown(EmrCluster cluster) {
return EmrClusterLifecycle.TERMINATING.equals(cluster.getState())
|| EmrClusterLifecycle.isTerminated(cluster.getState());
}
@@ -0,0 +1,282 @@
package io.floci.aws.services.emr;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.SmithyValidationErrors;
import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrInstanceFleet;
import io.floci.aws.services.emr.model.EmrInstanceGroup;
import io.floci.aws.services.emr.model.EmrSession;
import io.floci.aws.services.emrserverless.EmrServerlessJobRunService;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* The rules of a cluster's Spark Connect sessions (Amazon EMR Management Guide, "Interactive sessions"): "a managed
* connection between your local PySpark client and a Spark Connect Server running on your Amazon EMR cluster". Floci
* keeps a session and its lifecycle, but starts no Spark Connect server for it: a session is SUBMITTED as StartSession
* answers, IDLE from then on, and TERMINATED when it is terminated, when its idle timeout passes, or when its cluster
* shuts down. {@link EmrService} applies them under its lock, to the sessions it keeps apart from their clusters.
*/
final class EmrSessions {
static final String SUBMITTED = "SUBMITTED";
static final String IDLE = "IDLE";
static final String TERMINATED = "TERMINATED";
static final List<String> STATES =
List.of(SUBMITTED, "STARTING", "STARTED", IDLE, "BUSY", "TERMINATING", TERMINATED, "FAILED");
private static final Set<String> ENDED = Set.of(TERMINATED, "FAILED");
// "Amazon EMR enforces a limit of 1000 concurrent active sessions per cluster."
static final int MAX_CONCURRENT_SESSIONS = 1000;
// "Sessions end after a configurable idle timeout. The default timeout is 60 minutes, with a maximum of 24 hours."
static final long DEFAULT_IDLE_TIMEOUT_MINUTES = 60;
static final long MAX_IDLE_TIMEOUT_MINUTES = Duration.ofHours(24).toMinutes();
// "Authentication tokens expire after 1 hour."
static final Duration TOKEN_VALIDITY = Duration.ofHours(1);
// ListSessions' MaxResultsNumber is 1 to 100.
static final int MAX_LIST_RESULTS = 100;
// Where GetSessionEndpoint points; nothing answers Spark Connect there, as Floci runs no server for a session.
static final String ENDPOINT_PATH = "/_aws/emr/sessions/";
private static final int MAX_NAME_LENGTH = 256;
private static final int MIN_TOKEN_LENGTH = 1;
private static final int MAX_TOKEN_LENGTH = 36;
private static final String ROLE_ARN_PATTERN =
"^arn:(aws[a-zA-Z0-9-]*):iam::(\\d{12})?:(role((\\u002F)|(\\u002F[\\u0021-\\u007F]+\\u002F))[\\w+=,.@-]+)$";
private static final int MIN_ROLE_ARN_LENGTH = 20;
private static final int MAX_ROLE_ARN_LENGTH = 2048;
private static final String SPARK = "spark";
// No source gives AWS's wording for these ends; they are Floci's.
static final String IDLE_TIMED_OUT = "The session was idle for its idle timeout.";
static final String CLUSTER_ENDED = "The session's cluster was terminated.";
static final String USER_REQUEST = "The session was terminated by request.";
private EmrSessions() {
}
/** What StartSession asks for, its configurations as raw JSON, null where it gives none. */
record Request(String name, String executionRoleArn, String engineConfigurations, String monitoringConfiguration,
Long sessionIdleTimeoutInMinutes, String clientRequestToken, Map<String, String> tags) {
/** The idle timeout the session gets: the request's, or else the default. */
long idleTimeoutMinutes() {
return sessionIdleTimeoutInMinutes != null ? sessionIdleTimeoutInMinutes : DEFAULT_IDLE_TIMEOUT_MINUTES;
}
}
/**
* Refuses a request the model's constraints refuse, with the ValidationException AWS's validation layer answers,
* and one without a name, as "The --name parameter is required and must be a non-empty value", or with an idle
* timeout outside 1 minute to 24 hours, with InvalidRequestException in Floci's own wording, as AWS's is not
* recorded.
*/
static void validate(Request request) {
List<String> violations = new ArrayList<>();
if (request.name() != null && request.name().length() > MAX_NAME_LENGTH) {
violations.add(SmithyValidationErrors.lengthOutOfRange("name", request.name(), 0, MAX_NAME_LENGTH));
}
String role = request.executionRoleArn();
if (role != null && (role.length() < MIN_ROLE_ARN_LENGTH || role.length() > MAX_ROLE_ARN_LENGTH)) {
violations.add(SmithyValidationErrors.lengthOutOfRange("executionRoleArn", role, MIN_ROLE_ARN_LENGTH,
MAX_ROLE_ARN_LENGTH));
} else if (role != null && !role.matches(ROLE_ARN_PATTERN)) {
violations.add(SmithyValidationErrors.pattern("executionRoleArn", role, ROLE_ARN_PATTERN));
}
String token = request.clientRequestToken();
if (token != null && (token.length() < MIN_TOKEN_LENGTH || token.length() > MAX_TOKEN_LENGTH)) {
violations.add(SmithyValidationErrors.lengthOutOfRange("clientRequestToken", token, MIN_TOKEN_LENGTH,
MAX_TOKEN_LENGTH));
}
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
if (request.name() == null || request.name().isBlank()) {
throw EmrService.invalid("Name is required.");
}
Long timeout = request.sessionIdleTimeoutInMinutes();
if (timeout != null && (timeout < 1 || timeout > MAX_IDLE_TIMEOUT_MINUTES)) {
throw EmrService.invalid("SessionIdleTimeoutInMinutes must be from 1 to " + MAX_IDLE_TIMEOUT_MINUTES
+ " minutes (24 hours).");
}
}
/**
* Refuses a session the cluster cannot hold: StartSession's "The cluster must be in the RUNNING or WAITING state
* and have sessions enabled", on "release emr-spark-8.0.0 or later" with "The Spark application installed on the
* cluster", not one with "multiple primary nodes", which "are not supported for Spark Connect sessions", and at
* most {@link #MAX_CONCURRENT_SESSIONS} of its {@code sessions} that have not ended. AWS's wording for each
* refusal is not recorded; InvalidRequestException is the one error the model declares for them.
*/
static void checkStartable(EmrCluster cluster, List<EmrSession> sessions, ObjectMapper objectMapper) {
if (!cluster.isSessionEnabled()) {
throw EmrService.invalid("Cluster " + cluster.getId() + " does not have sessions enabled.");
}
if (!EmrServerlessJobRunService.sparkRuntime(cluster.getReleaseLabel())) {
throw EmrService.invalid("Sessions are supported on release emr-spark-8.0.0 and later.");
}
if (!EmrSparkSteps.names(cluster.getApplications(), objectMapper, SPARK)) {
throw EmrService.invalid("Cluster " + cluster.getId() + " does not have Spark installed.");
}
if (highlyAvailable(cluster)) {
throw EmrService.invalid("Sessions are not supported on a cluster with multiple primary nodes.");
}
if (!EmrClusterLifecycle.RUNNING.equals(cluster.getState())
&& !EmrClusterLifecycle.WAITING.equals(cluster.getState())) {
throw EmrService.invalid("Cluster " + cluster.getId() + " is " + cluster.getState()
+ ", and a session needs it RUNNING or WAITING.");
}
long open = sessions.stream().filter(session -> !ENDED.contains(session.getState())).count();
if (open >= MAX_CONCURRENT_SESSIONS) {
throw EmrService.invalid("Cluster " + cluster.getId() + " already has " + MAX_CONCURRENT_SESSIONS
+ " concurrent active sessions.");
}
}
// More than one primary node: a primary instance group of more than one instance, or a primary fleet's capacity.
private static boolean highlyAvailable(EmrCluster cluster) {
for (EmrInstanceGroup group : cluster.getInstanceGroups()) {
if (EmrService.isMasterGroup(group) && group.getRequestedInstanceCount() > 1) {
return true;
}
}
for (EmrInstanceFleet fleet : cluster.getInstanceFleets()) {
if (EmrService.isMasterFleet(fleet)
&& fleet.getTargetOnDemandCapacity() + fleet.getTargetSpotCapacity() > 1) {
return true;
}
}
return false;
}
/** The one of a cluster's {@code sessions} started with the client request token, or null. */
static EmrSession startedWithToken(List<EmrSession> sessions, String clientRequestToken) {
if (clientRequestToken == null) {
return null;
}
return sessions.stream()
.filter(session -> clientRequestToken.equals(session.getClientRequestToken()))
.findFirst()
.orElse(null);
}
/**
* A new session on the cluster, SUBMITTED, as "When a session is first created, it enters the SUBMITTED state",
* the cluster's {@code sequence}th, which orders it among its sessions created within the same millisecond.
* {@code parameters} is what a retry of the request must repeat.
*/
static EmrSession start(EmrCluster cluster, Request request, String id, String arn, String accountId,
Instant now, long sequence, String parameters) {
EmrSession session = new EmrSession();
session.setId(id);
session.setClusterId(cluster.getId());
session.setSequence(sequence);
session.setName(request.name());
session.setArn(arn);
session.setState(SUBMITTED);
session.setReleaseLabel(cluster.getReleaseLabel());
session.setExecutionRoleArn(request.executionRoleArn());
session.setAccountId(accountId);
session.setCreatedAt(now);
session.setUpdatedAt(now);
session.setEngineConfigurations(request.engineConfigurations());
session.setMonitoringConfiguration(request.monitoringConfiguration());
session.setSessionIdleTimeoutInMinutes(request.idleTimeoutMinutes());
session.setTags(request.tags() != null ? new LinkedHashMap<>(request.tags()) : new LinkedHashMap<>());
session.setClientRequestToken(request.clientRequestToken());
session.setRequest(parameters);
return session;
}
/**
* Brings a session of the cluster up to {@code now}: a SUBMITTED one is IDLE from when it was made, as nothing has
* to start; an IDLE one ends once its idle timeout has passed since it went idle; and every one that has not
* ended ends as its cluster shuts down, whichever comes first. Returns whether it changed.
*/
static boolean settle(EmrCluster cluster, EmrSession session, Instant now) {
if (ENDED.contains(session.getState())) {
return false;
}
boolean changed = false;
Instant clusterEnd = EmrService.isShutDown(cluster) ? firstOf(cluster.getTerminatingDateTime(),
cluster.getEndDateTime(), now) : null;
if (SUBMITTED.equals(session.getState())
&& (clusterEnd == null || session.getCreatedAt().isBefore(clusterEnd))) {
session.setState(IDLE);
session.setStartedAt(session.getCreatedAt());
session.setIdleSince(session.getCreatedAt());
changed = true;
}
Instant idleLimit = IDLE.equals(session.getState()) && session.getIdleSince() != null
? session.getIdleSince().plus(Duration.ofMinutes(session.getSessionIdleTimeoutInMinutes())) : null;
if (idleLimit != null && !now.isBefore(idleLimit)
&& (clusterEnd == null || idleLimit.isBefore(clusterEnd))) {
end(session, IDLE_TIMED_OUT, idleLimit);
changed = true;
} else if (clusterEnd != null) {
end(session, CLUSTER_ENDED, clusterEnd);
changed = true;
}
return changed;
}
/**
* The one of a cluster's {@code sessions} with that id, or InvalidRequestException, the model's error, in Floci's
* own wording.
*/
static EmrSession find(EmrCluster cluster, List<EmrSession> sessions, String sessionId) {
if (sessionId == null) {
throw SmithyValidationErrors.validationException(SmithyValidationErrors.notNull("sessionId"));
}
return sessions.stream()
.filter(session -> sessionId.equals(session.getId()))
.findFirst()
.orElseThrow(() -> EmrService.invalid("Session " + sessionId + " does not exist on cluster "
+ cluster.getId() + "."));
}
/**
* Terminates a session that has not ended: "After you call this operation, the session enters the TERMINATING
* state and then transitions to TERMINATED." With no server to stop, Floci's is TERMINATED at once. One that has
* already ended is refused, in Floci's own wording, as AWS's answer is not recorded.
*/
static void terminate(EmrSession session, Instant now) {
requireNotEnded(session);
end(session, USER_REQUEST, now);
}
/** Refuses a session that has ended, which has nothing to connect to or terminate. */
static void requireNotEnded(EmrSession session) {
if (ENDED.contains(session.getState())) {
throw EmrService.invalid("Session " + session.getId() + " has already ended.");
}
}
/** Refuses a ListSessions' SessionStates filter naming a state the model does not. */
static void validateStates(List<String> states) {
if (states != null && !STATES.containsAll(states)) {
throw SmithyValidationErrors.validationException(
SmithyValidationErrors.notAllInEnum(states, "sessionStates", STATES));
}
}
private static void end(EmrSession session, String reason, Instant at) {
session.setState(TERMINATED);
session.setStateChangeReason(reason);
session.setEndedAt(at);
session.setUpdatedAt(at);
session.setIdleSince(null);
}
private static Instant firstOf(Instant... instants) {
for (Instant instant : instants) {
if (instant != null) {
return instant;
}
}
return null;
}
}
@@ -273,9 +273,12 @@ final class EmrSparkSteps {
// Apache Spark, which installs neither Hive, HCatalog nor Pig.
private static boolean installs(String releaseLabel, String applications, ObjectMapper objectMapper,
String... names) {
if (releaseLabel != null && EmrServerlessSparkRunner.sparkRuntime(releaseLabel)) {
return false;
}
return (releaseLabel == null || !EmrServerlessSparkRunner.sparkRuntime(releaseLabel))
&& names(applications, objectMapper, names);
}
/** Whether a cluster's stored {@code Applications} name any of {@code names}, in any case. */
static boolean names(String applications, ObjectMapper objectMapper, String... names) {
for (JsonNode application : stored(applications, objectMapper)) {
String name = application.path("Name").asText();
for (String installed : names) {
@@ -39,6 +39,8 @@ public class EmrCluster {
private boolean autoTerminate;
private boolean unhealthyNodeReplacement;
private boolean keepJobFlowAliveWhenNoSteps;
// RunJobFlow's SessionEnabled: whether the cluster takes Spark Connect sessions.
private boolean sessionEnabled;
private int normalizedInstanceHours;
private int stepConcurrencyLevel = 1;
private int ebsRootVolumeSize;
@@ -247,4 +249,7 @@ public class EmrCluster {
public List<EmrInstanceFleet> getInstanceFleets() { return instanceFleets; }
public void setInstanceFleets(List<EmrInstanceFleet> instanceFleets) { this.instanceFleets = instanceFleets; }
public boolean isSessionEnabled() { return sessionEnabled; }
public void setSessionEnabled(boolean sessionEnabled) { this.sessionEnabled = sessionEnabled; }
}
@@ -0,0 +1,90 @@
package io.floci.aws.services.emr.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* A Spark Connect session on a cluster, as GetSession reports it, plus what only Floci needs: its place among its
* cluster's sessions, and the client request token and the parameters it was started with, which decide whether a
* repeated StartSession is a retry. Its engine and monitoring configurations are kept as the request's raw JSON.
*/
@RegisterForReflection
public class EmrSession {
private String id;
private String clusterId;
// Its place among its cluster's sessions, 1 for the first: the newer of two made in the same millisecond is later.
private long sequence;
private String name;
private String arn;
private String state;
private String stateChangeReason;
private String releaseLabel;
private String executionRoleArn;
private String accountId;
private Instant createdAt;
private Instant updatedAt;
private Instant startedAt;
private Instant endedAt;
private Instant idleSince;
private String engineConfigurations;
private String monitoringConfiguration;
private long sessionIdleTimeoutInMinutes;
private Map<String, String> tags = new LinkedHashMap<>();
private String clientRequestToken;
private String request;
public EmrSession() {}
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getClusterId() { return clusterId; }
public void setClusterId(String clusterId) { this.clusterId = clusterId; }
public long getSequence() { return sequence; }
public void setSequence(long sequence) { this.sequence = sequence; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
public String getState() { return state; }
public void setState(String state) { this.state = state; }
public String getStateChangeReason() { return stateChangeReason; }
public void setStateChangeReason(String stateChangeReason) { this.stateChangeReason = stateChangeReason; }
public String getReleaseLabel() { return releaseLabel; }
public void setReleaseLabel(String releaseLabel) { this.releaseLabel = releaseLabel; }
public String getExecutionRoleArn() { return executionRoleArn; }
public void setExecutionRoleArn(String executionRoleArn) { this.executionRoleArn = executionRoleArn; }
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
public Instant getCreatedAt() { return createdAt; }
public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
public Instant getUpdatedAt() { return updatedAt; }
public void setUpdatedAt(Instant updatedAt) { this.updatedAt = updatedAt; }
public Instant getStartedAt() { return startedAt; }
public void setStartedAt(Instant startedAt) { this.startedAt = startedAt; }
public Instant getEndedAt() { return endedAt; }
public void setEndedAt(Instant endedAt) { this.endedAt = endedAt; }
public Instant getIdleSince() { return idleSince; }
public void setIdleSince(Instant idleSince) { this.idleSince = idleSince; }
public String getEngineConfigurations() { return engineConfigurations; }
public void setEngineConfigurations(String engineConfigurations) {
this.engineConfigurations = engineConfigurations;
}
public String getMonitoringConfiguration() { return monitoringConfiguration; }
public void setMonitoringConfiguration(String monitoringConfiguration) {
this.monitoringConfiguration = monitoringConfiguration;
}
public long getSessionIdleTimeoutInMinutes() { return sessionIdleTimeoutInMinutes; }
public void setSessionIdleTimeoutInMinutes(long sessionIdleTimeoutInMinutes) {
this.sessionIdleTimeoutInMinutes = sessionIdleTimeoutInMinutes;
}
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
public String getClientRequestToken() { return clientRequestToken; }
public void setClientRequestToken(String clientRequestToken) { this.clientRequestToken = clientRequestToken; }
public String getRequest() { return request; }
public void setRequest(String request) { this.request = request; }
}
@@ -3,6 +3,7 @@ package io.floci.aws.services.emrserverless;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.SparkConnectEndpoint;
import io.floci.aws.services.emrserverless.model.Application;
import io.floci.aws.services.emrserverless.model.ApplicationSummary;
import io.floci.aws.services.emrserverless.model.CancelJobRunResponse;
@@ -282,7 +283,7 @@ public class EmrServerlessController {
@Path("/{applicationId}/sessions/{sessionId}/endpoint")
public GetSessionEndpointResponse getSessionEndpoint(@PathParam("applicationId") String applicationId,
@PathParam("sessionId") String sessionId) {
EmrServerlessSessionService.Endpoint endpoint = sessions.sessionEndpoint(applicationId, sessionId);
SparkConnectEndpoint endpoint = sessions.sessionEndpoint(applicationId, sessionId);
GetSessionEndpointResponse response = new GetSessionEndpointResponse();
response.setApplicationId(applicationId);
response.setSessionId(sessionId);
@@ -1353,9 +1353,11 @@ public class EmrServerlessJobRunService implements Resettable {
return releaseAtLeast(RELEASE_LABEL, releaseLabel, 7, 11) || sparkRuntime(releaseLabel);
}
// A release of the AWS runtime for Apache Spark, which starts at emr-spark-8.0-preview and comes after EMR
// Serverless 7.14.0 in the release list.
static boolean sparkRuntime(String releaseLabel) {
/**
* Whether {@code releaseLabel} is a release of the AWS runtime for Apache Spark, emr-spark-8.0 or later, which
* starts at emr-spark-8.0-preview and comes after EMR Serverless 7.14.0 in the release list.
*/
public static boolean sparkRuntime(String releaseLabel) {
return releaseAtLeast(SPARK_RUNTIME_RELEASE_LABEL, releaseLabel, 8, 0);
}
@@ -10,6 +10,7 @@ import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestContext;
import io.floci.aws.core.common.SmithyValidationErrors;
import io.floci.aws.core.common.SparkConnectEndpoint;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.emrserverless.model.Application;
@@ -22,13 +23,11 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -65,7 +64,6 @@ public class EmrServerlessSessionService {
static final Duration HARD_LIMIT = Duration.ofHours(24);
// "Authentication tokens are time-limited to 1 hour."
static final Duration TOKEN_VALIDITY = Duration.ofHours(1);
private static final int TOKEN_BYTES = 32;
// Where GetSessionEndpoint points; nothing answers Spark Connect there, as Floci runs no driver for a session.
static final String ENDPOINT_PATH = "/_aws/emr-serverless/sessions/";
private static final String SPARK_TYPE = "SPARK";
@@ -83,7 +81,6 @@ public class EmrServerlessSessionService {
private final ObjectMapper objectMapper;
private final Clock clock;
private final String baseUrl;
private final SecureRandom random = new SecureRandom();
@Inject
public EmrServerlessSessionService(StorageFactory storageFactory, EmrServerlessService applications,
@@ -107,7 +104,7 @@ public class EmrServerlessSessionService {
this.requestContext = requestContext;
this.objectMapper = objectMapper;
this.clock = clock;
this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
this.baseUrl = baseUrl;
}
/**
@@ -201,20 +198,14 @@ public class EmrServerlessSessionService {
* to 1 hour". The endpoint is on Floci's own address, where nothing answers Spark Connect, as Floci runs no driver
* for a session. No source gives AWS's answer for a session that has ended, so the refusal's wording is Floci's.
*/
public synchronized Endpoint sessionEndpoint(String applicationId, String sessionId) {
public synchronized SparkConnectEndpoint sessionEndpoint(String applicationId, String sessionId) {
applications.getApplication(applicationId);
Session session = settle(findSession(applicationId, sessionId)).getSession();
if (ENDED.contains(session.getState())) {
throw new AwsException("ValidationException", "Session " + sessionId + " has ended.", 400);
}
byte[] token = new byte[TOKEN_BYTES];
random.nextBytes(token);
return new Endpoint(baseUrl + ENDPOINT_PATH + applicationId + "/" + sessionId,
HexFormat.of().formatHex(token), now().plus(TOKEN_VALIDITY));
}
/** GetSessionEndpoint's endpoint, its token and when the token expires. */
public record Endpoint(String url, String authToken, Instant authTokenExpiresAt) {
return SparkConnectEndpoint.issue(baseUrl, ENDPOINT_PATH + applicationId + "/" + sessionId, now(),
TOKEN_VALIDITY);
}
/**
@@ -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);
}
}
@@ -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());