feat(emr): keep notebook executions on a cluster (#8705)

EMR's notebook execution operations, StartNotebookExecution,
DescribeNotebookExecution, StopNotebookExecution and
ListNotebookExecutions, were not served.

Floci now keeps notebook executions and their lifecycle, without running
a notebook. An execution needs a RUNNING or WAITING cluster that meets
the EMR Notebooks cluster requirements (release 5.18.0 or later, with
Hadoop, Spark and Livy, and Jupyter Enterprise Gateway from 5.32.0 or
6.2.0), and an account runs at most 100 at once in a Region. It is
RUNNING from its start and FINISHED once the cluster's step duration has
passed, with AWS's "Execution is finished for cluster ..."; it stops at
once as STOPPED, and FAILS when its cluster shuts down first or after 30
days. ListNotebookExecutions gives the newest first, within its From and
To window (by default the last 30 days), 50 to a page. Executions are
stored apart from their clusters, and IAM's resource-tag conditions read
their tags.

EMR's release comparison, its enum check, the time a cluster began to
shut down, and reading an ARN's id and a resource's tags for IAM are
now shared helpers, which CancelSteps, sessions, Studios and clusters
use too.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-17 01:29:07 -04:00
1 parent a00b091da2
commit e0ef191767
12 files changed
+1036 -58

No files matched your search

+33 -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, Spark Connect sessions, EMR Studios and their session mappings, 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, EMR Studios and their session mappings, notebook executions, 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
@@ -39,6 +39,10 @@ Floci emulates the Amazon EMR (Elastic MapReduce) management API. Clusters (job
| `ListStudioSessionMappings` | Lists the session mappings of a Studio, or of every Studio |
| `UpdateStudioSessionMapping` | Changes a mapped user's or group's session policy |
| `DeleteStudioSessionMapping` | Removes a user or group from a Studio |
| `StartNotebookExecution` | Starts a notebook execution on a cluster; see [Notebook executions](#notebook-executions) |
| `DescribeNotebookExecution` | Returns a notebook execution's status, times and configuration |
| `StopNotebookExecution` | Stops a notebook execution that has not ended |
| `ListNotebookExecutions` | Lists notebook executions, newest first, by editor, status, time and cluster |
| `AddInstanceGroups` | Adds instance groups to a running cluster |
| `ListInstanceGroups` | Lists the instance groups of a cluster |
| `AddInstanceFleet` | Adds an instance fleet to a cluster |
@@ -266,6 +270,34 @@ nothing answers.
user or group has since been deleted can still be removed. The `SessionPolicyArn` is kept as given. `ListStudioSessionMappings` lists a Studio's mappings, or every
Studio's when it names none, filtered by `IdentityType`, in the order they were made, 50 to a page.
## Notebook executions
Floci keeps a notebook execution and its lifecycle, but runs no notebook, in either runner mode, and writes no output
notebook.
* **StartNotebookExecution** refuses a request without `ExecutionEngine.Id` or `ServiceRole`, or with an
`ExecutionEngine.Type` or `OutputNotebookFormat` the model does not name, with `ValidationException`, and a member of
the wrong JSON type with `SerializationException`. The cluster must be `RUNNING` or `WAITING` and meet the EMR
Notebooks cluster requirements: "Only clusters created using Amazon EMR release version 5.18.0 and later are
supported", "The cluster must be launched with Hadoop, Spark, and Livy" and, "For Amazon EMR release versions
5.32.0 and later, or 6.2.0 and later", Jupyter Enterprise Gateway too (the AWS runtime for Apache Spark's releases
name no Hadoop among their applications). An account runs at most 100 executions that have not ended in a Region,
as "A maximum of 100 concurrent executions are supported per AWS Region per account". A blank `ServiceRole` is
refused too. Each of these refusals is
`InvalidRequestException` in Floci's own wording. The editor, relative path, S3 locations and parameters are kept as
given. The execution's id is `ex-` and 29 letters and digits, and its `ExecutionEngine.Type` is `EMR` unless given.
IAM's `aws:ResourceTag` conditions read its tags.
* **States**: an execution is `START_PENDING` as it starts, `RUNNING` from then on, and `FINISHED` once the cluster's
`step-duration-seconds` has passed (at once by default), with AWS's "Execution is finished for cluster ...". It is
`FAILED` if its cluster shuts down first, or once it has run 30 days, as "An execution is terminated if it runs for
more than 30 days", in Floci's own wording.
* **StopNotebookExecution** stops one that has not ended at once, `STOPPED` with AWS's "Execution is stopped for
cluster ...". One that has ended is refused with `InvalidRequestException`, in Floci's own wording.
* **ListNotebookExecutions** lists the Region's executions that started from `From` (by default 30 days ago) to
`To` (by default now), filtered by `EditorId`, `Status` and `ExecutionEngineId`, newest first, at most 50 to a page
("Returns a maximum of 50 notebook executions") after a `Marker`, which resumes only the listing it came from: the
same account, Region and filters.
## 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 | 55 |
| [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 59 |
| [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 |
@@ -19,6 +19,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.EmrNotebookExecution;
import io.floci.aws.services.emr.model.EmrSession;
import io.floci.aws.services.emr.model.EmrStep;
import io.floci.aws.services.emr.model.EmrStudio;
@@ -53,12 +54,15 @@ public class EmrHandler {
private final EmrService service;
private final EmrStudioService studios;
private final EmrNotebookExecutionService notebookExecutions;
private final ObjectMapper objectMapper;
@Inject
public EmrHandler(EmrService service, EmrStudioService studios, ObjectMapper objectMapper) {
public EmrHandler(EmrService service, EmrStudioService studios, EmrNotebookExecutionService notebookExecutions,
ObjectMapper objectMapper) {
this.service = service;
this.studios = studios;
this.notebookExecutions = notebookExecutions;
this.objectMapper = objectMapper;
}
@@ -94,6 +98,10 @@ public class EmrHandler {
case "ListStudioSessionMappings" -> handleListStudioSessionMappings(request);
case "UpdateStudioSessionMapping" -> handleUpdateStudioSessionMapping(request);
case "DeleteStudioSessionMapping" -> handleDeleteStudioSessionMapping(request);
case "StartNotebookExecution" -> handleStartNotebookExecution(request);
case "DescribeNotebookExecution" -> handleDescribeNotebookExecution(request);
case "StopNotebookExecution" -> handleStopNotebookExecution(request);
case "ListNotebookExecutions" -> handleListNotebookExecutions(request);
case "AddInstanceGroups" -> handleAddInstanceGroups(request);
case "ListInstanceGroups" -> handleListInstanceGroups(request);
case "AddInstanceFleet" -> handleAddInstanceFleet(request);
@@ -713,6 +721,133 @@ public class EmrHandler {
return value.asBoolean();
}
// ──────────────────────────── Notebook executions ────────────────────────────
private Response handleStartNotebookExecution(JsonNode request) {
EmrNotebookExecution execution = new EmrNotebookExecution();
execution.setEditorId(string(request, "EditorId"));
execution.setRelativePath(string(request, "RelativePath"));
execution.setName(string(request, "NotebookExecutionName"));
execution.setNotebookParams(string(request, "NotebookParams"));
JsonNode engine = request.path("ExecutionEngine");
if (!engine.isMissingNode() && !engine.isNull()) {
requireStructure(engine, "ExecutionEngine");
execution.setEngineId(string(engine, "Id"));
execution.setEngineType(string(engine, "Type"));
execution.setMasterInstanceSecurityGroupId(string(engine, "MasterInstanceSecurityGroupId"));
execution.setExecutionRoleArn(string(engine, "ExecutionRoleArn"));
}
execution.setServiceRole(string(request, "ServiceRole"));
execution.setNotebookInstanceSecurityGroupId(string(request, "NotebookInstanceSecurityGroupId"));
execution.setTags(tagList(request.path("Tags"), "Tags"));
JsonNode input = request.path("NotebookS3Location");
if (!input.isMissingNode() && !input.isNull()) {
requireStructure(input, "NotebookS3Location");
execution.setNotebookS3Bucket(string(input, "Bucket"));
execution.setNotebookS3Key(string(input, "Key"));
}
JsonNode output = request.path("OutputNotebookS3Location");
if (!output.isMissingNode() && !output.isNull()) {
requireStructure(output, "OutputNotebookS3Location");
execution.setOutputNotebookS3Bucket(string(output, "Bucket"));
execution.setOutputNotebookS3Key(string(output, "Key"));
}
execution.setOutputNotebookFormat(string(request, "OutputNotebookFormat"));
execution.setEnvironmentVariables(stringMap(request.path("EnvironmentVariables"), "EnvironmentVariables"));
EmrNotebookExecution started = notebookExecutions.start(execution);
ObjectNode response = objectMapper.createObjectNode();
response.put("NotebookExecutionId", started.getId());
return Response.ok(response).build();
}
private Response handleDescribeNotebookExecution(JsonNode request) {
EmrNotebookExecution execution = notebookExecutions.describe(string(request, "NotebookExecutionId"));
ObjectNode node = objectMapper.createObjectNode();
node.put("NotebookExecutionId", execution.getId());
putIfSet(node, "EditorId", execution.getEditorId());
ObjectNode engine = node.putObject("ExecutionEngine");
engine.put("Id", execution.getEngineId());
engine.put("Type", execution.getEngineType());
putIfSet(engine, "MasterInstanceSecurityGroupId", execution.getMasterInstanceSecurityGroupId());
putIfSet(engine, "ExecutionRoleArn", execution.getExecutionRoleArn());
putIfSet(node, "NotebookExecutionName", execution.getName());
putIfSet(node, "NotebookParams", execution.getNotebookParams());
node.put("Status", execution.getStatus());
putEpoch(node, "StartTime", execution.getStartTime());
putEpoch(node, "EndTime", execution.getEndTime());
node.put("Arn", execution.getArn());
putIfSet(node, "LastStateChangeReason", execution.getLastStateChangeReason());
putIfSet(node, "NotebookInstanceSecurityGroupId", execution.getNotebookInstanceSecurityGroupId());
node.set("Tags", tagArray(execution.getTags()));
putS3Location(node, "NotebookS3Location", execution.getNotebookS3Bucket(), execution.getNotebookS3Key());
putS3Location(node, "OutputNotebookS3Location", execution.getOutputNotebookS3Bucket(),
execution.getOutputNotebookS3Key());
putIfSet(node, "OutputNotebookFormat", execution.getOutputNotebookFormat());
if (execution.getEnvironmentVariables() != null) {
ObjectNode variables = node.putObject("EnvironmentVariables");
execution.getEnvironmentVariables().forEach(variables::put);
}
ObjectNode response = objectMapper.createObjectNode();
response.set("NotebookExecution", node);
return Response.ok(response).build();
}
private Response handleStopNotebookExecution(JsonNode request) {
notebookExecutions.stop(string(request, "NotebookExecutionId"));
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handleListNotebookExecutions(JsonNode request) {
PaginatedResult<EmrNotebookExecution> page = notebookExecutions.list(string(request, "EditorId"),
string(request, "Status"),
// As ListClusters reads its CreatedAfter and CreatedBefore.
AwsJsonTimestamp.epochSeconds(request, "From", "InvalidRequestException"),
AwsJsonTimestamp.epochSeconds(request, "To", "InvalidRequestException"),
string(request, "ExecutionEngineId"), string(request, "Marker"));
ObjectNode response = objectMapper.createObjectNode();
ArrayNode summaries = response.putArray("NotebookExecutions");
for (EmrNotebookExecution execution : page.items()) {
ObjectNode summary = summaries.addObject();
summary.put("NotebookExecutionId", execution.getId());
putIfSet(summary, "EditorId", execution.getEditorId());
putIfSet(summary, "NotebookExecutionName", execution.getName());
summary.put("Status", execution.getStatus());
putEpoch(summary, "StartTime", execution.getStartTime());
putEpoch(summary, "EndTime", execution.getEndTime());
putS3Location(summary, "NotebookS3Location", execution.getNotebookS3Bucket(),
execution.getNotebookS3Key());
summary.put("ExecutionEngineId", execution.getEngineId());
}
if (page.nextToken() != null) {
response.put("Marker", page.nextToken());
}
return Response.ok(response).build();
}
private void putS3Location(ObjectNode node, String field, String bucket, String key) {
if (bucket != null || key != null) {
ObjectNode location = node.putObject(field);
putIfSet(location, "Bucket", bucket);
putIfSet(location, "Key", key);
}
}
// A map of strings; null when it is not there.
private static Map<String, String> stringMap(JsonNode value, String member) {
if (value.isMissingNode() || value.isNull()) {
return null;
}
requireStructure(value, member);
Map<String, String> values = new LinkedHashMap<>();
value.properties().forEach(entry -> {
if (!entry.getValue().isTextual()) {
throw malformed(member + " must be a map of strings");
}
values.put(entry.getKey(), entry.getValue().asText());
});
return values;
}
// ──────────────────────────── Instance groups / fleets ────────────────────────────
private Response handleAddInstanceGroups(JsonNode request) {
@@ -0,0 +1,331 @@
package io.floci.aws.services.emr;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
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.SmithyValidationErrors;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrNotebookExecution;
import io.floci.aws.services.emrserverless.EmrServerlessSparkRunner;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Notebook executions on EMR clusters (Amazon EMR Management Guide, "Sample programmatic commands for EMR Notebooks").
* Floci keeps an execution and its lifecycle, but runs no notebook: in either runner mode an execution is RUNNING from
* the moment it starts and FINISHED once the cluster's step duration ({@code step-duration-seconds}) has passed, unless
* it is stopped first or its cluster shuts down; it writes no output notebook. Executions are kept apart from their
* clusters.
*/
@ApplicationScoped
public class EmrNotebookExecutionService {
static final String START_PENDING = "START_PENDING";
static final String RUNNING = "RUNNING";
static final String FINISHED = "FINISHED";
static final String FAILED = "FAILED";
static final String STOPPED = "STOPPED";
static final List<String> STATUSES = List.of(START_PENDING, "STARTING", RUNNING, "FINISHING", FINISHED,
"FAILING", FAILED, "STOP_PENDING", "STOPPING", STOPPED);
private static final Set<String> ENDED = Set.of(FINISHED, FAILED, STOPPED);
static final List<String> ENGINE_TYPES = List.of("EMR");
static final List<String> OUTPUT_FORMATS = List.of("HTML");
// "A maximum of 100 concurrent executions are supported per AWS Region per account."
static final int MAX_CONCURRENT_EXECUTIONS = 100;
// "An execution is terminated if it runs for more than 30 days."
static final Duration MAX_RUN = Duration.ofDays(30);
// ListNotebookExecutions "Returns a maximum of 50 notebook executions", and From's default "is the timestamp of 30
// days ago".
static final int PAGE_SIZE = 50;
static final Duration DEFAULT_LISTING_WINDOW = Duration.ofDays(30);
private static final int ID_LENGTH = 29;
// A notebook execution's ARN's resource, before its id.
static final String EXECUTION_RESOURCE = "notebook-execution/";
private static final int MAX_NAME_LENGTH = 256;
private final AccountAwareStorageBackend<EmrNotebookExecution> store;
private final EmrService clusters;
private final RegionResolver regionResolver;
private final Clock clock;
private final Duration runDuration;
@Inject
public EmrNotebookExecutionService(StorageFactory storageFactory, EmrService clusters,
RegionResolver regionResolver, EmulatorConfig config) {
this(storageFactory.create("emr", "emr-notebook-executions.json",
new TypeReference<Map<String, EmrNotebookExecution>>() {}),
clusters, regionResolver, Clock.systemUTC(),
Duration.ofSeconds(config.services().emr().stepDurationSeconds()));
}
EmrNotebookExecutionService(AccountAwareStorageBackend<EmrNotebookExecution> store, EmrService clusters,
RegionResolver regionResolver, Clock clock, Duration runDuration) {
this.store = store;
this.clusters = clusters;
this.regionResolver = regionResolver;
this.clock = clock;
this.runDuration = runDuration;
}
/**
* Starts a notebook execution on a cluster. The model's required members and enums are checked first, with the
* ValidationException AWS's validation layer answers. Then the cluster, which must be RUNNING or WAITING and meet
* the EMR Notebooks cluster requirements: "Only clusters created using Amazon EMR release version 5.18.0 and later
* are supported", "The cluster must be launched with Hadoop, Spark, and Livy" and, "For Amazon EMR release
* versions 5.32.0 and later, or 6.2.0 and later", Jupyter Enterprise Gateway too (the AWS runtime for Apache
* Spark's releases name no Hadoop among their applications); and at most {@link #MAX_CONCURRENT_EXECUTIONS} that
* have not ended. Each of these refusals is InvalidRequestException in Floci's own wording, as AWS's is not
* recorded.
*/
public synchronized EmrNotebookExecution start(EmrNotebookExecution requested) {
List<String> violations = new ArrayList<>();
if (requested.getEngineId() == null) {
violations.add(SmithyValidationErrors.notNull("executionEngine.id"));
}
if (requested.getServiceRole() == null) {
violations.add(SmithyValidationErrors.notNull("serviceRole"));
}
EmrService.checkEnum(violations, "executionEngine.type", requested.getEngineType(), ENGINE_TYPES);
EmrService.checkEnum(violations, "outputNotebookFormat", requested.getOutputNotebookFormat(), OUTPUT_FORMATS);
if (requested.getName() != null && requested.getName().length() > MAX_NAME_LENGTH) {
violations.add(SmithyValidationErrors.lengthOutOfRange("notebookExecutionName", requested.getName(), 0,
MAX_NAME_LENGTH));
}
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
// The model's XmlString takes an empty role, which names none; AWS's answer for one is not recorded.
if (requested.getServiceRole().isBlank()) {
throw EmrService.invalid("ServiceRole is required.");
}
EmrCluster cluster = clusters.describeCluster(requested.getEngineId());
checkCluster(cluster);
String region = regionResolver.getRegion();
List<EmrNotebookExecution> executions = settledExecutions(region);
long running = executions.stream().filter(execution -> !ENDED.contains(execution.getStatus())).count();
if (running >= MAX_CONCURRENT_EXECUTIONS) {
throw EmrService.invalid("The account already has " + MAX_CONCURRENT_EXECUTIONS
+ " concurrent notebook executions in the Region.");
}
EmrNotebookExecution execution = EmrService.SNAPSHOT_MAPPER.convertValue(requested,
EmrNotebookExecution.class);
String id = "ex-" + EmrService.randomId(ID_LENGTH);
execution.setId(id);
execution.setArn(regionResolver.buildArn("elasticmapreduce", region, EXECUTION_RESOURCE + id));
execution.setEngineType(requested.getEngineType() != null ? requested.getEngineType() : "EMR");
execution.setStatus(START_PENDING);
execution.setStartTime(now());
execution.setRegion(region);
execution.setTags(requested.getTags() != null ? new LinkedHashMap<>(requested.getTags())
: new LinkedHashMap<>());
execution.setSequence(store.scan(key -> true).stream().mapToLong(EmrNotebookExecution::getSequence)
.max().orElse(0) + 1);
store.put(id, execution);
return copy(execution);
}
public synchronized EmrNotebookExecution describe(String executionId) {
return copy(settle(require(executionId)));
}
/**
* Stops an execution that has not ended, which is STOPPED at once, as no notebook runs: "Execution is stopped for
* cluster ...", as AWS's example puts it. One that has ended is refused, in Floci's own wording, as AWS's answer
* is not recorded.
*/
public synchronized void stop(String executionId) {
EmrNotebookExecution execution = settle(require(executionId));
if (ENDED.contains(execution.getStatus())) {
throw EmrService.invalid("Notebook execution " + executionId + " has already ended.");
}
end(execution, STOPPED, "Execution is stopped for cluster " + execution.getEngineId() + ".", now());
}
/**
* The Region's executions that started from {@code from} (by default 30 days ago) to {@code to} (by default now),
* filtered by editor, status and execution engine, newest first, the later of two started in the same
* millisecond first too, 50 to a page after the request's Marker.
*/
public synchronized PaginatedResult<EmrNotebookExecution> list(String editorId, String status, Instant from,
Instant to, String engineId, String marker) {
List<String> violations = new ArrayList<>();
EmrService.checkEnum(violations, "status", status, STATUSES);
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
Instant now = clock.instant();
Instant since = from != null ? from : now.minus(DEFAULT_LISTING_WINDOW);
Instant until = to != null ? to : now;
List<EmrNotebookExecution> matching = settledExecutions(regionResolver.getRegion()).stream()
.filter(execution -> editorId == null || editorId.equals(execution.getEditorId()))
.filter(execution -> status == null || status.equals(execution.getStatus()))
.filter(execution -> engineId == null || engineId.equals(execution.getEngineId()))
.filter(execution -> !execution.getStartTime().isBefore(since)
&& !execution.getStartTime().isAfter(until))
.toList();
String namespace = listingNamespace(editorId, status, from, to, engineId);
PaginatedResult<EmrNotebookExecution> page = Pagination.paginate(matching,
execution -> String.format("%020d%020d", Long.MAX_VALUE - execution.getStartTime().toEpochMilli(),
Long.MAX_VALUE - execution.getSequence()),
PAGE_SIZE, marker, namespace, token -> EmrService.invalid("Invalid Marker."));
return new PaginatedResult<>(page.items().stream().map(EmrNotebookExecutionService::copy).toList(),
page.nextToken());
}
/** The tags held on the execution stored under {@code arn}, in the account and Region it names, for IAM. */
public Map<String, String> storedTags(String arn) {
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
String executionId = EmrService.resourceIdOf(parsed, EXECUTION_RESOURCE);
if (executionId == null) {
return Map.of();
}
return AccountAwareStorageBackend.readInAccount(store, parsed.accountId(), executionId)
.filter(execution -> parsed.region().equals(execution.getRegion()) && arn.equals(execution.getArn()))
.map(execution -> EmrService.heldTags(execution.getTags()))
.orElse(Map.of());
}
private static void checkCluster(EmrCluster cluster) {
if (!EmrClusterLifecycle.RUNNING.equals(cluster.getState())
&& !EmrClusterLifecycle.WAITING.equals(cluster.getState())) {
throw EmrService.invalid("Cluster " + cluster.getId() + " is " + cluster.getState()
+ ", and a notebook execution needs it RUNNING or WAITING.");
}
String release = cluster.getReleaseLabel();
if (!EmrService.releaseAtLeast(release, 5, 18, 0)) {
throw EmrService.invalid("Notebook executions need a cluster of release emr-5.18.0 or later.");
}
List<String> required = new ArrayList<>(List.of("Spark", "Livy"));
if (release == null || !EmrServerlessSparkRunner.sparkRuntime(release)) {
required.add(0, "Hadoop");
}
boolean gateway = EmrService.releaseAtLeast(release, 6, 2, 0)
|| (EmrService.releaseAtLeast(release, 5, 32, 0) && !EmrService.releaseAtLeast(release, 6, 0, 0));
if (gateway) {
required.add("JupyterEnterpriseGateway");
}
for (String application : required) {
if (!EmrSparkSteps.names(cluster.getApplications(), EmrService.SNAPSHOT_MAPPER, application)) {
throw EmrService.invalid("Notebook executions need a cluster with " + String.join(", ", required)
+ " installed, and cluster " + cluster.getId() + " has no " + application + ".");
}
}
}
// The Region's executions, each brought up to date, stored where it changed.
private List<EmrNotebookExecution> settledExecutions(String region) {
List<EmrNotebookExecution> executions = store.scan(key -> true).stream()
.filter(execution -> region.equals(execution.getRegion()))
.toList();
executions.forEach(this::settle);
return executions;
}
/**
* Brings an execution up to now: RUNNING from its start, FINISHED once the run duration has passed, "Execution is
* finished for cluster ...", as AWS's example puts it, and FAILED once its cluster shuts down first, or once it
* has run 30 days, in Floci's own wording.
*/
private EmrNotebookExecution settle(EmrNotebookExecution execution) {
if (ENDED.contains(execution.getStatus())) {
return execution;
}
boolean changed = false;
if (START_PENDING.equals(execution.getStatus())) {
execution.setStatus(RUNNING);
changed = true;
}
Instant now = clock.instant();
Instant finish = execution.getStartTime().plus(runDuration);
Instant limit = execution.getStartTime().plus(MAX_RUN);
EmrCluster cluster = clusterOf(execution);
Instant clusterEnd = cluster != null ? EmrService.shutDownAt(cluster, now) : null;
if (limit.isBefore(finish) && !now.isBefore(limit) && (clusterEnd == null || limit.isBefore(clusterEnd))) {
end(execution, FAILED, "Execution is terminated for cluster " + execution.getEngineId()
+ ", as it ran for more than 30 days.", limit);
} else if (!now.isBefore(finish) && !finish.isAfter(limit)
&& (clusterEnd == null || finish.isBefore(clusterEnd))) {
end(execution, FINISHED, "Execution is finished for cluster " + execution.getEngineId() + ".", finish);
} else if (clusterEnd != null) {
end(execution, FAILED, "Execution failed for cluster " + execution.getEngineId()
+ ", as the cluster was terminated.", clusterEnd.isBefore(execution.getStartTime())
? execution.getStartTime() : clusterEnd);
} else if (changed) {
store.put(execution.getId(), execution);
}
return execution;
}
/**
* What a marker resumes only: the account, the Region and each filter, an absent one told apart from any value, as
* a JSON list.
*/
private String listingNamespace(String editorId, String status, Instant from, Instant to, String engineId) {
List<String> parts = Arrays.asList("ListNotebookExecutions", regionResolver.getAccountId(),
regionResolver.getRegion(), editorId, status, from != null ? from.toString() : null,
to != null ? to.toString() : null, engineId);
try {
return EmrService.SNAPSHOT_MAPPER.writeValueAsString(parts);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Cannot write a listing's namespace", e);
}
}
/**
* The execution's cluster as it now stands, or null once it is gone, which DescribeCluster answers with
* InvalidRequestException; any other failure is the caller's, not the execution's.
*/
private EmrCluster clusterOf(EmrNotebookExecution execution) {
try {
return clusters.describeCluster(execution.getEngineId());
} catch (AwsException e) {
if ("InvalidRequestException".equals(e.getErrorCode())) {
return null;
}
throw e;
}
}
private void end(EmrNotebookExecution execution, String status, String reason, Instant at) {
execution.setStatus(status);
execution.setLastStateChangeReason(reason);
execution.setEndTime(at);
store.put(execution.getId(), execution);
}
private EmrNotebookExecution require(String executionId) {
if (executionId == null) {
throw SmithyValidationErrors.validationException(SmithyValidationErrors.notNull("notebookExecutionId"));
}
return store.get(executionId)
.filter(execution -> regionResolver.getRegion().equals(execution.getRegion()))
.orElseThrow(() -> EmrService.invalid("Notebook execution " + executionId + " does not exist."));
}
private Instant now() {
return clock.instant().truncatedTo(ChronoUnit.MILLIS);
}
private static EmrNotebookExecution copy(EmrNotebookExecution execution) {
return EmrService.SNAPSHOT_MAPPER.convertValue(execution, EmrNotebookExecution.class);
}
}
@@ -54,6 +54,7 @@ import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
@@ -272,6 +273,10 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
@Inject
Provider<EmrStudioService> studios;
// The notebook executions, whose tags this service answers for too; looked up as they are needed.
@Inject
Provider<EmrNotebookExecutionService> notebookExecutions;
@Inject
public EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
EmrEventPublisher eventPublisher, EmrServerlessSparkRunner sparkRunner,
@@ -1223,9 +1228,10 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
}
/**
* The tags held on the cluster or Studio stored under {@code arn}, in the account it names, read in place: the
* cluster of that id in the ARN's Region, or one recorded with no Region, as the tag handlers find it, or the
* Studio of that id in the ARN's Region; empty for an ARN naming nothing stored or naming anything else.
* The tags held on the cluster, Studio or notebook execution stored under {@code arn}, in the account it names,
* read in place: the cluster of that id in the ARN's Region, or one recorded with no Region, as the tag handlers
* find it, or the Studio or execution of that id in the ARN's Region; empty for an ARN naming nothing stored or
* naming anything else.
*/
@Override
public Map<String, String> storedTags(String arn) {
@@ -1237,21 +1243,37 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
if (resource.startsWith(EmrStudioService.STUDIO_RESOURCE)) {
return studioService().map(service -> service.storedTags(arn)).orElse(Map.of());
}
if (!resource.startsWith(CLUSTER_RESOURCE) || resource.indexOf('/', CLUSTER_RESOURCE.length()) >= 0
|| !arn.equals(AwsArnUtils.Arn.of("elasticmapreduce", parsed.region(), parsed.accountId(), resource)
.toString())) {
if (resource.startsWith(EmrNotebookExecutionService.EXECUTION_RESOURCE)) {
return notebookExecutions != null ? notebookExecutions.get().storedTags(arn) : Map.of();
}
String clusterId = resourceIdOf(parsed, CLUSTER_RESOURCE);
if (clusterId == null || !arn.equals(AwsArnUtils.Arn.of("elasticmapreduce", parsed.region(),
parsed.accountId(), resource).toString())) {
return Map.of();
}
Map<String, String> held = new LinkedHashMap<>();
AccountAwareStorageBackend.readInAccount(clusterStore, parsed.accountId(),
resource.substring(CLUSTER_RESOURCE.length()))
return AccountAwareStorageBackend.readInAccount(clusterStore, parsed.accountId(), clusterId)
.filter(cluster -> cluster.getRegion() == null || cluster.getRegion().equals(parsed.region()))
.map(EmrCluster::getTags)
.ifPresent(tags -> tags.forEach((key, value) -> {
if (key != null && value != null) {
held.put(key, value);
}
}));
.map(cluster -> heldTags(cluster.getTags()))
.orElse(Map.of());
}
/** The id after {@code prefix} in the resource of an ARN naming one resource of that type; null for another. */
static String resourceIdOf(AwsArnUtils.Arn arn, String prefix) {
String resource = arn.resource();
return resource.startsWith(prefix) && resource.indexOf('/', prefix.length()) < 0
? resource.substring(prefix.length()) : null;
}
/** A resource's tags as IAM's conditions read them: those with both a key and a value. */
static Map<String, String> heldTags(Map<String, String> tags) {
Map<String, String> held = new LinkedHashMap<>();
if (tags != null) {
tags.forEach((key, value) -> {
if (key != null && value != null) {
held.put(key, value);
}
});
}
return held;
}
@@ -1536,14 +1558,21 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
// Whether a cluster of releaseLabel takes CancelSteps: from 4.8.0 on but 5.0.0; a label not of the emr-x.y.z form
// is taken as current.
static boolean cancelsSteps(String releaseLabel) {
return releaseAtLeast(releaseLabel, 4, 8, 0) && !"emr-5.0.0".equals(releaseLabel);
}
/**
* Whether {@code releaseLabel} is {@code major.minor.patch} or later; a label not of the emr-x.y.z form, such as
* the AWS runtime for Apache Spark's, is taken as current.
*/
static boolean releaseAtLeast(String releaseLabel, int major, int minor, int patch) {
Matcher version = RELEASE_VERSION.matcher(releaseLabel == null ? "" : releaseLabel);
if (!version.matches()) {
return true;
}
int major = Integer.parseInt(version.group(1));
int minor = Integer.parseInt(version.group(2));
int patch = Integer.parseInt(version.group(3));
return (major > 4 || major == 4 && minor >= 8) && !(major == 5 && minor == 0 && patch == 0);
int[] label = {Integer.parseInt(version.group(1)), Integer.parseInt(version.group(2)),
Integer.parseInt(version.group(3))};
return Arrays.compare(label, new int[]{major, minor, patch}) >= 0;
}
// Why a cluster gets no instance group or fleet of the other kind: "The configuration option you choose applies to
@@ -1636,6 +1665,25 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
}
}
/**
* When the cluster began to shut down, if it has: as it began terminating, or else as it ended, or else
* {@code now}; null while it runs. A session or notebook execution on it ends then.
*/
static Instant shutDownAt(EmrCluster cluster, Instant now) {
if (!isShutDown(cluster)) {
return null;
}
return cluster.getTerminatingDateTime() != null ? cluster.getTerminatingDateTime()
: cluster.getEndDateTime() != null ? cluster.getEndDateTime() : now;
}
/** Adds the violation of an enum member whose value is not one of {@code allowed}, as AWS's validation words it. */
static void checkEnum(List<String> violations, String member, String value, List<String> allowed) {
if (value != null && !allowed.contains(value)) {
violations.add(SmithyValidationErrors.notInEnum(value, member, allowed));
}
}
/** Shutting down or ended: "A job flow that is shutting down, terminated, or finished may not be modified." */
static boolean isShutDown(EmrCluster cluster) {
return EmrClusterLifecycle.TERMINATING.equals(cluster.getState())
@@ -201,8 +201,7 @@ final class EmrSessions {
return false;
}
boolean changed = false;
Instant clusterEnd = EmrService.isShutDown(cluster) ? firstOf(cluster.getTerminatingDateTime(),
cluster.getEndDateTime(), now) : null;
Instant clusterEnd = EmrService.shutDownAt(cluster, now);
if (SUBMITTED.equals(session.getState())
&& (clusterEnd == null || session.getCreatedAt().isBefore(clusterEnd))) {
session.setState(IDLE);
@@ -270,13 +269,4 @@ final class EmrSessions {
session.setUpdatedAt(at);
session.setIdleSince(null);
}
private static Instant firstOf(Instant... instants) {
for (Instant instant : instants) {
if (instant != null) {
return instant;
}
}
return null;
}
}
@@ -106,8 +106,8 @@ public class EmrStudioService {
requireMember(violations, "workspaceSecurityGroupId", requested.getWorkspaceSecurityGroupId());
requireMember(violations, "engineSecurityGroupId", requested.getEngineSecurityGroupId());
requireMember(violations, "defaultS3Location", requested.getDefaultS3Location());
checkEnum(violations, "authMode", requested.getAuthMode(), AUTH_MODES);
checkEnum(violations, "idcUserAssignment", requested.getIdcUserAssignment(), USER_ASSIGNMENTS);
EmrService.checkEnum(violations, "authMode", requested.getAuthMode(), AUTH_MODES);
EmrService.checkEnum(violations, "idcUserAssignment", requested.getIdcUserAssignment(), USER_ASSIGNMENTS);
checkLength(violations, "name", requested.getName());
checkLength(violations, "description", requested.getDescription());
if (!violations.isEmpty()) {
@@ -235,21 +235,14 @@ public class EmrStudioService {
/** The tags held on the Studio stored under {@code arn}, in the account and Region it names, for IAM. */
public Map<String, String> storedTags(String arn) {
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
String resource = parsed.resource();
if (!resource.startsWith(STUDIO_RESOURCE) || resource.indexOf('/', STUDIO_RESOURCE.length()) >= 0) {
String studioId = EmrService.resourceIdOf(parsed, STUDIO_RESOURCE);
if (studioId == null) {
return Map.of();
}
Map<String, String> held = new LinkedHashMap<>();
String studioId = resource.substring(STUDIO_RESOURCE.length());
AccountAwareStorageBackend.readInAccount(store, parsed.accountId(), studioId)
return AccountAwareStorageBackend.readInAccount(store, parsed.accountId(), studioId)
.filter(studio -> parsed.region().equals(studio.getRegion()) && arn.equals(studio.getStudioArn()))
.map(EmrStudio::getTags)
.ifPresent(tags -> tags.forEach((key, value) -> {
if (key != null && value != null) {
held.put(key, value);
}
}));
return held;
.map(studio -> EmrService.heldTags(studio.getTags()))
.orElse(Map.of());
}
/** Removes a Studio "from the Studio metadata store", its session mappings with it. */
@@ -331,7 +324,7 @@ public class EmrStudioService {
public synchronized PaginatedResult<StudioMapping> listSessionMappings(String studioId, String identityType,
String marker) {
List<String> violations = new ArrayList<>();
checkEnum(violations, "identityType", identityType, IDENTITY_TYPES);
EmrService.checkEnum(violations, "identityType", identityType, IDENTITY_TYPES);
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
@@ -377,7 +370,7 @@ public class EmrStudioService {
if (policyRequired && sessionPolicyArn == null) {
violations.add(SmithyValidationErrors.notNull("sessionPolicyArn"));
}
checkEnum(violations, "identityType", identity.type(), IDENTITY_TYPES);
EmrService.checkEnum(violations, "identityType", identity.type(), IDENTITY_TYPES);
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
@@ -495,12 +488,6 @@ public class EmrStudioService {
}
}
private static void checkEnum(List<String> violations, String member, String value, List<String> allowed) {
if (value != null && !allowed.contains(value)) {
violations.add(SmithyValidationErrors.notInEnum(value, member, allowed));
}
}
private static void checkLength(List<String> violations, String member, String value) {
if (value != null && value.length() > MAX_NAME_LENGTH) {
violations.add(SmithyValidationErrors.lengthOutOfRange(member, value, 0, MAX_NAME_LENGTH));
@@ -0,0 +1,106 @@
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 notebook execution, as DescribeNotebookExecution reports it, with the Region it is in, the service role and
* relative path it was started with, and its place among the account's executions.
*/
@RegisterForReflection
public class EmrNotebookExecution {
private String id;
private String arn;
private String editorId;
private String relativePath;
private String name;
private String notebookParams;
private String engineId;
private String engineType;
private String masterInstanceSecurityGroupId;
private String executionRoleArn;
private String serviceRole;
private String notebookInstanceSecurityGroupId;
private Map<String, String> tags = new LinkedHashMap<>();
private String notebookS3Bucket;
private String notebookS3Key;
private String outputNotebookS3Bucket;
private String outputNotebookS3Key;
private String outputNotebookFormat;
private Map<String, String> environmentVariables;
private String status;
private Instant startTime;
private Instant endTime;
private String lastStateChangeReason;
private String region;
private long sequence;
public EmrNotebookExecution() {}
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
public String getEditorId() { return editorId; }
public void setEditorId(String editorId) { this.editorId = editorId; }
public String getRelativePath() { return relativePath; }
public void setRelativePath(String relativePath) { this.relativePath = relativePath; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getNotebookParams() { return notebookParams; }
public void setNotebookParams(String notebookParams) { this.notebookParams = notebookParams; }
public String getEngineId() { return engineId; }
public void setEngineId(String engineId) { this.engineId = engineId; }
public String getEngineType() { return engineType; }
public void setEngineType(String engineType) { this.engineType = engineType; }
public String getMasterInstanceSecurityGroupId() { return masterInstanceSecurityGroupId; }
public void setMasterInstanceSecurityGroupId(String masterInstanceSecurityGroupId) {
this.masterInstanceSecurityGroupId = masterInstanceSecurityGroupId;
}
public String getExecutionRoleArn() { return executionRoleArn; }
public void setExecutionRoleArn(String executionRoleArn) { this.executionRoleArn = executionRoleArn; }
public String getServiceRole() { return serviceRole; }
public void setServiceRole(String serviceRole) { this.serviceRole = serviceRole; }
public String getNotebookInstanceSecurityGroupId() { return notebookInstanceSecurityGroupId; }
public void setNotebookInstanceSecurityGroupId(String notebookInstanceSecurityGroupId) {
this.notebookInstanceSecurityGroupId = notebookInstanceSecurityGroupId;
}
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
public String getNotebookS3Bucket() { return notebookS3Bucket; }
public void setNotebookS3Bucket(String notebookS3Bucket) { this.notebookS3Bucket = notebookS3Bucket; }
public String getNotebookS3Key() { return notebookS3Key; }
public void setNotebookS3Key(String notebookS3Key) { this.notebookS3Key = notebookS3Key; }
public String getOutputNotebookS3Bucket() { return outputNotebookS3Bucket; }
public void setOutputNotebookS3Bucket(String outputNotebookS3Bucket) {
this.outputNotebookS3Bucket = outputNotebookS3Bucket;
}
public String getOutputNotebookS3Key() { return outputNotebookS3Key; }
public void setOutputNotebookS3Key(String outputNotebookS3Key) { this.outputNotebookS3Key = outputNotebookS3Key; }
public String getOutputNotebookFormat() { return outputNotebookFormat; }
public void setOutputNotebookFormat(String outputNotebookFormat) {
this.outputNotebookFormat = outputNotebookFormat;
}
public Map<String, String> getEnvironmentVariables() { return environmentVariables; }
public void setEnvironmentVariables(Map<String, String> environmentVariables) {
this.environmentVariables = environmentVariables;
}
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public Instant getStartTime() { return startTime; }
public void setStartTime(Instant startTime) { this.startTime = startTime; }
public Instant getEndTime() { return endTime; }
public void setEndTime(Instant endTime) { this.endTime = endTime; }
public String getLastStateChangeReason() { return lastStateChangeReason; }
public void setLastStateChangeReason(String lastStateChangeReason) {
this.lastStateChangeReason = lastStateChangeReason;
}
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
public long getSequence() { return sequence; }
public void setSequence(long sequence) { this.sequence = sequence; }
}
@@ -0,0 +1,114 @@
package io.floci.aws.services.emr;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static io.floci.aws.testing.EmrRequests.emr;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Notebook executions over the AWS JSON 1.1 wire protocol: StartNotebookExecution, DescribeNotebookExecution,
* ListNotebookExecutions and StopNotebookExecution, with the step duration of 0 the tests run with, which finishes an
* execution as soon as it is read.
*/
@QuarkusTest
class EmrNotebookExecutionIntegrationTest {
@Inject
EmrService emrService;
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void anExecutionIsStartedDescribedAndListedOnACluster() {
String clusterId = cluster();
String id = emr("StartNotebookExecution", """
{"EditorId": "e-ABCDEFG123456", "RelativePath": "test.ipynb", "NotebookExecutionName": "my-execution",
"NotebookParams": "{\\"input_param\\": \\"my-value\\"}",
"ExecutionEngine": {"Id": "%s", "MasterInstanceSecurityGroupId": "sg-05ce12e58cd4f715e"},
"ServiceRole": "EMR_Notebooks_DefaultRole", "OutputNotebookFormat": "HTML",
"NotebookS3Location": {"Bucket": "notebooks", "Key": "in/test.ipynb"},
"EnvironmentVariables": {"KERNEL_LAUNCH_TIMEOUT": "350"},
"Tags": [{"Key": "team", "Value": "data"}]}
""".formatted(clusterId))
.then().statusCode(200)
.body("NotebookExecutionId", matchesPattern("ex-[A-Z0-9]{29}"))
.extract().path("NotebookExecutionId");
emr("DescribeNotebookExecution", "{\"NotebookExecutionId\":\"" + id + "\"}")
.then().statusCode(200)
.body("NotebookExecution.NotebookExecutionId", equalTo(id))
.body("NotebookExecution.EditorId", equalTo("e-ABCDEFG123456"))
.body("NotebookExecution.ExecutionEngine.Id", equalTo(clusterId))
.body("NotebookExecution.ExecutionEngine.Type", equalTo("EMR"))
.body("NotebookExecution.ExecutionEngine.MasterInstanceSecurityGroupId",
equalTo("sg-05ce12e58cd4f715e"))
.body("NotebookExecution.NotebookExecutionName", equalTo("my-execution"))
.body("NotebookExecution.Status", equalTo("FINISHED"))
.body("NotebookExecution.LastStateChangeReason",
equalTo("Execution is finished for cluster " + clusterId + "."))
.body("NotebookExecution.Arn", equalTo(
"arn:aws:elasticmapreduce:us-east-1:000000000000:notebook-execution/" + id))
.body("NotebookExecution.StartTime", notNullValue())
.body("NotebookExecution.EndTime", notNullValue())
.body("NotebookExecution.NotebookS3Location.Key", equalTo("in/test.ipynb"))
.body("NotebookExecution.EnvironmentVariables.KERNEL_LAUNCH_TIMEOUT", equalTo("350"))
.body("NotebookExecution.Tags[0].Key", equalTo("team"));
// What an IAM condition on aws:ResourceTag reads of the execution.
assertEquals(Map.of("team", "data"),
emrService.storedTags("arn:aws:elasticmapreduce:us-east-1:000000000000:notebook-execution/" + id));
emr("ListNotebookExecutions", "{\"ExecutionEngineId\":\"" + clusterId + "\",\"Status\":\"FINISHED\"}")
.then().statusCode(200)
.body("NotebookExecutions.NotebookExecutionId", hasItem(id))
.body("NotebookExecutions[0].ExecutionEngineId", equalTo(clusterId));
emr("StopNotebookExecution", "{\"NotebookExecutionId\":\"" + id + "\"}")
.then().statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + clusterId + "\"]}").then().statusCode(200);
}
@Test
void aMalformedOrIncompleteRequestIsRefused() {
String clusterId = cluster();
emr("StartNotebookExecution", "{\"ExecutionEngine\": \"" + clusterId + "\", \"ServiceRole\": \"r\"}")
.then().statusCode(400)
.body("__type", equalTo("SerializationException"));
emr("StartNotebookExecution", "{\"ExecutionEngine\": {\"Id\": \"" + clusterId + "\"}, \"ServiceRole\": \"r\","
+ " \"EnvironmentVariables\": {\"A\": 1}}")
.then().statusCode(400)
.body("__type", equalTo("SerializationException"));
emr("StartNotebookExecution", "{\"ExecutionEngine\": {\"Id\": \"" + clusterId + "\"}}")
.then().statusCode(400)
.body("__type", equalTo("ValidationException"));
emr("DescribeNotebookExecution", "{\"NotebookExecutionId\": \"ex-NOSUCHEXECUTION\"}")
.then().statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + clusterId + "\"]}").then().statusCode(200);
}
private static String cluster() {
return emr("RunJobFlow", """
{"Name": "notebooks", "ReleaseLabel": "emr-6.15.0",
"Applications": [{"Name": "Hadoop"}, {"Name": "Spark"}, {"Name": "Livy"},
{"Name": "JupyterEnterpriseGateway"}],
"Instances": {"KeepJobFlowAliveWhenNoSteps": true,
"InstanceGroups": [{"Name": "primary", "InstanceRole": "MASTER", "InstanceType": "m5.xlarge",
"InstanceCount": 1}]}}
""")
.then().statusCode(200).extract().path("JobFlowId");
}
}
@@ -0,0 +1,231 @@
package io.floci.aws.services.emr;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrNotebookExecution;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import static io.floci.aws.services.emr.EmrServiceFixture.ACCOUNT;
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.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** Notebook executions through {@link EmrNotebookExecutionService}: their lifecycle and what refuses one. */
class EmrNotebookExecutionServiceTest {
private static final String NOTEBOOK_APPS = "[{\"Name\":\"Hadoop\"},{\"Name\":\"Spark\"},{\"Name\":\"Livy\"},"
+ "{\"Name\":\"JupyterEnterpriseGateway\"}]";
private static final Duration RUN = Duration.ofMinutes(10);
private final EmrServiceFixture fixture = new EmrServiceFixture(0, 0, 0);
private final AccountAwareStorageBackend<EmrNotebookExecution> store = AccountAwareStorageBackend.inMemory(ACCOUNT);
private final EmrNotebookExecutionService executions = new EmrNotebookExecutionService(store, fixture.service,
new RegionResolver(REGION, ACCOUNT), fixture.clock, RUN);
@Test
void anExecutionRunsForTheStepDurationAndFinishesAsAwsReportsIt() {
String clusterId = notebookCluster("emr-6.15.0", NOTEBOOK_APPS);
EmrNotebookExecution started = executions.start(request(clusterId));
assertTrue(started.getId().matches("ex-[A-Z0-9]{29}"), started.getId());
assertEquals("arn:aws:elasticmapreduce:us-east-1:000000000000:notebook-execution/" + started.getId(),
started.getArn());
assertEquals("START_PENDING", started.getStatus());
EmrNotebookExecution running = executions.describe(started.getId());
assertEquals("RUNNING", running.getStatus());
assertEquals("EMR", running.getEngineType());
assertNull(running.getEndTime());
fixture.clock.advance(RUN);
EmrNotebookExecution finished = executions.describe(started.getId());
assertEquals("FINISHED", finished.getStatus());
assertEquals("Execution is finished for cluster " + clusterId + ".", finished.getLastStateChangeReason());
assertEquals(started.getStartTime().plus(RUN), finished.getEndTime());
}
@Test
void aRunningExecutionStopsAndOneThatHasEndedCannotStopAgain() {
String clusterId = notebookCluster("emr-6.15.0", NOTEBOOK_APPS);
String id = executions.start(request(clusterId)).getId();
executions.stop(id);
EmrNotebookExecution stopped = executions.describe(id);
assertEquals("STOPPED", stopped.getStatus());
assertEquals("Execution is stopped for cluster " + clusterId + ".", stopped.getLastStateChangeReason());
assertEquals("InvalidRequestException", assertThrows(AwsException.class, () -> executions.stop(id))
.getErrorCode());
}
@Test
void anExecutionFailsAsItsClusterShutsDown() {
String clusterId = notebookCluster("emr-6.15.0", NOTEBOOK_APPS);
String id = executions.start(request(clusterId)).getId();
fixture.service.terminateJobFlows(List.of(clusterId));
EmrNotebookExecution failed = executions.describe(id);
assertEquals("FAILED", failed.getStatus());
assertTrue(failed.getLastStateChangeReason().contains("the cluster was terminated"),
failed.getLastStateChangeReason());
}
@Test
void aClusterMustMeetTheEmrNotebooksRequirements() {
assertRefused(notebookCluster("emr-5.17.0", NOTEBOOK_APPS), "emr-5.18.0");
assertRefused(notebookCluster("emr-6.15.0", "[{\"Name\":\"Hadoop\"},{\"Name\":\"Spark\"},"
+ "{\"Name\":\"JupyterEnterpriseGateway\"}]"), "has no Livy");
assertRefused(notebookCluster("emr-6.15.0", "[{\"Name\":\"Hadoop\"},{\"Name\":\"Spark\"},{\"Name\":\"Livy\"}]"),
"has no JupyterEnterpriseGateway");
// Before 5.32.0, no Jupyter Enterprise Gateway; the AWS runtime for Apache Spark names no Hadoop.
executions.start(request(notebookCluster("emr-5.31.0",
"[{\"Name\":\"Hadoop\"},{\"Name\":\"Spark\"},{\"Name\":\"Livy\"}]")));
executions.start(request(notebookCluster("emr-spark-8.0.0",
"[{\"Name\":\"Spark\"},{\"Name\":\"Livy\"},{\"Name\":\"JupyterEnterpriseGateway\"}]")));
EmrServiceFixture starting = new EmrServiceFixture(600, 0, 0);
EmrNotebookExecutionService early = new EmrNotebookExecutionService(AccountAwareStorageBackend.inMemory(
ACCOUNT), starting.service, new RegionResolver(REGION, ACCOUNT), starting.clock, RUN);
String startingId = starting.service.runJobFlow(clusterSpec("emr-6.15.0", NOTEBOOK_APPS), REGION).getId();
AwsException notReady = assertThrows(AwsException.class, () -> early.start(request(startingId)));
assertTrue(notReady.getMessage().contains("RUNNING or WAITING"), notReady.getMessage());
assertEquals("InvalidRequestException", assertThrows(AwsException.class,
() -> executions.start(request("j-NOSUCHCLUSTER"))).getErrorCode());
}
@Test
void aRequestIsRefusedWithoutItsRequiredMembersOrWithAValueOutsideAnEnum() {
String clusterId = notebookCluster("emr-6.15.0", NOTEBOOK_APPS);
EmrNotebookExecution noRole = request(clusterId);
noRole.setServiceRole(null);
EmrNotebookExecution onEks = request(clusterId);
onEks.setEngineType("EMR_ON_EKS");
EmrNotebookExecution pdf = request(clusterId);
pdf.setOutputNotebookFormat("PDF");
for (EmrNotebookExecution refused : List.of(noRole, onEks, pdf, request(null))) {
assertEquals("ValidationException", assertThrows(AwsException.class, () -> executions.start(refused))
.getErrorCode());
}
}
@Test
void aBlankServiceRoleIsRefused() {
EmrNotebookExecution blank = request(notebookCluster("emr-6.15.0", NOTEBOOK_APPS));
blank.setServiceRole(" ");
assertEquals("InvalidRequestException", assertThrows(AwsException.class, () -> executions.start(blank))
.getErrorCode());
}
@Test
void aClusterLookupThatFailsForAnotherReasonLeavesTheExecutionAsItWas() {
EmrService failing = mock(EmrService.class);
EmrCluster cluster = clusterSpec("emr-6.15.0", NOTEBOOK_APPS);
cluster.setId("j-FAILING");
cluster.setState("WAITING");
when(failing.describeCluster("j-FAILING")).thenReturn(cluster)
.thenThrow(new IllegalStateException("storage unavailable"));
EmrNotebookExecutionService service = new EmrNotebookExecutionService(store, failing,
new RegionResolver(REGION, ACCOUNT), fixture.clock, RUN);
String id = service.start(request("j-FAILING")).getId();
assertThrows(IllegalStateException.class, () -> service.describe(id));
// RUNNING from its start, whatever its cluster; not FAILED as if the cluster had gone.
assertEquals("RUNNING", store.get(id).orElseThrow().getStatus());
assertNull(store.get(id).orElseThrow().getEndTime());
}
@Test
void aMarkerResumesOnlyTheListingItCameFrom() {
String clusterId = notebookCluster("emr-6.15.0", NOTEBOOK_APPS);
for (int i = 0; i <= EmrNotebookExecutionService.PAGE_SIZE; i++) {
executions.start(request(clusterId));
}
String marker = executions.list(null, null, null, null, null, null).nextToken();
assertEquals(1, executions.list(null, null, null, null, null, marker).items().size());
assertEquals("InvalidRequestException", assertThrows(AwsException.class,
() -> executions.list("null", null, null, null, null, marker)).getErrorCode());
EmrNotebookExecutionService elsewhere = new EmrNotebookExecutionService(store, fixture.service,
new RegionResolver("eu-west-1", ACCOUNT), fixture.clock, RUN);
assertEquals("InvalidRequestException", assertThrows(AwsException.class,
() -> elsewhere.list(null, null, null, null, null, marker)).getErrorCode());
}
@Test
void theAccountRunsAtMostAHundredExecutionsInARegion() {
String clusterId = notebookCluster("emr-6.15.0", NOTEBOOK_APPS);
for (int i = 0; i < EmrNotebookExecutionService.MAX_CONCURRENT_EXECUTIONS; i++) {
executions.start(request(clusterId));
}
AwsException full = assertThrows(AwsException.class, () -> executions.start(request(clusterId)));
assertTrue(full.getMessage().contains("100 concurrent notebook executions"), full.getMessage());
fixture.clock.advance(RUN);
executions.start(request(clusterId));
}
@Test
void listingGivesTheNewestFirstFilteredWithinItsWindowAPageAtATime() {
String clusterId = notebookCluster("emr-6.15.0", NOTEBOOK_APPS);
String old = executions.start(request(clusterId)).getId();
fixture.clock.advance(Duration.ofDays(31));
EmrNotebookExecution editor = request(clusterId);
editor.setEditorId("e-EDITOR");
String first = executions.start(editor).getId();
String second = executions.start(request(clusterId)).getId();
executions.stop(second);
assertEquals(List.of(second, first), ids(executions.list(null, null, null, null, null, null)));
assertEquals(List.of(second, first, old), ids(executions.list(null, null, Instant.EPOCH, null, null, null)));
assertEquals(List.of(first), ids(executions.list("e-EDITOR", null, null, null, null, null)));
assertEquals(List.of(second), ids(executions.list(null, "STOPPED", null, null, null, null)));
assertEquals(List.of(), ids(executions.list(null, null, null, null, "j-OTHER", null)));
assertEquals("ValidationException", assertThrows(AwsException.class,
() -> executions.list(null, "DONE", null, null, null, null)).getErrorCode());
}
private void assertRefused(String clusterId, String message) {
AwsException refused = assertThrows(AwsException.class, () -> executions.start(request(clusterId)));
assertEquals("InvalidRequestException", refused.getErrorCode());
assertTrue(refused.getMessage().contains(message), refused.getMessage());
}
private static List<String> ids(PaginatedResult<EmrNotebookExecution> page) {
return page.items().stream().map(EmrNotebookExecution::getId).toList();
}
private String notebookCluster(String releaseLabel, String applications) {
return fixture.service.runJobFlow(clusterSpec(releaseLabel, applications), REGION).getId();
}
private static EmrCluster clusterSpec(String releaseLabel, String applications) {
EmrCluster cluster = cluster("notebooks", true);
cluster.setReleaseLabel(releaseLabel);
cluster.setApplications(applications);
return cluster;
}
private static EmrNotebookExecution request(String clusterId) {
EmrNotebookExecution request = new EmrNotebookExecution();
request.setEngineId(clusterId);
request.setServiceRole("EMR_Notebooks_DefaultRole");
request.setRelativePath("test.ipynb");
request.setName("run");
return request;
}
}
@@ -1112,7 +1112,8 @@ class EmrServiceContainerStepsTest {
fixture.runStepThread();
ObjectMapper objectMapper = new ObjectMapper();
JsonNode answer = (JsonNode) new EmrHandler(service, mock(EmrStudioService.class), objectMapper)
JsonNode answer = (JsonNode) new EmrHandler(service, mock(EmrStudioService.class),
mock(EmrNotebookExecutionService.class), objectMapper)
.handle("DescribeStep", objectMapper.createObjectNode().put("ClusterId", cluster.getId())
.put("StepId", cluster.getSteps().get(0).getId()), REGION).getEntity();
@@ -2040,7 +2041,8 @@ class EmrServiceContainerStepsTest {
bootstrapping.runStepThread();
String waitingId = bootstrapping.service.runJobFlow(cluster("waiting", true), REGION).getId();
ObjectMapper objectMapper = new ObjectMapper();
EmrHandler handler = new EmrHandler(bootstrapping.service, mock(EmrStudioService.class), objectMapper);
EmrHandler handler = new EmrHandler(bootstrapping.service, mock(EmrStudioService.class),
mock(EmrNotebookExecutionService.class), objectMapper);
String page = ERROR_CODE_PAGES + "BOOTSTRAP_FAILURE_PRIMARY_WITH_NON_ZERO_CODE.html";
JsonNode expected = objectMapper.readTree("""
[{"ErrorCode": "BOOTSTRAP_FAILURE_PRIMARY_WITH_NON_ZERO_CODE",
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.emr.EmrHandler;
import io.floci.aws.services.emr.EmrNotebookExecutionService;
import io.floci.aws.services.emr.EmrService;
import io.floci.aws.services.emr.EmrStudioService;
import io.floci.aws.services.emr.model.EmrCluster;
@@ -73,7 +74,8 @@ class AslExecutorEmrSyncTest {
.sfnService(instance)
.customResourceLiveness(null)
.emrTaskInvoker(new EmrTaskInvoker(
new EmrHandler(emrService, mock(EmrStudioService.class), objectMapper), objectMapper))
new EmrHandler(emrService, mock(EmrStudioService.class),
mock(EmrNotebookExecutionService.class), objectMapper), objectMapper))
.nanoTime(testNanos::get)
.sleeper(testNanos::addAndGet)
.build();