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,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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user