mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(emr-serverless): list same-millisecond runs and sessions newest first, and compare retries as held (#8735)
ListJobRuns and ListSessions ordered runs and sessions by their creation millisecond, breaking a tie by the random id, so of two started within the same millisecond the newer could list second. Each stored run and session now keeps a creation sequence, the microseconds of its creation or one past the latest its service gave, which the listing breaks a tie by. One stored before keeps 0, and its id orders it, as before. A nextToken given before, whose cursor holds no sequence, is refused with "Invalid nextToken." rather than resuming at the wrong place. A StartJobRun or StartSession retry was compared with the original as raw request JSON, so one that left out a member the first gave at its default, or empty, was refused with ConflictException. The two are now compared as the run or session each would start holds them, built by the same code that starts one: a run's execution timeout left out or 720, a session's idle timeout left out or 60, tags left out or empty, and a session's configurationOverrides without a runtimeConfiguration count as the same. Anything the run would hold otherwise still conflicts, a mode given where the original left it out, a tag with an empty value or another name among them. Classic EMR sessions compare their retries as held since #8699.
This commit is contained in:
1 parent
83c64f5d91
commit
1a26ef4f73
8 files changed
+264
-43
No files matched your search
@@ -3,6 +3,7 @@ package io.floci.aws.services.emrserverless;
|
||||
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 io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
@@ -179,6 +180,8 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
private final Set<String> executing = new HashSet<>();
|
||||
// Raised by each reset, so a run's thread from before it writes nothing back after the wipe.
|
||||
private long generation;
|
||||
// The latest sequence a run was given, nextSequence.
|
||||
private long lastSequence;
|
||||
|
||||
@Inject
|
||||
public EmrServerlessJobRunService(StorageFactory storageFactory, EmrServerlessService applications,
|
||||
@@ -282,7 +285,7 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
JobRunRecord existing = EmrServerlessService.startedWithClientToken(store.scan(key -> true),
|
||||
body.getClientToken(), JobRunRecord::getClientToken, record -> inRequestRegion(record.getJobRun()));
|
||||
if (existing != null) {
|
||||
if (!original.equals(existing.getRequest())) {
|
||||
if (!sameRun(existing.getRequest(), applicationId, body)) {
|
||||
throw new AwsException("ConflictException", "Request did not match the original", 409);
|
||||
}
|
||||
return settle(existing).getJobRun();
|
||||
@@ -411,8 +414,8 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
String.valueOf(createdAtBefore), String.valueOf(mode));
|
||||
PaginatedResult<JobRunRecord> page = EmrServerlessService.pageByState(matching,
|
||||
record -> record.getJobRun().getJobRunId(), record -> record.getJobRun().getState(),
|
||||
record -> record.getJobRun().getCreatedAt(), states, maxResults, MAX_LIST_RESULTS, nextToken,
|
||||
namespace);
|
||||
record -> record.getJobRun().getCreatedAt(), JobRunRecord::getSequence, states, maxResults,
|
||||
MAX_LIST_RESULTS, nextToken, namespace);
|
||||
return new PaginatedResult<>(page.items().stream().map(EmrServerlessJobRunService::toSummary).toList(),
|
||||
page.nextToken());
|
||||
}
|
||||
@@ -508,6 +511,50 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets on {@code run} what a run takes from the request that starts it, as it holds it: its name, role, policy,
|
||||
* configuration overrides, driver, tags (none where the request gives none), execution timeout
|
||||
* ({@value #DEFAULT_EXECUTION_TIMEOUT_MINUTES} minutes where it gives none), mode and retry policy.
|
||||
*/
|
||||
private static void requested(JobRun run, StartJobRunRequest request) {
|
||||
run.setName(request.getName());
|
||||
run.setExecutionRole(request.getExecutionRoleArn());
|
||||
run.setExecutionIamPolicy(request.getExecutionIamPolicy());
|
||||
run.setConfigurationOverrides(request.getConfigurationOverrides());
|
||||
run.setJobDriver(request.getJobDriver());
|
||||
run.setTags(request.getTags() != null ? new LinkedHashMap<>(request.getTags()) : new LinkedHashMap<>());
|
||||
run.setExecutionTimeoutMinutes(request.getExecutionTimeoutMinutes() != null
|
||||
? request.getExecutionTimeoutMinutes() : DEFAULT_EXECUTION_TIMEOUT_MINUTES);
|
||||
run.setMode(request.getMode());
|
||||
run.setRetryPolicy(request.getRetryPolicy());
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a retry asks for the run its original started: on the same application, with what the two would have
|
||||
* the run hold alike, {@link #requested}. A member the run holds the same way whether it is left out or given,
|
||||
* the execution timeout at its default or the tags empty, is alike; one the run would hold otherwise, such as a
|
||||
* mode given where the original left it out, is not.
|
||||
*/
|
||||
private boolean sameRun(JsonNode original, String applicationId, StartJobRunRequest retried) {
|
||||
ObjectNode first = ((ObjectNode) original).deepCopy();
|
||||
String firstApplication = first.path("applicationId").asText(null);
|
||||
first.remove("applicationId");
|
||||
return applicationId.equals(firstApplication)
|
||||
&& held(objectMapper.convertValue(first, StartJobRunRequest.class)).equals(held(retried));
|
||||
}
|
||||
|
||||
private JsonNode held(StartJobRunRequest request) {
|
||||
JobRun run = new JobRun();
|
||||
requested(run, request);
|
||||
return objectMapper.valueToTree(run);
|
||||
}
|
||||
|
||||
// The sequence of a run created at now, after the last this service gave.
|
||||
private long nextSequence(Instant now) {
|
||||
lastSequence = EmrServerlessService.nextSequence(lastSequence, now);
|
||||
return lastSequence;
|
||||
}
|
||||
|
||||
private JobRunRecord newRun(Application app, StartJobRunRequest request, JsonNode original) {
|
||||
AwsArnUtils.Arn applicationArn = AwsArnUtils.parse(app.getArn());
|
||||
String jobRunId = EmrServerlessService.newId();
|
||||
@@ -516,26 +563,17 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
JobRun run = new JobRun();
|
||||
run.setApplicationId(app.getApplicationId());
|
||||
run.setJobRunId(jobRunId);
|
||||
run.setName(request.getName());
|
||||
run.setArn(AwsArnUtils.Arn.of("emr-serverless", applicationArn.region(), applicationArn.accountId(),
|
||||
applicationArn.resource() + "/jobruns/" + jobRunId).toString());
|
||||
run.setCreatedBy(EmrServerlessService.createdBy(iamService, requestContext, regionResolver,
|
||||
applicationArn.accountId()));
|
||||
run.setCreatedAt(now);
|
||||
run.setUpdatedAt(now);
|
||||
run.setExecutionRole(request.getExecutionRoleArn());
|
||||
run.setExecutionIamPolicy(request.getExecutionIamPolicy());
|
||||
requested(run, request);
|
||||
run.setState(sparkRunner != null ? STATE_SCHEDULED : STATE_RUNNING);
|
||||
run.setStateDetails("");
|
||||
run.setReleaseLabel(app.getReleaseLabel());
|
||||
run.setConfigurationOverrides(request.getConfigurationOverrides());
|
||||
run.setJobDriver(request.getJobDriver());
|
||||
run.setTags(request.getTags() != null ? new LinkedHashMap<>(request.getTags()) : new LinkedHashMap<>());
|
||||
run.setNetworkConfiguration(app.getNetworkConfiguration());
|
||||
run.setExecutionTimeoutMinutes(request.getExecutionTimeoutMinutes() != null
|
||||
? request.getExecutionTimeoutMinutes() : DEFAULT_EXECUTION_TIMEOUT_MINUTES);
|
||||
run.setMode(request.getMode());
|
||||
run.setRetryPolicy(request.getRetryPolicy());
|
||||
run.setAttempt(FIRST_ATTEMPT);
|
||||
run.setAttemptCreatedAt(now);
|
||||
run.setAttemptUpdatedAt(now);
|
||||
@@ -546,6 +584,7 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
|
||||
JobRunRecord record = new JobRunRecord();
|
||||
record.setJobRun(run);
|
||||
record.setSequence(nextSequence(now));
|
||||
record.setClientToken(request.getClientToken());
|
||||
record.setRequest(original);
|
||||
record.setApplicationType(app.getType());
|
||||
|
||||
@@ -46,6 +46,7 @@ import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.ToLongFunction;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -645,22 +646,30 @@ public class EmrServerlessService {
|
||||
return violations;
|
||||
}
|
||||
|
||||
// The shape of pageByState's cursors, which a nextToken names: the state group, the creation time, the sequence.
|
||||
private static final String CURSOR_SHAPE = "group-created-sequence";
|
||||
|
||||
/**
|
||||
* A page of ListJobRuns' runs or ListSessions' sessions: {@code matching}, newest first, and, where {@code states}
|
||||
* names any, "grouped by the state", in the order it names them, as each operation's {@code states} member reads.
|
||||
* A {@code nextToken} resumes only the listing {@code namespace} names.
|
||||
* Of two created within the same millisecond, the later {@code sequence}, {@link #nextSequence}, is the newer; one
|
||||
* stored before sequences were kept has 0, and its id orders it among those. A {@code nextToken} resumes only the
|
||||
* listing {@code namespace} names, in this cursor's shape: one given before sequences were kept, whose cursors
|
||||
* hold none, is refused rather than resuming at the wrong place.
|
||||
*/
|
||||
static <T> PaginatedResult<T> pageByState(List<T> matching, Function<T, String> id, Function<T, String> state,
|
||||
Function<T, Instant> createdAt, List<String> states, Integer maxResults,
|
||||
int defaultMaxResults, String nextToken, String namespace) {
|
||||
Function<T, Instant> createdAt, ToLongFunction<T> sequence,
|
||||
List<String> states, Integer maxResults, int defaultMaxResults,
|
||||
String nextToken, String namespace) {
|
||||
Map<String, String> cursors = new HashMap<>();
|
||||
for (T item : matching) {
|
||||
int group = states == null || states.isEmpty() ? 0 : states.indexOf(state.apply(item));
|
||||
cursors.put(id.apply(item), String.format("%02d%020d%s", group,
|
||||
Long.MAX_VALUE - createdAt.apply(item).toEpochMilli(), id.apply(item)));
|
||||
cursors.put(id.apply(item), String.format("%02d%020d%020d%s", group,
|
||||
Long.MAX_VALUE - createdAt.apply(item).toEpochMilli(),
|
||||
Long.MAX_VALUE - sequence.applyAsLong(item), id.apply(item)));
|
||||
}
|
||||
return Pagination.paginate(matching, item -> cursors.get(id.apply(item)),
|
||||
maxResults != null ? maxResults : defaultMaxResults, nextToken, namespace,
|
||||
maxResults != null ? maxResults : defaultMaxResults, nextToken, namespace + "|" + CURSOR_SHAPE,
|
||||
token -> new AwsException("ValidationException", "Invalid nextToken.", 400));
|
||||
}
|
||||
|
||||
@@ -785,6 +794,17 @@ public class EmrServerlessService {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The sequence of a run or session created at {@code now}, after {@code last}, the latest its service gave: the
|
||||
* microseconds of {@code now}, or one past {@code last} when that is not later. It orders the run after every one
|
||||
* created before it, within the same millisecond too; one an earlier Floci process created has a sequence below
|
||||
* {@code now}'s microseconds, the clock having moved on since, so none is reused.
|
||||
*/
|
||||
static long nextSequence(long last, Instant now) {
|
||||
long micros = now.getEpochSecond() * 1_000_000L + now.getNano() / 1_000;
|
||||
return Math.max(micros, last + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* What a retry of StartJobRun or StartSession must repeat: the application and every member of the body but
|
||||
* the client token itself. Read back from its JSON text, so that its numbers compare equal to those of a stored
|
||||
|
||||
+52
-17
@@ -3,6 +3,7 @@ package io.floci.aws.services.emrserverless;
|
||||
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 io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
@@ -132,6 +133,8 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta
|
||||
private final Map<String, Grant> grants = new ConcurrentHashMap<>();
|
||||
// Raised by each reset, so a server's thread from before it writes nothing back after the wipe.
|
||||
private long generation;
|
||||
// The latest sequence a session was given, EmrServerlessService.nextSequence.
|
||||
private long lastSequence;
|
||||
|
||||
@Inject
|
||||
public EmrServerlessSessionService(StorageFactory storageFactory, EmrServerlessService applications,
|
||||
@@ -217,7 +220,7 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta
|
||||
SessionRecord existing = EmrServerlessService.startedWithClientToken(store.scan(key -> true),
|
||||
body.getClientToken(), SessionRecord::getClientToken, record -> inRequestRegion(record.getSession()));
|
||||
if (existing != null) {
|
||||
if (!original.equals(existing.getRequest())) {
|
||||
if (!sameSession(existing.getRequest(), applicationId, body)) {
|
||||
throw new AwsException("ConflictException", "Request did not match the original", 409);
|
||||
}
|
||||
return copy(settle(existing).getSession());
|
||||
@@ -250,7 +253,7 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta
|
||||
throw SmithyValidationErrors.validationException(violations);
|
||||
}
|
||||
applications.getApplication(applicationId);
|
||||
List<Session> matching = new ArrayList<>();
|
||||
List<SessionRecord> matching = new ArrayList<>();
|
||||
for (SessionRecord record : store.scan(key -> true)) {
|
||||
Session session = record.getSession();
|
||||
if (!applicationId.equals(session.getApplicationId()) || !inRequestRegion(session)) {
|
||||
@@ -262,14 +265,17 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta
|
||||
|| (createdAtBefore != null && !session.getCreatedAt().isBefore(createdAtBefore))) {
|
||||
continue;
|
||||
}
|
||||
matching.add(session);
|
||||
matching.add(record);
|
||||
}
|
||||
String namespace = String.join("|", "ListSessions", applicationId,
|
||||
String.valueOf(states != null ? states : List.of()), String.valueOf(createdAtAfter),
|
||||
String.valueOf(createdAtBefore));
|
||||
PaginatedResult<Session> page = EmrServerlessService.pageByState(matching, Session::getSessionId,
|
||||
Session::getState, Session::getCreatedAt, states, maxResults, MAX_LIST_RESULTS, nextToken, namespace);
|
||||
return new PaginatedResult<>(page.items().stream().map(SessionSummary::of).toList(), page.nextToken());
|
||||
PaginatedResult<SessionRecord> page = EmrServerlessService.pageByState(matching,
|
||||
record -> record.getSession().getSessionId(), record -> record.getSession().getState(),
|
||||
record -> record.getSession().getCreatedAt(), SessionRecord::getSequence, states, maxResults,
|
||||
MAX_LIST_RESULTS, nextToken, namespace);
|
||||
return new PaginatedResult<>(page.items().stream().map(record -> SessionSummary.of(record.getSession()))
|
||||
.toList(), page.nextToken());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -569,10 +575,9 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta
|
||||
session.setSessionId(sessionId);
|
||||
session.setArn(AwsArnUtils.Arn.of("emr-serverless", applicationArn.region(), applicationArn.accountId(),
|
||||
applicationArn.resource() + "/sessions/" + sessionId).toString());
|
||||
session.setName(request.getName());
|
||||
requested(session, request);
|
||||
session.setStateDetails("");
|
||||
session.setReleaseLabel(app.getReleaseLabel());
|
||||
session.setExecutionRoleArn(request.getExecutionRoleArn());
|
||||
session.setCreatedBy(EmrServerlessService.createdBy(iamService, requestContext, regionResolver,
|
||||
applicationArn.accountId()));
|
||||
session.setCreatedAt(now);
|
||||
@@ -585,19 +590,12 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta
|
||||
} else {
|
||||
session.setState(STATE_SUBMITTED);
|
||||
}
|
||||
// "Only runtime configuration overrides are supported."
|
||||
if (request.getConfigurationOverrides() != null
|
||||
&& request.getConfigurationOverrides().get("runtimeConfiguration") != null) {
|
||||
session.setConfigurationOverrides(Map.of("runtimeConfiguration",
|
||||
request.getConfigurationOverrides().get("runtimeConfiguration")));
|
||||
}
|
||||
session.setNetworkConfiguration(app.getNetworkConfiguration());
|
||||
session.setIdleTimeoutMinutes(request.getIdleTimeoutMinutes() != null
|
||||
? request.getIdleTimeoutMinutes() : DEFAULT_IDLE_TIMEOUT_MINUTES);
|
||||
session.setTags(request.getTags() != null ? new LinkedHashMap<>(request.getTags()) : new LinkedHashMap<>());
|
||||
|
||||
SessionRecord record = new SessionRecord();
|
||||
record.setSession(session);
|
||||
lastSequence = EmrServerlessService.nextSequence(lastSequence, now);
|
||||
record.setSequence(lastSequence);
|
||||
record.setClientToken(request.getClientToken());
|
||||
record.setRequest(original);
|
||||
record.setContainerSession(sparkRunner != null);
|
||||
@@ -818,6 +816,43 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets on {@code session} what a session takes from the request that starts it, as it holds it: its name, role,
|
||||
* runtime configuration overrides alone, as "Only runtime configuration overrides are supported", idle timeout
|
||||
* ({@value #DEFAULT_IDLE_TIMEOUT_MINUTES} minutes where the request gives none) and tags (none where it gives
|
||||
* none).
|
||||
*/
|
||||
private static void requested(Session session, StartSessionRequest request) {
|
||||
session.setName(request.getName());
|
||||
session.setExecutionRoleArn(request.getExecutionRoleArn());
|
||||
if (request.getConfigurationOverrides() != null
|
||||
&& request.getConfigurationOverrides().get("runtimeConfiguration") != null) {
|
||||
session.setConfigurationOverrides(Map.of("runtimeConfiguration",
|
||||
request.getConfigurationOverrides().get("runtimeConfiguration")));
|
||||
}
|
||||
session.setIdleTimeoutMinutes(request.getIdleTimeoutMinutes() != null
|
||||
? request.getIdleTimeoutMinutes() : DEFAULT_IDLE_TIMEOUT_MINUTES);
|
||||
session.setTags(request.getTags() != null ? new LinkedHashMap<>(request.getTags()) : new LinkedHashMap<>());
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a retry asks for the session its original started: on the same application, with what the two would
|
||||
* have the session hold alike, {@link #requested}, as a job run's retry is compared.
|
||||
*/
|
||||
private boolean sameSession(JsonNode original, String applicationId, StartSessionRequest retried) {
|
||||
ObjectNode first = ((ObjectNode) original).deepCopy();
|
||||
String firstApplication = first.path("applicationId").asText(null);
|
||||
first.remove("applicationId");
|
||||
return applicationId.equals(firstApplication)
|
||||
&& held(objectMapper.convertValue(first, StartSessionRequest.class)).equals(held(retried));
|
||||
}
|
||||
|
||||
private JsonNode held(StartSessionRequest request) {
|
||||
Session session = new Session();
|
||||
requested(session, request);
|
||||
return objectMapper.valueToTree(session);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends a session whose time has run out by now: an idle one once its idle timeout has passed since it went idle,
|
||||
* and any once its 24 hours have passed since it started, whichever comes first. An idle timeout of 0 ends
|
||||
|
||||
@@ -20,6 +20,8 @@ import java.util.Map;
|
||||
public class JobRunRecord {
|
||||
private JobRun jobRun;
|
||||
private String clientToken;
|
||||
// Orders it among those created within the same millisecond: EmrServerlessService.nextSequence.
|
||||
private long sequence;
|
||||
private JsonNode request;
|
||||
private String applicationType;
|
||||
private boolean containerRun;
|
||||
@@ -30,6 +32,8 @@ public class JobRunRecord {
|
||||
public void setJobRun(JobRun jobRun) { this.jobRun = jobRun; }
|
||||
public String getClientToken() { return clientToken; }
|
||||
public void setClientToken(String clientToken) { this.clientToken = clientToken; }
|
||||
public long getSequence() { return sequence; }
|
||||
public void setSequence(long sequence) { this.sequence = sequence; }
|
||||
public JsonNode getRequest() { return request; }
|
||||
public void setRequest(JsonNode request) { this.request = request; }
|
||||
public String getApplicationType() { return applicationType; }
|
||||
|
||||
@@ -11,6 +11,8 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
public class SessionRecord {
|
||||
private Session session;
|
||||
private String clientToken;
|
||||
// Orders it among those created within the same millisecond: EmrServerlessService.nextSequence.
|
||||
private long sequence;
|
||||
private JsonNode request;
|
||||
// Whether Floci runs a Spark Connect server for it, as it does in the docker runner mode.
|
||||
private boolean containerSession;
|
||||
@@ -19,6 +21,8 @@ public class SessionRecord {
|
||||
public void setSession(Session session) { this.session = session; }
|
||||
public String getClientToken() { return clientToken; }
|
||||
public void setClientToken(String clientToken) { this.clientToken = clientToken; }
|
||||
public long getSequence() { return sequence; }
|
||||
public void setSequence(long sequence) { this.sequence = sequence; }
|
||||
public JsonNode getRequest() { return request; }
|
||||
public void setRequest(JsonNode request) { this.request = request; }
|
||||
public boolean isContainerSession() { return containerSession; }
|
||||
|
||||
Reference in new issue
Block a user