diff --git a/docs/services/emr-serverless.md b/docs/services/emr-serverless.md index a51ab66874..636b868999 100644 --- a/docs/services/emr-serverless.md +++ b/docs/services/emr-serverless.md @@ -1,6 +1,6 @@ # EMR Serverless -EMR Serverless is an AWS service that provides serverless data analytics environments. Floci provides an emulator for the management-plane API (REST JSON) which covers the lifecycle of an Application and of the job runs submitted to it. +EMR Serverless is an AWS service that provides serverless data analytics environments. Floci provides an emulator for the management-plane API (REST JSON) which covers the lifecycle of an Application, of the job runs submitted to it and of its Spark Connect sessions. ## Configuration @@ -34,21 +34,26 @@ The emulator implements the standard AWS `emr-serverless` service endpoints: * `DELETE /applications/{applicationId}/jobruns/{jobRunId}` (CancelJobRun) * `GET /applications/{applicationId}/jobruns/{jobRunId}/attempts` (ListJobRunAttempts) * `GET /applications/{applicationId}/jobruns/{jobRunId}/dashboard` (GetDashboardForJobRun) +* `POST /applications/{applicationId}/sessions` (StartSession) +* `GET /applications/{applicationId}/sessions` (ListSessions) +* `GET /applications/{applicationId}/sessions/{sessionId}` (GetSession) +* `DELETE /applications/{applicationId}/sessions/{sessionId}` (TerminateSession) +* `GET /applications/{applicationId}/sessions/{sessionId}/endpoint` (GetSessionEndpoint) +* `GET /applications/{applicationId}/dashboard` (GetResourceDashboard) * `POST /tags/{resourceArn}` (TagResource) * `DELETE /tags/{resourceArn}?tagKeys=...` (UntagResource) * `GET /tags/{resourceArn}` (ListTagsForResource) -The tagging operations work on application and job run ARNs, as `CreateApplication` and `StartJobRun` -return them (`arn:aws:emr-serverless:::/applications/` and -`.../applications//jobruns/`). They share the tags those calls store, so `GetApplication` and -`GetJobRun` always report the current set. Following the EMR Serverless user guide, a resource holds -at most 50 tags, and `aws:` in any case is reserved as the prefix of a tag key or value. A session ARN -(`.../sessions/`) answers `ResourceNotFoundException`, as sessions are not emulated. Once an -application is deleted, its ARN and its runs' ARNs answer `ResourceNotFoundException` too, while -`GetApplication` and `GetJobRun` still report them. +The tagging operations work on application, job run and session ARNs, as `CreateApplication`, `StartJobRun` and +`StartSession` return them (`arn:aws:emr-serverless:::/applications/`, +`.../applications//jobruns/` and `.../applications//sessions/`). They share the tags those calls +store, so `GetApplication`, `GetJobRun` and `GetSession` always report the current set. Following the EMR Serverless +user guide, a resource holds at most 50 tags, and `aws:` in any case is reserved as the prefix of a tag key or value. +Once an application is deleted, its ARN and its runs' and sessions' ARNs answer `ResourceNotFoundException` too, +while `GetApplication`, `GetJobRun` and `GetSession` still report them. -Applications, job runs, creation client tokens, and tags are scoped to the request's AWS Region. An -application or run created in one Region is not returned by list, get, or tag requests signed for +Applications, job runs, sessions, creation client tokens, and tags are scoped to the request's AWS Region. An +application, run or session created in one Region is not returned by list, get, or tag requests signed for another. `ListApplications` refuses a `states` filter naming a state that does not exist, or more than 7, and a @@ -110,7 +115,8 @@ runner mode a Spark run executes; see [Running Spark job runs](#running-spark-jo a `CANCELLING` one included, as the API reference says "All scheduled and running jobs must be completed or cancelled before stopping an application." It answers `ValidationException`, the one error the model declares for this, with that sentence as its message: AWS's own message is not - recorded, so the wording is Floci's reading. + recorded, so the wording is Floci's reading. It terminates the application's sessions (see + [Sessions](#sessions)). * **ListJobRuns** returns the newest runs first, filtered by `states`, `createdAtAfter`, `createdAtBefore` and `mode`, at most 50 per page. With several `states`, the runs are grouped by state in the order the filter names them. A state or mode that does not exist, or more than 8 @@ -142,6 +148,45 @@ runner mode a Spark run executes; see [Running Spark job runs](#running-spark-jo page asking for a new one, and one whose run has gone a `404`. Like the rest of Floci, the page asks for no credentials. `accessSystemProfileLogs`, for jobs on Lake Formation, changes nothing. +## Sessions + +A session is "a managed connection between your local PySpark client and a Spark driver running on Amazon EMR +Serverless", through Spark Connect. Floci keeps a session and its lifecycle, but runs no Spark driver for it, so +nothing answers Spark Connect at its endpoint. + +* **Starting**: `StartSession` needs a Spark application on `emr-7.13.0` or later, or on the AWS runtime for Apache + Spark (`emr-spark-8.0.0` on), whose `interactiveConfiguration.sessionEnabled` is `true`. As for a job run, a + `CREATED` or `STOPPED` application is started unless its auto-start is off, when the session is refused, and so is + one on a terminated application. Each of these refusals is `ValidationException` in Floci's own wording, as AWS's is + not recorded. `clientToken` is the idempotency token, as for a job run. An application holds at most 25 sessions + that have not ended, as "Each EMR Serverless application supports up to 25 concurrent sessions by default"; a 26th + is refused with `ServiceQuotaExceededException` (HTTP 402). Of `configurationOverrides`, only `runtimeConfiguration` + is kept: "Only runtime configuration overrides are supported." A `runtimeConfiguration` with a member of the wrong + JSON type is refused with `SerializationException`, and a configuration without its `classification` with + `ValidationException`. `releaseLabel` and `networkConfiguration` come from + the application, and `createdBy` is the caller's ARN. +* **States**: a session is `IDLE` as soon as it starts, with `startedAt` and `idleSince` set. It is `TERMINATED` once + it has been idle for its `idleTimeoutMinutes` (0 to 1,000,000, 60 when not given, as "Default timeout is set to 1 + hour"), or once 24 hours have passed since it started, as "Each session has a hard limit of 24 hours by default", + whichever comes first. No source says what an idle timeout of `0` does; Floci reads it as no idle timeout, as for a + job run's `executionTimeoutMinutes`. Floci never reports `SUBMITTED`, `STARTING`, `STARTED`, `BUSY`, `FAILED` or + `TERMINATING`. +* **TerminateSession** ends a session at once as `TERMINATED`; AWS's passes through `TERMINATING` first. A session + that has already ended is refused with `ValidationException`, in Floci's own wording. +* **StopApplication** terminates the application's sessions that have not ended, with `stateDetails` saying so. The + API reference requires a stopping application's job runs to have ended but names no such requirement for sessions, + and once an application is stopped "no resources are running on the application"; AWS's own handling is not + recorded. +* **GetSessionEndpoint** answers for a session that has not ended with an endpoint on Floci's own address + (`/_aws/emr-serverless/sessions//`) and a fresh authentication token that expires in an + hour, as "Authentication tokens are time-limited to 1 hour". Nothing answers Spark Connect there. A session that has + ended is refused with `ValidationException`, in Floci's own wording. +* **ListSessions** returns the newest sessions first, filtered by `states`, `createdAtAfter` and `createdAtBefore`, at + most 50 per page, grouped by state as `ListJobRuns` groups runs. +* **GetResourceDashboard** takes a `resourceType` of `SESSION`, the only one, and gives a link like + `GetDashboardForJobRun`'s, valid for an hour, to a page about the session on Floci's address, which stands in for + the session's Spark UI or Spark History Server. `accessSystemProfileLogs` changes nothing. + A state machine drives applications and job runs through the `emr-serverless:` integrations, `.sync` included; see [Step Functions: Amazon EMR Serverless tasks](step-functions.md#amazon-emr-serverless-tasks). @@ -322,6 +367,6 @@ application's `imageConfiguration`; a `TezTask` image is not used, as Tez's task directory; Spark alone unpacks the others, into its own files folder. Floci reads an archive itself, whatever the execution role may read, though Spark's own read of it uses the role's credentials. * **Custom images**: Floci does not check an `imageUri` against the model's pattern, which would refuse the repository URIs Floci's own ECR hands out, nor that the image was built from its release's base image (AWS refuses one that was not from `emr-7.14.0` and `emr-spark-8.1.0` on), nor the image's size. An image that cannot be pulled fails the run, not the request that names it. An image's digest is resolved as the application starts where its `applicationLevelDigestResolution` is true, or left unset on EMR 7.13 or earlier, as the user guide's table has it, and AWS's "Custom images are resolved to a digest at application start; that digest is used for all jobs until the application restarts": the application's image configuration gets the digest of the image in Floci's ECR as its `resolvedImageDigest`, and each run pulls the image by it until the application starts again; a stopped application reports none. An image outside ECR, one in another account's repository (Floci does not check that the application may pull it), or one Floci's ECR does not hold or cannot read without Docker, has no digest to read and is resolved for each run, as every image is from 7.14 on; any other answer from Floci's ECR fails `StartApplication` with `InternalServerException`; such a run's digest comes from its attempt's own pull (see **Image** above), and a job run's image configurations carry no `applicationLevelDigestResolution`. -* **Not emulated**: the "EMR Serverless Job Run Retry" event, as Floci sends no EMR Serverless events, queuing (`QUEUED`), `totalResourceUtilization` and `billedResourceUtilization`, and `shutdownGracePeriodInSeconds` (accepted and ignored: a cancelled run's driver is stopped at once). +* **Not emulated**: the "EMR Serverless Job Run Retry" event, as Floci sends no EMR Serverless events, queuing (`QUEUED`), `totalResourceUtilization` and `billedResourceUtilization` (of a job run or a session), and `shutdownGracePeriodInSeconds` (accepted and ignored: a cancelled run's driver is stopped at once). * **Instant Start/Stop**: Floci marks the application `STARTED` or `STOPPED` immediately without provisioning actual compute capacity in the background. -* **Data Plane**: Floci does not implement the data-plane API, such as interactive sessions. +* **Sessions run nothing**: a session is kept with its lifecycle, but no Spark driver runs for it, and nothing answers Spark Connect at the endpoint `GetSessionEndpoint` gives (see [Sessions](#sessions)). diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessController.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessController.java index a5146c3e1d..100e940dbd 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessController.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessController.java @@ -12,6 +12,9 @@ import io.floci.aws.services.emrserverless.model.DeleteApplicationResponse; import io.floci.aws.services.emrserverless.model.GetApplicationResponse; import io.floci.aws.services.emrserverless.model.GetDashboardForJobRunResponse; import io.floci.aws.services.emrserverless.model.GetJobRunResponse; +import io.floci.aws.services.emrserverless.model.GetResourceDashboardResponse; +import io.floci.aws.services.emrserverless.model.GetSessionEndpointResponse; +import io.floci.aws.services.emrserverless.model.GetSessionResponse; import io.floci.aws.services.emrserverless.model.JobRun; import io.floci.aws.services.emrserverless.model.JobRunAttemptSummary; import io.floci.aws.services.emrserverless.model.JobRunSummary; @@ -19,10 +22,16 @@ import io.floci.aws.services.emrserverless.model.ListApplicationsRequest; import io.floci.aws.services.emrserverless.model.ListApplicationsResponse; import io.floci.aws.services.emrserverless.model.ListJobRunAttemptsResponse; import io.floci.aws.services.emrserverless.model.ListJobRunsResponse; +import io.floci.aws.services.emrserverless.model.ListSessionsResponse; +import io.floci.aws.services.emrserverless.model.Session; +import io.floci.aws.services.emrserverless.model.SessionSummary; import io.floci.aws.services.emrserverless.model.StartApplicationResponse; import io.floci.aws.services.emrserverless.model.StartJobRunRequest; import io.floci.aws.services.emrserverless.model.StartJobRunResponse; +import io.floci.aws.services.emrserverless.model.StartSessionRequest; +import io.floci.aws.services.emrserverless.model.StartSessionResponse; import io.floci.aws.services.emrserverless.model.StopApplicationResponse; +import io.floci.aws.services.emrserverless.model.TerminateSessionResponse; import io.floci.aws.services.emrserverless.model.UpdateApplicationRequest; import io.floci.aws.services.emrserverless.model.UpdateApplicationResponse; import jakarta.enterprise.context.ApplicationScoped; @@ -48,14 +57,17 @@ public class EmrServerlessController { private final EmrServerlessService service; private final EmrServerlessJobRunService jobRuns; + private final EmrServerlessSessionService sessions; private final EmrServerlessDashboards dashboards; private final RegionResolver regionResolver; @Inject public EmrServerlessController(EmrServerlessService service, EmrServerlessJobRunService jobRuns, - EmrServerlessDashboards dashboards, RegionResolver regionResolver) { + EmrServerlessSessionService sessions, EmrServerlessDashboards dashboards, + RegionResolver regionResolver) { this.service = service; this.jobRuns = jobRuns; + this.sessions = sessions; this.dashboards = dashboards; this.regionResolver = regionResolver; } @@ -127,7 +139,7 @@ public class EmrServerlessController { @POST @Path("/{applicationId}/stop") public StopApplicationResponse stopApplication(@PathParam("applicationId") String applicationId) { - jobRuns.stopApplication(applicationId); + sessions.stopApplication(applicationId); StopApplicationResponse response = new StopApplicationResponse(); return response; } @@ -215,4 +227,84 @@ public class EmrServerlessController { response.setJobRunId(run.getJobRunId()); return response; } + + @POST + @Path("/{applicationId}/sessions") + public StartSessionResponse startSession(@PathParam("applicationId") String applicationId, + StartSessionRequest request) { + Session session = sessions.startSession(applicationId, request); + StartSessionResponse response = new StartSessionResponse(); + response.setApplicationId(session.getApplicationId()); + response.setSessionId(session.getSessionId()); + response.setArn(session.getArn()); + return response; + } + + @GET + @Path("/{applicationId}/sessions") + public ListSessionsResponse listSessions(@PathParam("applicationId") String applicationId, + @QueryParam("states") List states, + @QueryParam("createdAtAfter") String createdAtAfter, + @QueryParam("createdAtBefore") String createdAtBefore, + @QueryParam("maxResults") String maxResults, + @QueryParam("nextToken") String nextToken) { + PaginatedResult page = sessions.listSessions(applicationId, states, + EmrServerlessJobRunService.parseTimestamp(createdAtAfter, "createdAtAfter"), + EmrServerlessJobRunService.parseTimestamp(createdAtBefore, "createdAtBefore"), + Pagination.parseMaxResults(maxResults, "ValidationException"), nextToken); + ListSessionsResponse response = new ListSessionsResponse(); + response.setSessions(page.items()); + response.setNextToken(page.nextToken()); + return response; + } + + @GET + @Path("/{applicationId}/sessions/{sessionId}") + public GetSessionResponse getSession(@PathParam("applicationId") String applicationId, + @PathParam("sessionId") String sessionId) { + GetSessionResponse response = new GetSessionResponse(); + response.setSession(sessions.getSession(applicationId, sessionId)); + return response; + } + + @DELETE + @Path("/{applicationId}/sessions/{sessionId}") + public TerminateSessionResponse terminateSession(@PathParam("applicationId") String applicationId, + @PathParam("sessionId") String sessionId) { + Session session = sessions.terminateSession(applicationId, sessionId); + TerminateSessionResponse response = new TerminateSessionResponse(); + response.setApplicationId(session.getApplicationId()); + response.setSessionId(session.getSessionId()); + return response; + } + + @GET + @Path("/{applicationId}/sessions/{sessionId}/endpoint") + public GetSessionEndpointResponse getSessionEndpoint(@PathParam("applicationId") String applicationId, + @PathParam("sessionId") String sessionId) { + EmrServerlessSessionService.Endpoint endpoint = sessions.sessionEndpoint(applicationId, sessionId); + GetSessionEndpointResponse response = new GetSessionEndpointResponse(); + response.setApplicationId(applicationId); + response.setSessionId(sessionId); + response.setEndpoint(endpoint.url()); + response.setAuthToken(endpoint.authToken()); + response.setAuthTokenExpiresAt(endpoint.authTokenExpiresAt()); + return response; + } + + /** + * The link to a session's application UI ({@link EmrServerlessDashboards}). {@code accessSystemProfileLogs} is for + * sessions on Lake Formation, which Floci runs none of, so it changes nothing. + */ + @GET + @Path("/{applicationId}/dashboard") + public GetResourceDashboardResponse getResourceDashboard(@PathParam("applicationId") String applicationId, + @QueryParam("resourceId") String resourceId, + @QueryParam("resourceType") String resourceType) { + Session session = sessions.dashboardResource(applicationId, resourceId, resourceType); + GetResourceDashboardResponse response = new GetResourceDashboardResponse(); + response.setUrl(dashboards.sessionUrl(regionResolver.getAccountId(), regionResolver.getRegion(), + applicationId, session.getSessionId())); + return response; + } } diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardController.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardController.java index efd09b8d86..c8cc09db06 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardController.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardController.java @@ -4,6 +4,7 @@ import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.Html; import io.floci.aws.core.common.RequestScopes; import io.floci.aws.services.emrserverless.model.JobRun; +import io.floci.aws.services.emrserverless.model.Session; import jakarta.inject.Inject; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; @@ -12,45 +13,64 @@ import jakarta.ws.rs.QueryParam; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; +import java.time.Instant; import java.util.ArrayList; import java.util.List; /** - * The page a {@code GetDashboardForJobRun} link opens ({@link EmrServerlessDashboards}). EMR Serverless opens the run's - * live Spark or Tez UI while it runs and its Spark History Server or persistent Tez UI once it has ended; Floci keeps - * neither, so the page shows the attempt as GetJobRun gives it and where its driver's logs go, as it was admitted. A - * link that is not one of this process's, or whose hour has passed, opens a refusal instead, and so does one whose run - * has gone. Like the rest of Floci the page takes no AWS credentials: the link is all it asks for. + * The page a {@code GetDashboardForJobRun} or {@code GetResourceDashboard} link opens + * ({@link EmrServerlessDashboards}). EMR Serverless opens the run's live Spark or Tez UI while it runs and its Spark + * History Server or persistent Tez UI once it has ended, and a session's live Spark UI or Spark History Server + * likewise; Floci keeps neither, so the page shows the attempt as GetJobRun gives it and where its driver's logs go, as + * it was admitted, or the session as GetSession gives it. A link that is not one of this process's, or whose hour has + * passed, opens a refusal instead, and so does one whose run or session has gone. Like the rest of Floci the page takes + * no AWS credentials: the link is all it asks for. */ @Path(EmrServerlessDashboards.PATH) public class EmrServerlessDashboardController { // No source gives AWS's wording for these; they are Floci's. static final String INVALID = "This dashboard link is not valid, or its hour has passed. Call" - + " GetDashboardForJobRun for a new one."; + + " GetDashboardForJobRun or GetResourceDashboard for a new one."; static final String NO_UI = "Floci keeps no Spark UI, Tez UI or Spark History Server for a job run, so this page" + " stands in for the application UI EMR Serverless opens. The driver's output is in its logs."; + static final String NO_SESSION_UI = "Floci keeps no Spark UI or Spark History Server for a session, and runs no" + + " Spark driver for one, so this page stands in for the application UI EMR Serverless opens."; private final EmrServerlessDashboards dashboards; private final EmrServerlessJobRunService jobRuns; + private final EmrServerlessSessionService sessions; @Inject - public EmrServerlessDashboardController(EmrServerlessDashboards dashboards, EmrServerlessJobRunService jobRuns) { + public EmrServerlessDashboardController(EmrServerlessDashboards dashboards, EmrServerlessJobRunService jobRuns, + EmrServerlessSessionService sessions) { this.dashboards = dashboards; this.jobRuns = jobRuns; + this.sessions = sessions; } @GET @Produces(MediaType.TEXT_HTML) public Response dashboard(@QueryParam("account") String accountId, @QueryParam("region") String region, @QueryParam("application") String applicationId, - @QueryParam("jobRun") String jobRunId, @QueryParam("attempt") String attempt, - @QueryParam("expires") String expires, + @QueryParam("jobRun") String jobRunId, @QueryParam("session") String sessionId, + @QueryParam("attempt") String attempt, @QueryParam("expires") String expires, @QueryParam("signature") String signature) { - EmrServerlessDashboards.Link link = dashboards.verified(accountId, region, applicationId, jobRunId, attempt, - expires, signature); + EmrServerlessDashboards.Link link = dashboards.verified(accountId, region, applicationId, jobRunId, sessionId, + attempt, expires, signature); if (link == null) { - return page(403, "Job run dashboard", List.of("

" + Html.escape(INVALID) + "

")); + return page(403, sessionId != null ? "Session dashboard" : "Job run dashboard", + List.of("

" + Html.escape(INVALID) + "

")); + } + if (link.sessionId() != null) { + Session session; + try { + session = RequestScopes.callAs(link.accountId(), link.region(), + () -> sessions.getSession(link.applicationId(), link.sessionId())); + } catch (AwsException e) { + return page(404, "Session " + link.sessionId(), List.of("

" + Html.escape(e.getMessage()) + "

")); + } + return page(200, "Session " + link.sessionId(), body(session)); } EmrServerlessJobRunService.DashboardView view; try { @@ -84,7 +104,29 @@ public class EmrServerlessDashboardController { return lines; } - // A row of the table, left out when the run has no such value. + private static List body(Session session) { + List lines = new ArrayList<>(); + lines.add(""); + row(lines, "Application", session.getApplicationId()); + row(lines, "Session", session.getSessionId()); + row(lines, "Name", session.getName()); + row(lines, "State", session.getState()); + row(lines, "State details", session.getStateDetails()); + row(lines, "Release label", session.getReleaseLabel()); + row(lines, "Created", text(session.getCreatedAt())); + row(lines, "Started", text(session.getStartedAt())); + row(lines, "Idle since", text(session.getIdleSince())); + row(lines, "Ended", text(session.getEndedAt())); + lines.add("
"); + lines.add("

" + Html.escape(NO_SESSION_UI) + "

"); + return lines; + } + + private static String text(Instant instant) { + return instant != null ? instant.toString() : null; + } + + // A row of the table, left out when the run or session has no such value. private static void row(List lines, String name, String value) { if (value != null && !value.isEmpty()) { lines.add("" + Html.escape(name) + "" + Html.escape(value) + ""); diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessDashboards.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessDashboards.java index c5fee03562..3108cdbed5 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessDashboards.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessDashboards.java @@ -16,12 +16,13 @@ import java.time.Duration; import java.util.HexFormat; /** - * The links {@code GetDashboardForJobRun} gives: "a URL that you can use to access the application UIs for a job run", - * which "is valid for one hour after you generate it. To access the application UI after that hour elapses, you must - * invoke the API again to generate a new URL." Floci keeps no Spark UI or Spark History Server for a run, so a link - * opens a page of Floci's own about the run ({@link EmrServerlessDashboardController}). It names the run's account, - * Region, application, run and attempt, and when it expires, signed with a key this process makes: a link changed, or - * past its hour, opens nothing, and the links given before a restart open nothing after it. + * The links {@code GetDashboardForJobRun} gives, "a URL that you can use to access the application UIs for a job run", + * and {@code GetResourceDashboard} gives for a session. Each "is valid for one hour after you generate it. To access + * the application UI after that hour elapses, you must invoke the API again to generate a new URL." Floci keeps no + * Spark UI or Spark History Server for a run or a session, so a link opens a page of Floci's own about it + * ({@link EmrServerlessDashboardController}). It names the account, Region, application, the run and its attempt or + * the session, and when it expires, signed with a key this process makes: a link changed, or past its hour, opens + * nothing, and the links given before a restart open nothing after it. */ @ApplicationScoped public class EmrServerlessDashboards { @@ -47,33 +48,41 @@ public class EmrServerlessDashboards { this.key = key.clone(); } - /** What a link names: one attempt of a run, and the second, since the epoch, it expires at. */ - public record Link(String accountId, String region, String applicationId, String jobRunId, int attempt, - long expires) { + /** + * What a link names: one attempt of a run, or a session, whose {@code attempt} is 0, and the second, since the + * epoch, it expires at. + */ + public record Link(String accountId, String region, String applicationId, String jobRunId, String sessionId, + int attempt, long expires) { } /** A link to a run's attempt, valid for {@link #VALIDITY} from now. */ public String url(String accountId, String region, String applicationId, String jobRunId, int attempt) { - Link link = new Link(accountId, region, applicationId, jobRunId, attempt, - clock.instant().plus(VALIDITY).getEpochSecond()); - return baseUrl + PATH + "?account=" + encoded(accountId) + "®ion=" + encoded(region) - + "&application=" + encoded(applicationId) + "&jobRun=" + encoded(jobRunId) - + "&attempt=" + attempt + "&expires=" + link.expires() + "&signature=" + signature(link); + Link link = new Link(accountId, region, applicationId, jobRunId, null, attempt, expiry()); + return prefix(link) + "&jobRun=" + encoded(jobRunId) + "&attempt=" + attempt + suffix(link); + } + + /** A link to a session, valid for {@link #VALIDITY} from now. */ + public String sessionUrl(String accountId, String region, String applicationId, String sessionId) { + Link link = new Link(accountId, region, applicationId, null, sessionId, 0, expiry()); + return prefix(link) + "&session=" + encoded(sessionId) + suffix(link); } /** - * The link a page request's parameters name, or null when one is missing or malformed, the signature is not this - * process's for them, or the link has expired. + * The link a page request's parameters name, or null when one is missing or malformed, it names both a run and a + * session or neither, the signature is not this process's for them, or the link has expired. A session's link + * carries no attempt. */ - public Link verified(String accountId, String region, String applicationId, String jobRunId, String attempt, - String expires, String signature) { - if (accountId == null || region == null || applicationId == null || jobRunId == null || signature == null) { + public Link verified(String accountId, String region, String applicationId, String jobRunId, String sessionId, + String attempt, String expires, String signature) { + if (accountId == null || region == null || applicationId == null || signature == null + || (jobRunId == null) == (sessionId == null) || (sessionId != null && attempt != null)) { return null; } Link link; try { - link = new Link(accountId, region, applicationId, jobRunId, Integer.parseInt(attempt), - Long.parseLong(expires)); + link = new Link(accountId, region, applicationId, jobRunId, sessionId, + sessionId != null ? 0 : Integer.parseInt(attempt), Long.parseLong(expires)); } catch (NumberFormatException e) { return null; } @@ -85,8 +94,24 @@ public class EmrServerlessDashboards { return link; } + private long expiry() { + return clock.instant().plus(VALIDITY).getEpochSecond(); + } + + private String prefix(Link link) { + return baseUrl + PATH + "?account=" + encoded(link.accountId()) + "®ion=" + encoded(link.region()) + + "&application=" + encoded(link.applicationId()); + } + + private String suffix(Link link) { + return "&expires=" + link.expires() + "&signature=" + signature(link); + } + + // Over what the link names; a run's link and a session's are told apart, so neither opens as the other. private String signature(Link link) { - String signed = String.join("\n", link.accountId(), link.region(), link.applicationId(), link.jobRunId(), + String signed = String.join("\n", link.accountId(), link.region(), link.applicationId(), + link.jobRunId() != null ? "jobRun" : "session", + link.jobRunId() != null ? link.jobRunId() : link.sessionId(), String.valueOf(link.attempt()), String.valueOf(link.expires())); try { Mac mac = Mac.getInstance(ALGORITHM); diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java index d929c4ebe2..fb8c7f7885 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java @@ -1,10 +1,8 @@ package io.floci.aws.services.emrserverless; -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 io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; @@ -44,7 +42,6 @@ import java.time.format.DateTimeParseException; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; @@ -134,7 +131,7 @@ public class EmrServerlessJobRunService implements Resettable { // The EMR Serverless 7.11.0 release notes: for BATCH job runs the maximum "is 7 days from this release // onwards", and the timeout "can no longer be set to 0". private static final long MAX_BATCH_EXECUTION_TIMEOUT_MINUTES = 10_080; - private static final Pattern RELEASE_LABEL = Pattern.compile("emr-(\\d{1,6})\\.(\\d{1,6})(?:\\..*)?"); + static final Pattern RELEASE_LABEL = Pattern.compile("emr-(\\d{1,6})\\.(\\d{1,6})(?:\\..*)?"); // The AWS runtime for Apache Spark, emr-spark-8.0.0 on (and emr-spark-8.0-preview). private static final Pattern SPARK_RUNTIME_RELEASE_LABEL = Pattern.compile("emr-spark-(\\d{1,6})\\.(\\d{1,6})(?:[.-].*)?"); @@ -273,8 +270,9 @@ public class EmrServerlessJobRunService implements Resettable { StartJobRunRequest body = request != null ? request : new StartJobRunRequest(); validate(body); applications.getApplication(applicationId); - JsonNode original = requestOf(applicationId, body); - JobRunRecord existing = runWithClientToken(body.getClientToken()); + JsonNode original = EmrServerlessService.retriedRequest(objectMapper, applicationId, body); + JobRunRecord existing = EmrServerlessService.startedWithClientToken(store.scan(key -> true), + body.getClientToken(), JobRunRecord::getClientToken, record -> inRequestRegion(record.getJobRun())); if (existing != null) { if (!original.equals(existing.getRequest())) { throw new AwsException("ConflictException", "Request did not match the original", 409); @@ -285,7 +283,8 @@ public class EmrServerlessJobRunService implements Resettable { if (body.getTags() != null) { EmrServerlessService.validateTags(body.getTags()); } - JobRunRecord record = applications.admitJobRun(applicationId, app -> checkBatchTimeout(app, body), app -> { + JobRunRecord record = applications.admit(applicationId, "a job run is submitted", + app -> checkBatchTimeout(app, body), app -> { JobRunRecord admitted = newRun(app, body, original); if (sparkRunner != null) { launch(admitted, app); @@ -376,14 +375,8 @@ public class EmrServerlessJobRunService implements Resettable { public synchronized PaginatedResult listJobRuns(String applicationId, List states, Instant createdAtAfter, Instant createdAtBefore, String mode, Integer maxResults, String nextToken) { - List violations = new ArrayList<>(); - if (maxResults != null) { - String violation = SmithyValidationErrors.outOfRange("maxResults", maxResults, 1, MAX_LIST_RESULTS); - if (violation != null) { - violations.add(violation); - } - } - violations.addAll(EmrServerlessService.statesViolations(states, STATES, MAX_FILTER_STATES)); + List violations = EmrServerlessService.listViolations(maxResults, MAX_LIST_RESULTS, states, STATES, + MAX_FILTER_STATES); if (mode != null && !MODES.contains(mode)) { violations.add(SmithyValidationErrors.notInEnum(mode, "mode", MODES)); } @@ -391,7 +384,6 @@ public class EmrServerlessJobRunService implements Resettable { throw SmithyValidationErrors.validationException(violations); } List matching = new ArrayList<>(); - Map cursors = new HashMap<>(); for (JobRunRecord record : store.scan(key -> true)) { JobRun run = record.getJobRun(); if (!applicationId.equals(run.getApplicationId()) || !inRequestRegion(run)) { @@ -404,18 +396,15 @@ public class EmrServerlessJobRunService implements Resettable { || (mode != null && !mode.equals(run.getMode() != null ? run.getMode() : MODE_BATCH))) { continue; } - int group = states == null || states.isEmpty() ? 0 : states.indexOf(run.getState()); - cursors.put(run.getJobRunId(), String.format("%02d%020d%s", group, - Long.MAX_VALUE - run.getCreatedAt().toEpochMilli(), run.getJobRunId())); matching.add(record); } String namespace = String.join("|", "ListJobRuns", applicationId, String.valueOf(states != null ? states : List.of()), String.valueOf(createdAtAfter), String.valueOf(createdAtBefore), String.valueOf(mode)); - PaginatedResult page = Pagination.paginate(matching, - record -> cursors.get(record.getJobRun().getJobRunId()), - maxResults != null ? maxResults : MAX_LIST_RESULTS, nextToken, namespace, - token -> new AwsException("ValidationException", "Invalid nextToken.", 400)); + PaginatedResult page = EmrServerlessService.pageByState(matching, + record -> record.getJobRun().getJobRunId(), record -> record.getJobRun().getState(), + record -> record.getJobRun().getCreatedAt(), states, maxResults, MAX_LIST_RESULTS, nextToken, + namespace); return new PaginatedResult<>(page.items().stream().map(EmrServerlessJobRunService::toSummary).toList(), page.nextToken()); } @@ -522,7 +511,8 @@ public class EmrServerlessJobRunService implements Resettable { run.setName(request.getName()); run.setArn(AwsArnUtils.Arn.of("emr-serverless", applicationArn.region(), applicationArn.accountId(), applicationArn.resource() + "/jobruns/" + jobRunId).toString()); - run.setCreatedBy(createdBy(applicationArn.accountId())); + run.setCreatedBy(EmrServerlessService.createdBy(iamService, requestContext, regionResolver, + applicationArn.accountId())); run.setCreatedAt(now); run.setUpdatedAt(now); run.setExecutionRole(request.getExecutionRoleArn()); @@ -1258,39 +1248,6 @@ public class EmrServerlessJobRunService implements Resettable { .orElseThrow(() -> EmrServerlessService.resourceNotFound(resource.arn())); } - private JobRunRecord runWithClientToken(String clientToken) { - for (JobRunRecord record : store.scan(key -> true)) { - if (clientToken.equals(record.getClientToken()) && inRequestRegion(record.getJobRun())) { - return record; - } - } - return null; - } - - /** - * What a retry must repeat: the application and every member of the body but the token itself. - * Read back from its JSON text, so that its numbers compare equal to those of a stored request - * once storage has written and read it. - */ - private JsonNode requestOf(String applicationId, StartJobRunRequest request) { - ObjectNode node; - try { - node = (ObjectNode) objectMapper.readTree(objectMapper.writeValueAsString(request)); - } catch (JsonProcessingException e) { - throw new IllegalStateException("Cannot serialize a StartJobRun request", e); - } - node.remove("clientToken"); - node.put("applicationId", applicationId); - return node; - } - - // The caller, as GetCallerIdentity reports it; the account root for a key IAM does not know. - private String createdBy(String accountId) { - String accessKeyId = requestContext != null ? requestContext.getAccessKeyId() : null; - return iamService.resolveCallerArn(accessKeyId) - .orElseGet(() -> regionResolver.buildGlobalArn("iam", accountId, "root")); - } - private boolean inRequestRegion(JobRun run) { return regionResolver.getRegion().equals(AwsArnUtils.parse(run.getArn()).region()); } @@ -1305,11 +1262,9 @@ public class EmrServerlessJobRunService implements Resettable { if (request.getClientToken() == null) { violations.add(SmithyValidationErrors.notNull("clientToken")); } - if (request.getExecutionRoleArn() == null) { - violations.add(SmithyValidationErrors.notNull("executionRoleArn")); - } else if (!ROLE_ARN.matcher(request.getExecutionRoleArn()).matches()) { - violations.add("Value at 'executionRoleArn' failed to satisfy constraint: " - + "Member must satisfy regular expression pattern: " + ROLE_ARN_PATTERN); + String roleViolation = executionRoleViolation(request.getExecutionRoleArn()); + if (roleViolation != null) { + violations.add(roleViolation); } if (request.getMode() != null && !MODES.contains(request.getMode())) { violations.add(SmithyValidationErrors.notInEnum(request.getMode(), "mode", MODES)); @@ -1346,6 +1301,16 @@ public class EmrServerlessJobRunService implements Resettable { } } + /** What is wrong with a request's {@code executionRoleArn}, which the model requires: null when nothing is. */ + static String executionRoleViolation(String executionRoleArn) { + if (executionRoleArn == null) { + return SmithyValidationErrors.notNull("executionRoleArn"); + } + return ROLE_ARN.matcher(executionRoleArn).matches() ? null + : "Value at 'executionRoleArn' failed to satisfy constraint: " + + "Member must satisfy regular expression pattern: " + ROLE_ARN_PATTERN; + } + /** * The members of a run's {@code retryPolicy} it gives, each an integer in the model. A restJson1 service * refuses a body member of another type, a string, a boolean or a fraction where an integer goes, with @@ -1390,12 +1355,12 @@ public class EmrServerlessJobRunService implements Resettable { // 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. - private static boolean sparkRuntime(String releaseLabel) { + static boolean sparkRuntime(String releaseLabel) { return releaseAtLeast(SPARK_RUNTIME_RELEASE_LABEL, releaseLabel, 8, 0); } // Whether releaseLabel is of the family labelPattern matches, at major.minor or later. - private static boolean releaseAtLeast(Pattern labelPattern, String releaseLabel, int major, int minor) { + static boolean releaseAtLeast(Pattern labelPattern, String releaseLabel, int major, int minor) { Matcher matcher = labelPattern.matcher(releaseLabel != null ? releaseLabel : ""); if (!matcher.matches()) { return false; diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessService.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessService.java index 0f55705d72..d6cd9bd856 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessService.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessService.java @@ -1,6 +1,10 @@ package io.floci.aws.services.emrserverless; +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 io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; @@ -22,6 +26,7 @@ import io.floci.aws.services.emrserverless.model.ImageConfiguration; import io.floci.aws.services.emrserverless.model.ListApplicationsRequest; import io.floci.aws.services.emrserverless.model.UpdateApplicationRequest; import io.floci.aws.services.emrserverless.model.WorkerTypeSpecification; +import io.floci.aws.services.iam.IamService; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; @@ -31,6 +36,7 @@ import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Date; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -39,6 +45,7 @@ import java.util.Set; import java.util.UUID; import java.util.function.Consumer; import java.util.function.Function; +import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -82,8 +89,8 @@ public class EmrServerlessService { private static final int MAX_APPLICATION_STATES = 7; private static final int MAX_LIST_RESULTS = 50; - /** What an EMR Serverless resource ARN names: an application, or one of its job runs. */ - public record ResourceArn(String arn, String applicationId, String jobRunId) {} + /** What an EMR Serverless resource ARN names: an application, or one of its job runs or sessions. */ + public record ResourceArn(String arn, String applicationId, String jobRunId, String sessionId) {} private final EmulatorConfig config; private final AccountAwareStorageBackend storage; @@ -174,15 +181,8 @@ public class EmrServerlessService { } public PaginatedResult listApplications(ListApplicationsRequest request) { - List violations = new ArrayList<>(); - if (request.getMaxResults() != null) { - String violation = SmithyValidationErrors.outOfRange("maxResults", request.getMaxResults(), 1, - MAX_LIST_RESULTS); - if (violation != null) { - violations.add(violation); - } - } - violations.addAll(statesViolations(request.getStates(), APPLICATION_STATES, MAX_APPLICATION_STATES)); + List violations = listViolations(request.getMaxResults(), MAX_LIST_RESULTS, request.getStates(), + APPLICATION_STATES, MAX_APPLICATION_STATES); if (!violations.isEmpty()) { throw SmithyValidationErrors.validationException(violations); } @@ -487,15 +487,17 @@ public class EmrServerlessService { } /** - * Admits a job run to the application and returns what {@code admit} builds from it. An + * Admits a job run or a session to the application and returns what {@code admit} builds from it. An * application "only accepts jobs when it's in" STARTED, and auto-start, on unless the * application turns it off, starts a CREATED or STOPPED one "on job submission" (EMR Serverless - * user guide, "Application states" and "Default application behavior"). {@code check} refuses a - * run against the application before auto-start can change it. This service's lock is held - * throughout, so the application cannot be updated, stopped or deleted while the run is admitted. + * user guide, "Application states" and "Default application behavior"); StartSession's "The application + * must be in the STARTED state or have AutoStart enabled" is the same rule. {@code check} refuses the + * submission against the application before auto-start can change it, and {@code submission} says what it + * is in the refusal of a stopped application. This service's lock is held throughout, so the application + * cannot be updated, stopped or deleted while the submission is admitted. */ - public synchronized T admitJobRun(String applicationId, Consumer check, - Function admit) { + public synchronized T admit(String applicationId, String submission, Consumer check, + Function admit) { Application app = getApplication(applicationId); String state = app.getState(); if ("TERMINATED".equals(state)) { @@ -505,7 +507,7 @@ public class EmrServerlessService { if (!"STARTED".equals(state)) { if (!autoStartEnabled(app)) { throw new AwsException("ValidationException", "Application " + applicationId - + " must be started before a job run is submitted, as its auto-start is disabled.", 400); + + " must be started before " + submission + ", as its auto-start is disabled.", 400); } startApplication(applicationId); app = getApplication(applicationId); @@ -544,8 +546,8 @@ public class EmrServerlessService { /** * Parses a tagging ARN: {@code arn::emr-serverless:::/applications/}, - * the form CreateApplication returns, with {@code /jobruns/} for a job run. An ARN of another - * Region names nothing here, and neither does a session's, as sessions are not emulated. + * the form CreateApplication returns, with {@code /jobruns/} for a job run and {@code /sessions/} for a + * session. An ARN of another Region names nothing here. */ public ResourceArn resourceArn(String arn) { AwsArnUtils.Arn parsed; @@ -558,10 +560,12 @@ public class EmrServerlessService { if (!"emr-serverless".equals(parsed.service()) || !matcher.matches()) { throw new AwsException("ValidationException", "Invalid resourceArn: " + arn, 400); } - if (!parsed.region().equals(regionResolver.getRegion()) || "sessions".equals(matcher.group(2))) { + if (!parsed.region().equals(regionResolver.getRegion())) { throw resourceNotFound(arn); } - return new ResourceArn(arn, matcher.group(1), matcher.group(3)); + boolean session = "sessions".equals(matcher.group(2)); + return new ResourceArn(arn, matcher.group(1), session ? null : matcher.group(3), + session ? matcher.group(3) : null); } /** Whether the application exists and has not been deleted, which leaves it TERMINATED. */ @@ -571,7 +575,7 @@ public class EmrServerlessService { /** * Runs {@code use} on the application when it exists and has not been deleted, under this service's - * lock, so that it cannot be deleted meanwhile, as with {@link #admitJobRun}; returns whether it ran. + * lock, so that it cannot be deleted meanwhile, as with {@link #admit}; returns whether it ran. */ public synchronized boolean whileLive(String applicationId, Consumer use) { Optional app = live(applicationId); @@ -624,11 +628,47 @@ public class EmrServerlessService { return remaining; } + /** + * What is wrong with a ListApplications, ListJobRuns or ListSessions request's {@code maxResults} and + * {@code states}. + */ + static List listViolations(Integer maxResults, int maxListResults, List states, + List allowed, int maxStates) { + List violations = new ArrayList<>(); + if (maxResults != null) { + String violation = SmithyValidationErrors.outOfRange("maxResults", maxResults, 1, maxListResults); + if (violation != null) { + violations.add(violation); + } + } + violations.addAll(statesViolations(states, allowed, maxStates)); + return violations; + } + + /** + * 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. + */ + static PaginatedResult pageByState(List matching, Function id, Function state, + Function createdAt, List states, Integer maxResults, + int defaultMaxResults, String nextToken, String namespace) { + Map 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))); + } + return Pagination.paginate(matching, item -> cursors.get(id.apply(item)), + maxResults != null ? maxResults : defaultMaxResults, nextToken, namespace, + token -> new AwsException("ValidationException", "Invalid nextToken.", 400)); + } + /** * The violations of a {@code states} filter: at most {@code max} states, each one of * {@code allowed}. A typo would otherwise match nothing and list nothing. */ - static List statesViolations(List states, List allowed, int max) { + private static List statesViolations(List states, List allowed, int max) { List violations = new ArrayList<>(); if (states == null) { return violations; @@ -717,11 +757,51 @@ public class EmrServerlessService { return text.regionMatches(true, 0, RESERVED_PREFIX, 0, RESERVED_PREFIX.length()); } - /** An application or job run id: 16 lowercase hexadecimal characters, within the model's [0-9a-z]+. */ + /** An application, job run or session id: 16 lowercase hexadecimal characters, within the model's [0-9a-z]+. */ static String newId() { return UUID.randomUUID().toString().replace("-", "").substring(0, 16); } + /** A job run's or session's {@code createdBy}: the caller, as GetCallerIdentity reports it, or else the root. */ + static String createdBy(IamService iamService, RequestContext requestContext, RegionResolver regionResolver, + String accountId) { + String accessKeyId = requestContext != null ? requestContext.getAccessKeyId() : null; + return iamService.resolveCallerArn(accessKeyId) + .orElseGet(() -> regionResolver.buildGlobalArn("iam", accountId, "root")); + } + + /** + * The run or session that StartJobRun or StartSession started with {@code clientToken}, which a retry returns, or + * null. A client token is the request's Region's: reused on another application, it finds the run or session it + * started there, whose request then does not match the retry's. + */ + static T startedWithClientToken(List records, String clientToken, Function tokenOf, + Predicate inRequestRegion) { + for (T record : records) { + if (clientToken.equals(tokenOf.apply(record)) && inRequestRegion.test(record)) { + return record; + } + } + return null; + } + + /** + * 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 + * request once storage has written and read it. + */ + static JsonNode retriedRequest(ObjectMapper objectMapper, String applicationId, Object request) { + ObjectNode node; + try { + node = (ObjectNode) objectMapper.readTree(objectMapper.writeValueAsString(request)); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Cannot serialize a " + request.getClass().getSimpleName(), e); + } + node.remove("clientToken"); + node.put("applicationId", applicationId); + return node; + } + private String buildArn(String id) { String region = regionResolver.getRegion(); String accountId = requestContext != null && requestContext.getAccountId() != null ? requestContext.getAccountId() : config.defaultAccountId(); diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSessionService.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSessionService.java new file mode 100644 index 0000000000..2469d3cd09 --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSessionService.java @@ -0,0 +1,494 @@ +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 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.RegionResolver; +import io.floci.aws.core.common.RequestContext; +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.emrserverless.model.Application; +import io.floci.aws.services.emrserverless.model.Session; +import io.floci.aws.services.emrserverless.model.SessionRecord; +import io.floci.aws.services.emrserverless.model.SessionSummary; +import io.floci.aws.services.emrserverless.model.StartSessionRequest; +import io.floci.aws.services.iam.IamService; +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; +import java.util.Set; + +/** + * EMR Serverless sessions: "a managed connection between your local PySpark client and a Spark driver running on Amazon + * EMR Serverless", through Spark Connect (EMR Serverless user guide, "Run interactive sessions with Amazon EMR + * Serverless through Spark Connect"). Floci keeps each session and its lifecycle but starts no Spark driver for it: a + * session is IDLE once started, nothing answers Spark Connect at its endpoint, and it ends when it is terminated, when + * its idle timeout or its 24 hours pass, or when its application stops. + */ +@ApplicationScoped +public class EmrServerlessSessionService { + + private static final Logger LOG = Logger.getLogger(EmrServerlessSessionService.class); + + static final String STATE_IDLE = "IDLE"; + static final String STATE_TERMINATED = "TERMINATED"; + private static final List STATES = + List.of("SUBMITTED", "STARTING", "STARTED", STATE_IDLE, "BUSY", "FAILED", "TERMINATING", STATE_TERMINATED); + private static final Set ENDED = Set.of("FAILED", STATE_TERMINATED); + private static final List RESOURCE_TYPES = List.of("SESSION"); + // SessionStateSet holds 1 to 8 states; a ListSessions page holds 1 to 50 sessions. + private static final int MAX_FILTER_STATES = 8; + private static final int MAX_LIST_RESULTS = 50; + // "Each EMR Serverless application supports up to 25 concurrent sessions by default." + static final int MAX_CONCURRENT_SESSIONS = 25; + // "Sessions end after a configurable idle timeout. Default timeout is set to 1 hour." + static final long DEFAULT_IDLE_TIMEOUT_MINUTES = 60; + private static final long MAX_IDLE_TIMEOUT_MINUTES = 1_000_000; + // "Each session has a hard limit of 24 hours by default, after which it auto-terminates even if it is actively + // running a task." + 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"; + // 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 HARD_LIMIT_REACHED = "The session reached its 24 hour limit."; + static final String APPLICATION_STOPPED = "The session's application was stopped."; + + private final AccountAwareStorageBackend store; + private final EmrServerlessService applications; + private final EmrServerlessJobRunService jobRuns; + private final IamService iamService; + private final RegionResolver regionResolver; + private final RequestContext requestContext; + 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, + EmrServerlessJobRunService jobRuns, IamService iamService, + RegionResolver regionResolver, RequestContext requestContext, + ObjectMapper objectMapper, EmulatorConfig config, Clock clock) { + this(storageFactory.create("emrserverless", "emr-serverless-sessions.json", new TypeReference<>() {}), + applications, jobRuns, iamService, regionResolver, requestContext, objectMapper, clock, + config.effectiveBaseUrl()); + } + + EmrServerlessSessionService(AccountAwareStorageBackend store, EmrServerlessService applications, + EmrServerlessJobRunService jobRuns, IamService iamService, + RegionResolver regionResolver, RequestContext requestContext, + ObjectMapper objectMapper, Clock clock, String baseUrl) { + this.store = store; + this.applications = applications; + this.jobRuns = jobRuns; + this.iamService = iamService; + this.regionResolver = regionResolver; + this.requestContext = requestContext; + this.objectMapper = objectMapper; + this.clock = clock; + this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl; + } + + /** + * Starts a session, which "The application must be in the STARTED state or have AutoStart enabled, and have + * interactive sessions enabled" for, on "EMR release 7.13.0 and later", and, as "Spark Connect is supported only + * for the Apache Spark engine", on a Spark application. A retry with the same client token returns the session it + * started, and one whose request differs is refused, as StartJobRun's is. An application holds at most + * {@link #MAX_CONCURRENT_SESSIONS} sessions that have not ended. + */ + public synchronized Session startSession(String applicationId, StartSessionRequest request) { + StartSessionRequest body = request != null ? request : new StartSessionRequest(); + validate(body); + applications.getApplication(applicationId); + JsonNode original = EmrServerlessService.retriedRequest(objectMapper, applicationId, body); + SessionRecord existing = EmrServerlessService.startedWithClientToken(store.scan(key -> true), + body.getClientToken(), SessionRecord::getClientToken, record -> inRequestRegion(record.getSession())); + if (existing != null) { + if (!original.equals(existing.getRequest())) { + throw new AwsException("ConflictException", "Request did not match the original", 409); + } + return copy(settle(existing).getSession()); + } + // Before admission, which may auto-start the application: a refused session leaves it as it was. + if (body.getTags() != null) { + EmrServerlessService.validateTags(body.getTags()); + } + SessionRecord record = applications.admit(applicationId, "a session is started", this::checkAdmissible, + app -> newSession(app, body, original)); + LOG.infov("Started EMR Serverless session {0} on application {1}", record.getSession().getSessionId(), + applicationId); + return copy(record.getSession()); + } + + public synchronized Session getSession(String applicationId, String sessionId) { + applications.getApplication(applicationId); + return copy(settle(findSession(applicationId, sessionId)).getSession()); + } + + /** + * The application's sessions in the request's Region, newest first, grouped by state as ListJobRuns' runs are. + */ + public synchronized PaginatedResult listSessions(String applicationId, List states, + Instant createdAtAfter, Instant createdAtBefore, + Integer maxResults, String nextToken) { + List violations = EmrServerlessService.listViolations(maxResults, MAX_LIST_RESULTS, states, STATES, + MAX_FILTER_STATES); + if (!violations.isEmpty()) { + throw SmithyValidationErrors.validationException(violations); + } + applications.getApplication(applicationId); + List matching = new ArrayList<>(); + for (SessionRecord record : store.scan(key -> true)) { + Session session = record.getSession(); + if (!applicationId.equals(session.getApplicationId()) || !inRequestRegion(session)) { + continue; + } + settle(record); + if ((states != null && !states.isEmpty() && !states.contains(session.getState())) + || (createdAtAfter != null && !session.getCreatedAt().isAfter(createdAtAfter)) + || (createdAtBefore != null && !session.getCreatedAt().isBefore(createdAtBefore))) { + continue; + } + matching.add(session); + } + String namespace = String.join("|", "ListSessions", applicationId, + String.valueOf(states != null ? states : List.of()), String.valueOf(createdAtAfter), + String.valueOf(createdAtBefore)); + PaginatedResult 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()); + } + + /** + * Terminates a session that has not ended: "After you terminate a session, it enters the TERMINATING state and + * then the TERMINATED state." With no driver to stop, Floci's is TERMINATED at once. One that has already ended + * is refused; no source gives AWS's answer for it, so the wording is Floci's. + */ + public synchronized Session terminateSession(String applicationId, String sessionId) { + applications.getApplication(applicationId); + SessionRecord record = settle(findSession(applicationId, sessionId)); + if (ENDED.contains(record.getSession().getState())) { + throw new AwsException("ValidationException", "Session " + sessionId + " has already ended.", 400); + } + end(record, STATE_TERMINATED, null, now()); + LOG.infov("Terminated EMR Serverless session {0} on application {1}", sessionId, applicationId); + return copy(record.getSession()); + } + + /** + * Where a client connects to a session that has not ended, with an authentication token, which is "time-limited + * 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) { + 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) { + } + + /** + * Stops the application as StopApplication does once its job runs have ended + * ({@link EmrServerlessJobRunService#stopApplication}), and then terminates its sessions that have not ended. Once + * an application is stopped "no resources are running on the application" (EMR Serverless user guide, "Application + * states"), and while StopApplication requires that "All scheduled and running jobs must be completed or cancelled + * before stopping an application", it names no such requirement for sessions. Under this service's lock, as + * StartSession's admission is, so no session starts between the two. + */ + public synchronized void stopApplication(String applicationId) { + jobRuns.stopApplication(applicationId); + Instant now = now(); + for (SessionRecord record : store.scan(key -> true)) { + Session session = record.getSession(); + if (applicationId.equals(session.getApplicationId()) && inRequestRegion(session) + && !ENDED.contains(settle(record).getSession().getState())) { + end(record, STATE_TERMINATED, APPLICATION_STOPPED, now); + } + } + } + + /** + * The session GetResourceDashboard links to, in any state: "Currently, only Session is supported" as its + * {@code resourceType}. + */ + public synchronized Session dashboardResource(String applicationId, String resourceId, String resourceType) { + List violations = new ArrayList<>(); + if (resourceId == null) { + violations.add(SmithyValidationErrors.notNull("resourceId")); + } + if (resourceType == null) { + violations.add(SmithyValidationErrors.notNull("resourceType")); + } else if (!RESOURCE_TYPES.contains(resourceType)) { + violations.add(SmithyValidationErrors.notInEnum(resourceType, "resourceType", RESOURCE_TYPES)); + } + if (!violations.isEmpty()) { + throw SmithyValidationErrors.validationException(violations); + } + return getSession(applicationId, resourceId); + } + + public synchronized Map listTags(EmrServerlessService.ResourceArn resource) { + Session session = sessionFor(resource).getSession(); + return session.getTags() != null ? new LinkedHashMap<>(session.getTags()) : new LinkedHashMap<>(); + } + + public synchronized void tagResource(EmrServerlessService.ResourceArn resource, Map tags) { + SessionRecord record = sessionFor(resource); + record.getSession().setTags(EmrServerlessService.withTags(record.getSession().getTags(), tags)); + store.put(record.getSession().getSessionId(), record); + } + + public synchronized void untagResource(EmrServerlessService.ResourceArn resource, List tagKeys) { + SessionRecord record = sessionFor(resource); + record.getSession().setTags(EmrServerlessService.withoutTags(record.getSession().getTags(), tagKeys)); + store.put(record.getSession().getSessionId(), record); + } + + private static void validate(StartSessionRequest request) { + List violations = new ArrayList<>(); + if (request.getClientToken() == null) { + violations.add(SmithyValidationErrors.notNull("clientToken")); + } + String roleViolation = EmrServerlessJobRunService.executionRoleViolation(request.getExecutionRoleArn()); + if (roleViolation != null) { + violations.add(roleViolation); + } + if (request.getConfigurationOverrides() != null) { + Object configurations = request.getConfigurationOverrides().get("runtimeConfiguration"); + if (configurations != null) { + violations.addAll(configurationViolations(configurations, + "configurationOverrides.runtimeConfiguration")); + } + } + if (request.getIdleTimeoutMinutes() != null) { + String violation = SmithyValidationErrors.outOfRange("idleTimeoutMinutes", request.getIdleTimeoutMinutes(), + 0, MAX_IDLE_TIMEOUT_MINUTES); + if (violation != null) { + violations.add(violation); + } + } + if (!violations.isEmpty()) { + throw SmithyValidationErrors.validationException(violations); + } + } + + /** + * The violations of a ConfigurationList at {@code path}: each configuration needs its {@code classification}. + * One of the wrong JSON type, the list, a configuration, its {@code classification}, its {@code properties}, a + * map of strings, or its nested {@code configurations}, is refused at once with SerializationException, as a + * restJson1 service refuses a body member of another type (Smithy's restJson1 malformed-request tests), in + * Floci's own wording. + */ + private static List configurationViolations(Object configurations, String path) { + if (!(configurations instanceof List list)) { + throw malformed(path + " must be a list of configurations"); + } + List violations = new ArrayList<>(); + for (int i = 0; i < list.size(); i++) { + String member = path + "." + (i + 1) + ".member"; + if (!(list.get(i) instanceof Map configuration)) { + throw malformed(member + " must be a configuration"); + } + Object classification = configuration.get("classification"); + if (classification == null) { + violations.add(SmithyValidationErrors.notNull(member + ".classification")); + } else if (!(classification instanceof String)) { + throw malformed(member + ".classification must be a string"); + } + Object properties = configuration.get("properties"); + if (properties != null && (!(properties instanceof Map map) + || !map.values().stream().allMatch(String.class::isInstance))) { + throw malformed(member + ".properties must be a map of strings"); + } + Object nested = configuration.get("configurations"); + if (nested != null) { + violations.addAll(configurationViolations(nested, member + ".configurations")); + } + } + return violations; + } + + private static AwsException malformed(String message) { + return new AwsException("SerializationException", message, 400); + } + + /** + * Refuses a session the application cannot hold, before auto-start can change it. No source gives AWS's wording + * for any of these refusals, so it is Floci's; ServiceQuotaExceededException is the model's error for the quota. + */ + private void checkAdmissible(Application app) { + if (!SPARK_TYPE.equalsIgnoreCase(app.getType())) { + throw new AwsException("ValidationException", + "Sessions are supported only on Spark applications.", 400); + } + if (!supportsSessions(app.getReleaseLabel())) { + throw new AwsException("ValidationException", + "Sessions are supported on EMR release 7.13.0 and later.", 400); + } + Object enabled = app.getInteractiveConfiguration() != null + ? app.getInteractiveConfiguration().getProperties().get("sessionEnabled") : null; + if (!Boolean.TRUE.equals(enabled)) { + throw new AwsException("ValidationException", "Application " + app.getApplicationId() + + " does not have interactive sessions enabled.", 400); + } + long open = 0; + for (SessionRecord record : store.scan(key -> true)) { + Session session = record.getSession(); + if (app.getApplicationId().equals(session.getApplicationId()) && inRequestRegion(session) + && !ENDED.contains(settle(record).getSession().getState())) { + open++; + } + } + if (open >= MAX_CONCURRENT_SESSIONS) { + throw new AwsException("ServiceQuotaExceededException", "Application " + app.getApplicationId() + + " already has " + MAX_CONCURRENT_SESSIONS + " concurrent sessions.", 402); + } + } + + /** + * "EMR release 7.13.0 and later": an emr- release from 7.13.0 on, or a release of the AWS runtime for Apache + * Spark, which the release list puts after them. + */ + static boolean supportsSessions(String releaseLabel) { + return EmrServerlessJobRunService.releaseAtLeast(EmrServerlessJobRunService.RELEASE_LABEL, releaseLabel, 7, 13) + || EmrServerlessJobRunService.sparkRuntime(releaseLabel); + } + + private SessionRecord newSession(Application app, StartSessionRequest request, JsonNode original) { + AwsArnUtils.Arn applicationArn = AwsArnUtils.parse(app.getArn()); + String sessionId = EmrServerlessService.newId(); + Instant now = now(); + + Session session = new Session(); + session.setApplicationId(app.getApplicationId()); + session.setSessionId(sessionId); + session.setArn(AwsArnUtils.Arn.of("emr-serverless", applicationArn.region(), applicationArn.accountId(), + applicationArn.resource() + "/sessions/" + sessionId).toString()); + session.setName(request.getName()); + // With no driver to start, a session is ready, and idle, as it starts. + session.setState(STATE_IDLE); + session.setStateDetails(""); + session.setReleaseLabel(app.getReleaseLabel()); + session.setExecutionRoleArn(request.getExecutionRoleArn()); + session.setCreatedBy(EmrServerlessService.createdBy(iamService, requestContext, regionResolver, + applicationArn.accountId())); + session.setCreatedAt(now); + session.setUpdatedAt(now); + session.setStartedAt(now); + session.setIdleSince(now); + // "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); + record.setClientToken(request.getClientToken()); + record.setRequest(original); + store.put(sessionId, record); + return record; + } + + /** + * 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 + * nothing: no source says what it does, and Floci reads it as a job run's execution timeout of 0 is read, as none. + */ + private SessionRecord settle(SessionRecord record) { + Session session = record.getSession(); + if (ENDED.contains(session.getState())) { + return record; + } + Instant hardLimit = session.getStartedAt() != null ? session.getStartedAt().plus(HARD_LIMIT) : null; + Long idleMinutes = session.getIdleTimeoutMinutes(); + Instant idleLimit = STATE_IDLE.equals(session.getState()) && session.getIdleSince() != null + && idleMinutes != null && idleMinutes > 0 + ? session.getIdleSince().plus(Duration.ofMinutes(idleMinutes)) : null; + Instant now = clock.instant(); + if (idleLimit != null && !now.isBefore(idleLimit) && (hardLimit == null || idleLimit.isBefore(hardLimit))) { + end(record, STATE_TERMINATED, IDLE_TIMED_OUT, idleLimit); + } else if (hardLimit != null && !now.isBefore(hardLimit)) { + end(record, STATE_TERMINATED, HARD_LIMIT_REACHED, hardLimit); + } + return record; + } + + private void end(SessionRecord record, String state, String details, Instant at) { + Session session = record.getSession(); + session.setState(state); + session.setStateDetails(details != null ? details : ""); + session.setEndedAt(at); + session.setUpdatedAt(at); + session.setIdleSince(null); + if (session.getStartedAt() != null) { + session.setTotalExecutionDurationSeconds(Duration.between(session.getStartedAt(), at).toSeconds()); + } + store.put(session.getSessionId(), record); + } + + private SessionRecord findSession(String applicationId, String sessionId) { + return store.get(sessionId) + .filter(record -> applicationId.equals(record.getSession().getApplicationId())) + .filter(record -> inRequestRegion(record.getSession())) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Session " + sessionId + " not found", 404)); + } + + // The session a tagging ARN names. The ARN must be the session's own, and a deleted application's sessions name + // nothing, as with job runs. + private SessionRecord sessionFor(EmrServerlessService.ResourceArn resource) { + return store.get(resource.sessionId()) + .filter(record -> resource.applicationId().equals(record.getSession().getApplicationId())) + .filter(record -> resource.arn().equals(record.getSession().getArn())) + .filter(record -> applications.isLive(resource.applicationId())) + .orElseThrow(() -> EmrServerlessService.resourceNotFound(resource.arn())); + } + + private boolean inRequestRegion(Session session) { + return regionResolver.getRegion().equals(AwsArnUtils.parse(session.getArn()).region()); + } + + private Instant now() { + return clock.instant().truncatedTo(ChronoUnit.MILLIS); + } + + private Session copy(Session session) { + return objectMapper.convertValue(session, Session.class); + } +} diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessTagHandler.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessTagHandler.java index b9f5158e11..1baaa942b6 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessTagHandler.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessTagHandler.java @@ -8,7 +8,7 @@ import java.util.List; import java.util.Map; /** - * EMR Serverless on the shared {@code /tags/{resourceArn}} path, for applications and job runs. The + * EMR Serverless on the shared {@code /tags/{resourceArn}} path, for applications, job runs and sessions. The * wire shape is the common one (a lowercase {@code tags} map, a {@code tagKeys} query and * {@code POST}), except that TagResource and UntagResource answer 200 rather than 204, and payloads * are validated strictly. @@ -18,11 +18,14 @@ public class EmrServerlessTagHandler implements TagHandler { private final EmrServerlessService service; private final EmrServerlessJobRunService jobRuns; + private final EmrServerlessSessionService sessions; @Inject - public EmrServerlessTagHandler(EmrServerlessService service, EmrServerlessJobRunService jobRuns) { + public EmrServerlessTagHandler(EmrServerlessService service, EmrServerlessJobRunService jobRuns, + EmrServerlessSessionService sessions) { this.service = service; this.jobRuns = jobRuns; + this.sessions = sessions; } @Override @@ -49,7 +52,10 @@ public class EmrServerlessTagHandler implements TagHandler { @Override public Map listTags(String region, String arn) { EmrServerlessService.ResourceArn resource = service.resourceArn(arn); - return resource.jobRunId() != null ? jobRuns.listTags(resource) : service.listTags(resource); + if (resource.jobRunId() != null) { + return jobRuns.listTags(resource); + } + return resource.sessionId() != null ? sessions.listTags(resource) : service.listTags(resource); } @Override @@ -57,6 +63,8 @@ public class EmrServerlessTagHandler implements TagHandler { EmrServerlessService.ResourceArn resource = service.resourceArn(arn); if (resource.jobRunId() != null) { jobRuns.tagResource(resource, tags); + } else if (resource.sessionId() != null) { + sessions.tagResource(resource, tags); } else { service.tagResource(resource, tags); } @@ -67,6 +75,8 @@ public class EmrServerlessTagHandler implements TagHandler { EmrServerlessService.ResourceArn resource = service.resourceArn(arn); if (resource.jobRunId() != null) { jobRuns.untagResource(resource, tagKeys); + } else if (resource.sessionId() != null) { + sessions.untagResource(resource, tagKeys); } else { service.untagResource(resource, tagKeys); } diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/GetResourceDashboardResponse.java b/src/main/java/io/floci/aws/services/emrserverless/model/GetResourceDashboardResponse.java new file mode 100644 index 0000000000..84de446a0b --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/model/GetResourceDashboardResponse.java @@ -0,0 +1,11 @@ +package io.floci.aws.services.emrserverless.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +public class GetResourceDashboardResponse { + private String url; + + public String getUrl() { return url; } + public void setUrl(String url) { this.url = url; } +} diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/GetSessionEndpointResponse.java b/src/main/java/io/floci/aws/services/emrserverless/model/GetSessionEndpointResponse.java new file mode 100644 index 0000000000..b5387360eb --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/model/GetSessionEndpointResponse.java @@ -0,0 +1,27 @@ +package io.floci.aws.services.emrserverless.model; + +import com.fasterxml.jackson.annotation.JsonFormat; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; + +@RegisterForReflection +public class GetSessionEndpointResponse { + private String applicationId; + private String sessionId; + private String endpoint; + private String authToken; + @JsonFormat(shape = JsonFormat.Shape.NUMBER) + private Instant authTokenExpiresAt; + + public String getApplicationId() { return applicationId; } + public void setApplicationId(String applicationId) { this.applicationId = applicationId; } + public String getSessionId() { return sessionId; } + public void setSessionId(String sessionId) { this.sessionId = sessionId; } + public String getEndpoint() { return endpoint; } + public void setEndpoint(String endpoint) { this.endpoint = endpoint; } + public String getAuthToken() { return authToken; } + public void setAuthToken(String authToken) { this.authToken = authToken; } + public Instant getAuthTokenExpiresAt() { return authTokenExpiresAt; } + public void setAuthTokenExpiresAt(Instant authTokenExpiresAt) { this.authTokenExpiresAt = authTokenExpiresAt; } +} diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/GetSessionResponse.java b/src/main/java/io/floci/aws/services/emrserverless/model/GetSessionResponse.java new file mode 100644 index 0000000000..a0c49d5dd3 --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/model/GetSessionResponse.java @@ -0,0 +1,11 @@ +package io.floci.aws.services.emrserverless.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +public class GetSessionResponse { + private Session session; + + public Session getSession() { return session; } + public void setSession(Session session) { this.session = session; } +} diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/ListSessionsResponse.java b/src/main/java/io/floci/aws/services/emrserverless/model/ListSessionsResponse.java new file mode 100644 index 0000000000..bf1ec13edf --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/model/ListSessionsResponse.java @@ -0,0 +1,18 @@ +package io.floci.aws.services.emrserverless.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; + +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ListSessionsResponse { + private List sessions; + private String nextToken; + + public List getSessions() { return sessions; } + public void setSessions(List sessions) { this.sessions = sessions; } + public String getNextToken() { return nextToken; } + public void setNextToken(String nextToken) { this.nextToken = nextToken; } +} diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/Session.java b/src/main/java/io/floci/aws/services/emrserverless/model/Session.java new file mode 100644 index 0000000000..651d13b6d4 --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/model/Session.java @@ -0,0 +1,83 @@ +package io.floci.aws.services.emrserverless.model; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.Map; + +/** GetSession's session. Timestamps go out as epoch seconds, the restJson1 default. */ +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +public class Session { + private String applicationId; + private String sessionId; + private String arn; + private String name; + private String state; + private String stateDetails; + private String releaseLabel; + private String executionRoleArn; + private String createdBy; + @JsonFormat(shape = JsonFormat.Shape.NUMBER) + private Instant createdAt; + @JsonFormat(shape = JsonFormat.Shape.NUMBER) + private Instant updatedAt; + @JsonFormat(shape = JsonFormat.Shape.NUMBER) + private Instant startedAt; + @JsonFormat(shape = JsonFormat.Shape.NUMBER) + private Instant endedAt; + @JsonFormat(shape = JsonFormat.Shape.NUMBER) + private Instant idleSince; + private Map configurationOverrides; + private NetworkConfiguration networkConfiguration; + private Long idleTimeoutMinutes; + private Map tags; + private Long totalExecutionDurationSeconds; + + public String getApplicationId() { return applicationId; } + public void setApplicationId(String applicationId) { this.applicationId = applicationId; } + public String getSessionId() { return sessionId; } + public void setSessionId(String sessionId) { this.sessionId = sessionId; } + public String getArn() { return arn; } + public void setArn(String arn) { this.arn = arn; } + public String getName() { return name; } + public void setName(String name) { this.name = name; } + public String getState() { return state; } + public void setState(String state) { this.state = state; } + public String getStateDetails() { return stateDetails; } + public void setStateDetails(String stateDetails) { this.stateDetails = stateDetails; } + 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 getCreatedBy() { return createdBy; } + public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } + 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 Map getConfigurationOverrides() { return configurationOverrides; } + public void setConfigurationOverrides(Map configurationOverrides) { + this.configurationOverrides = configurationOverrides; + } + public NetworkConfiguration getNetworkConfiguration() { return networkConfiguration; } + public void setNetworkConfiguration(NetworkConfiguration networkConfiguration) { + this.networkConfiguration = networkConfiguration; + } + public Long getIdleTimeoutMinutes() { return idleTimeoutMinutes; } + public void setIdleTimeoutMinutes(Long idleTimeoutMinutes) { this.idleTimeoutMinutes = idleTimeoutMinutes; } + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } + public Long getTotalExecutionDurationSeconds() { return totalExecutionDurationSeconds; } + public void setTotalExecutionDurationSeconds(Long totalExecutionDurationSeconds) { + this.totalExecutionDurationSeconds = totalExecutionDurationSeconds; + } +} diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/SessionRecord.java b/src/main/java/io/floci/aws/services/emrserverless/model/SessionRecord.java new file mode 100644 index 0000000000..bc55b27345 --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/model/SessionRecord.java @@ -0,0 +1,22 @@ +package io.floci.aws.services.emrserverless.model; + +import com.fasterxml.jackson.databind.JsonNode; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * A stored session: the session as GetSession reports it, plus the client token and the request it came with, which + * decide whether a repeated StartSession is a retry or a conflict. + */ +@RegisterForReflection +public class SessionRecord { + private Session session; + private String clientToken; + private JsonNode request; + + public Session getSession() { return session; } + public void setSession(Session session) { this.session = session; } + public String getClientToken() { return clientToken; } + public void setClientToken(String clientToken) { this.clientToken = clientToken; } + public JsonNode getRequest() { return request; } + public void setRequest(JsonNode request) { this.request = request; } +} diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/SessionSummary.java b/src/main/java/io/floci/aws/services/emrserverless/model/SessionSummary.java new file mode 100644 index 0000000000..df60a3a969 --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/model/SessionSummary.java @@ -0,0 +1,54 @@ +package io.floci.aws.services.emrserverless.model; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; + +/** One of ListSessions' sessions. */ +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +public class SessionSummary { + private String applicationId; + private String sessionId; + private String arn; + private String name; + private String state; + private String stateDetails; + private String releaseLabel; + private String executionRoleArn; + private String createdBy; + @JsonFormat(shape = JsonFormat.Shape.NUMBER) + private Instant createdAt; + @JsonFormat(shape = JsonFormat.Shape.NUMBER) + private Instant updatedAt; + + public static SessionSummary of(Session session) { + SessionSummary summary = new SessionSummary(); + summary.applicationId = session.getApplicationId(); + summary.sessionId = session.getSessionId(); + summary.arn = session.getArn(); + summary.name = session.getName(); + summary.state = session.getState(); + summary.stateDetails = session.getStateDetails(); + summary.releaseLabel = session.getReleaseLabel(); + summary.executionRoleArn = session.getExecutionRoleArn(); + summary.createdBy = session.getCreatedBy(); + summary.createdAt = session.getCreatedAt(); + summary.updatedAt = session.getUpdatedAt(); + return summary; + } + + public String getApplicationId() { return applicationId; } + public String getSessionId() { return sessionId; } + public String getArn() { return arn; } + public String getName() { return name; } + public String getState() { return state; } + public String getStateDetails() { return stateDetails; } + public String getReleaseLabel() { return releaseLabel; } + public String getExecutionRoleArn() { return executionRoleArn; } + public String getCreatedBy() { return createdBy; } + public Instant getCreatedAt() { return createdAt; } + public Instant getUpdatedAt() { return updatedAt; } +} diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/StartSessionRequest.java b/src/main/java/io/floci/aws/services/emrserverless/model/StartSessionRequest.java new file mode 100644 index 0000000000..301d95fb0e --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/model/StartSessionRequest.java @@ -0,0 +1,31 @@ +package io.floci.aws.services.emrserverless.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.Map; + +/** StartSession's body. */ +@RegisterForReflection +public class StartSessionRequest { + private String clientToken; + private String executionRoleArn; + private Map configurationOverrides; + private Map tags; + private Long idleTimeoutMinutes; + private String name; + + public String getClientToken() { return clientToken; } + public void setClientToken(String clientToken) { this.clientToken = clientToken; } + public String getExecutionRoleArn() { return executionRoleArn; } + public void setExecutionRoleArn(String executionRoleArn) { this.executionRoleArn = executionRoleArn; } + public Map getConfigurationOverrides() { return configurationOverrides; } + public void setConfigurationOverrides(Map configurationOverrides) { + this.configurationOverrides = configurationOverrides; + } + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } + public Long getIdleTimeoutMinutes() { return idleTimeoutMinutes; } + public void setIdleTimeoutMinutes(Long idleTimeoutMinutes) { this.idleTimeoutMinutes = idleTimeoutMinutes; } + public String getName() { return name; } + public void setName(String name) { this.name = name; } +} diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/StartSessionResponse.java b/src/main/java/io/floci/aws/services/emrserverless/model/StartSessionResponse.java new file mode 100644 index 0000000000..01ec8bdfd0 --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/model/StartSessionResponse.java @@ -0,0 +1,17 @@ +package io.floci.aws.services.emrserverless.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +public class StartSessionResponse { + private String applicationId; + private String sessionId; + private String arn; + + public String getApplicationId() { return applicationId; } + public void setApplicationId(String applicationId) { this.applicationId = applicationId; } + public String getSessionId() { return sessionId; } + public void setSessionId(String sessionId) { this.sessionId = sessionId; } + public String getArn() { return arn; } + public void setArn(String arn) { this.arn = arn; } +} diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/TerminateSessionResponse.java b/src/main/java/io/floci/aws/services/emrserverless/model/TerminateSessionResponse.java new file mode 100644 index 0000000000..9033becd47 --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/model/TerminateSessionResponse.java @@ -0,0 +1,14 @@ +package io.floci.aws.services.emrserverless.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +public class TerminateSessionResponse { + private String applicationId; + private String sessionId; + + public String getApplicationId() { return applicationId; } + public void setApplicationId(String applicationId) { this.applicationId = applicationId; } + public String getSessionId() { return sessionId; } + public void setSessionId(String sessionId) { this.sessionId = sessionId; } +} diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardsTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardsTest.java index ca3eba79f5..44056356e2 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardsTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardsTest.java @@ -39,10 +39,40 @@ class EmrServerlessDashboardsTest { assertEquals("2", query.get("attempt")); // "The URL is valid for one hour after you generate it." assertEquals(String.valueOf(NOW.plus(Duration.ofHours(1)).getEpochSecond()), query.get("expires")); - assertEquals(new EmrServerlessDashboards.Link("123456789012", "eu-west-1", "00fabcd", "00frun", 2, + assertEquals(new EmrServerlessDashboards.Link("123456789012", "eu-west-1", "00fabcd", "00frun", null, 2, NOW.plus(Duration.ofHours(1)).getEpochSecond()), verified(query)); } + @Test + void aSessionsLinkNamesTheSessionWithNoAttempt() { + Map query = query(dashboards.sessionUrl("123456789012", "eu-west-1", "00fabcd", "00fsession")); + + assertEquals("00fsession", query.get("session")); + assertNull(query.get("jobRun")); + assertNull(query.get("attempt")); + assertEquals(new EmrServerlessDashboards.Link("123456789012", "eu-west-1", "00fabcd", null, "00fsession", 0, + NOW.plus(Duration.ofHours(1)).getEpochSecond()), verified(query)); + } + + @Test + void aSessionsLinkDoesNotOpenAsARunsOfTheSameIdNorTheOtherWayRound() { + Map session = query(dashboards.sessionUrl("123456789012", "us-east-1", "app", "same")); + Map asRun = new LinkedHashMap<>(session); + asRun.put("jobRun", asRun.remove("session")); + asRun.put("attempt", "0"); + assertNull(verified(asRun)); + + Map run = query(dashboards.url("123456789012", "us-east-1", "app", "same", 1)); + Map asSession = new LinkedHashMap<>(run); + asSession.put("session", asSession.remove("jobRun")); + asSession.remove("attempt"); + assertNull(verified(asSession)); + + Map both = new LinkedHashMap<>(session); + both.put("jobRun", "same"); + assertNull(verified(both)); + } + @Test void aLinkWhoseHourHasPassedOpensNothing() { Map query = query(dashboards.url("123456789012", "us-east-1", "app", "run", 1)); @@ -82,7 +112,8 @@ class EmrServerlessDashboardsTest { private EmrServerlessDashboards.Link verified(Map query) { return dashboards.verified(query.get("account"), query.get("region"), query.get("application"), - query.get("jobRun"), query.get("attempt"), query.get("expires"), query.get("signature")); + query.get("jobRun"), query.get("session"), query.get("attempt"), query.get("expires"), + query.get("signature")); } private static Map query(String url) { diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionIntegrationTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionIntegrationTest.java new file mode 100644 index 0000000000..9dd7148851 --- /dev/null +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionIntegrationTest.java @@ -0,0 +1,211 @@ +package io.floci.aws.services.emrserverless; + +import io.floci.aws.core.common.Html; +import io.floci.aws.testing.EmrServerlessRequests; +import io.floci.aws.testing.PartitionCleanup; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.net.URI; +import java.util.UUID; + +import static io.floci.aws.testing.EmrServerlessRequests.emrServerless; +import static io.floci.aws.testing.EmrServerlessRequests.tagsPath; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.endsWith; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.matchesPattern; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * EMR Serverless sessions through the REST API: StartSession, GetSession, ListSessions, GetSessionEndpoint, + * TerminateSession and GetResourceDashboard, tags on a session's ARN, and StopApplication ending an application's + * sessions. + */ +@QuarkusTest +class EmrServerlessSessionIntegrationTest { + + private static final String REGION = "eu-west-1"; + private static final String ROLE = "arn:aws:iam::000000000000:role/emr-serverless-session"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void aSessionStartsIdleAndIsReportedListedConnectedToAndTerminated() { + String applicationId = application("emr-7.13.0", true); + + Response started = emrServerless(REGION).body(""" + {"clientToken": "%s", "executionRoleArn": "%s", "name": "notebook", "idleTimeoutMinutes": 30, + "configurationOverrides": {"runtimeConfiguration": [{"classification": "spark-defaults", + "properties": {"spark.executor.memory": "4g"}}]}, + "tags": {"team": "data"}} + """.formatted(UUID.randomUUID(), ROLE)) + .when().post("/applications/" + applicationId + "/sessions") + .then().statusCode(200) + .body("applicationId", equalTo(applicationId)) + .body("arn", containsString(":/applications/" + applicationId + "/sessions/")) + .extract().response(); + String sessionId = started.path("sessionId"); + String arn = started.path("arn"); + assertTrue(arn.startsWith("arn:aws:emr-serverless:eu-west-1:000000000000:/applications/"), arn); + + emrServerless(REGION).when().get("/applications/" + applicationId + "/sessions/" + sessionId) + .then().statusCode(200) + .body("session.sessionId", equalTo(sessionId)) + .body("session.arn", equalTo(arn)) + .body("session.name", equalTo("notebook")) + .body("session.state", equalTo("IDLE")) + .body("session.releaseLabel", equalTo("emr-7.13.0")) + .body("session.executionRoleArn", equalTo(ROLE)) + .body("session.idleTimeoutMinutes", equalTo(30)) + .body("session.configurationOverrides.runtimeConfiguration[0].properties", notNullValue()) + .body("session.tags.team", equalTo("data")) + .body("session.createdAt", notNullValue()) + .body("session.idleSince", notNullValue()) + .body("session.endedAt", nullValue()); + + emrServerless(REGION).when().get("/applications/" + applicationId + "/sessions?states=IDLE") + .then().statusCode(200) + .body("sessions", hasSize(1)) + .body("sessions[0].sessionId", equalTo(sessionId)) + .body("sessions[0].state", equalTo("IDLE")); + + emrServerless(REGION).when().get("/applications/" + applicationId + "/sessions/" + sessionId + "/endpoint") + .then().statusCode(200) + .body("applicationId", equalTo(applicationId)) + .body("sessionId", equalTo(sessionId)) + .body("endpoint", endsWith("/_aws/emr-serverless/sessions/" + applicationId + "/" + sessionId)) + .body("authToken", matchesPattern("[0-9a-f]{64}")) + .body("authTokenExpiresAt", notNullValue()); + + emrServerless(REGION).when().delete("/applications/" + applicationId + "/sessions/" + sessionId) + .then().statusCode(200) + .body("applicationId", equalTo(applicationId)) + .body("sessionId", equalTo(sessionId)); + emrServerless(REGION).when().get("/applications/" + applicationId + "/sessions/" + sessionId) + .then().statusCode(200) + .body("session.state", equalTo("TERMINATED")) + .body("session.endedAt", notNullValue()); + emrServerless(REGION).when().get("/applications/" + applicationId + "/sessions?states=IDLE") + .then().statusCode(200) + .body("sessions", hasSize(0)); + } + + @Test + void aSessionNeedsSessionsEnabledAndARecentEnoughRelease() { + emrServerless(REGION).body(start()) + .when().post("/applications/" + application("emr-7.13.0", false) + "/sessions") + .then().statusCode(400) + .body("__type", equalTo("ValidationException")); + emrServerless(REGION).body(start()) + .when().post("/applications/" + application("emr-7.12.0", true) + "/sessions") + .then().statusCode(400) + .body("__type", equalTo("ValidationException")); + emrServerless(REGION).body("{\"clientToken\": \"" + UUID.randomUUID() + "\"}") + .when().post("/applications/" + application("emr-7.13.0", true) + "/sessions") + .then().statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", containsString("executionRoleArn")); + emrServerless(REGION).body(""" + {"clientToken": "%s", "executionRoleArn": "%s", + "configurationOverrides": {"runtimeConfiguration": "not-a-list"}} + """.formatted(UUID.randomUUID(), ROLE)) + .when().post("/applications/" + application("emr-7.13.0", true) + "/sessions") + .then().statusCode(400) + .body("__type", equalTo("SerializationException")); + emrServerless(REGION).when().get("/applications/" + application("emr-7.13.0", true) + "/sessions/00fnone") + .then().statusCode(404) + .body("__type", equalTo("ResourceNotFoundException")); + } + + @Test + void aSessionsArnTakesTags() { + String applicationId = application("emr-7.13.0", true); + String arn = emrServerless(REGION).body(start()) + .when().post("/applications/" + applicationId + "/sessions") + .then().statusCode(200).extract().path("arn"); + + emrServerless(REGION).urlEncodingEnabled(false).body("{\"tags\": {\"env\": \"dev\"}}") + .when().post(tagsPath(arn)) + .then().statusCode(200); + emrServerless(REGION).urlEncodingEnabled(false).when().get(tagsPath(arn)) + .then().statusCode(200) + .body("tags.env", equalTo("dev")); + emrServerless(REGION).urlEncodingEnabled(false).when().delete(tagsPath(arn) + "?tagKeys=env") + .then().statusCode(200); + emrServerless(REGION).urlEncodingEnabled(false).when().get(tagsPath(arn)) + .then().statusCode(200) + .body("tags.env", nullValue()); + } + + @Test + void stoppingTheApplicationTerminatesItsSessions() { + String applicationId = application("emr-7.13.0", true); + String sessionId = emrServerless(REGION).body(start()) + .when().post("/applications/" + applicationId + "/sessions") + .then().statusCode(200).extract().path("sessionId"); + + emrServerless(REGION).when().post("/applications/" + applicationId + "/stop").then().statusCode(200); + + emrServerless(REGION).when().get("/applications/" + applicationId + "/sessions/" + sessionId) + .then().statusCode(200) + .body("session.state", equalTo("TERMINATED")) + .body("session.stateDetails", equalTo(EmrServerlessSessionService.APPLICATION_STOPPED)); + } + + @Test + void aSessionsResourceDashboardLinkOpensAPageAboutIt() { + String applicationId = application("emr-7.13.0", true); + String sessionId = emrServerless(REGION).body(start()) + .when().post("/applications/" + applicationId + "/sessions") + .then().statusCode(200).extract().path("sessionId"); + + String url = emrServerless(REGION).when() + .get("/applications/" + applicationId + "/dashboard?resourceType=SESSION&resourceId=" + sessionId) + .then().statusCode(200).extract().path("url"); + + page(url).then().statusCode(200).contentType(containsString("text/html")) + .body(containsString("

Session " + sessionId + "

")) + .body(containsString("StateIDLE")) + .body(containsString(Html.escape(EmrServerlessDashboardController.NO_SESSION_UI))); + emrServerless(REGION).when() + .get("/applications/" + applicationId + "/dashboard?resourceType=JOB_RUN&resourceId=" + sessionId) + .then().statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + private String application(String releaseLabel, boolean sessionEnabled) { + String applicationId = emrServerless(REGION).body(""" + {"name": "sessions-%s", "releaseLabel": "%s", "type": "SPARK", "clientToken": "%s", + "interactiveConfiguration": {"sessionEnabled": %s}} + """.formatted(UUID.randomUUID(), releaseLabel, UUID.randomUUID(), sessionEnabled)) + .when().post("/applications") + .then().statusCode(200).extract().path("applicationId"); + cleanup.register(() -> EmrServerlessRequests.deleteApplication(REGION, applicationId)); + return applicationId; + } + + private static String start() { + return "{\"clientToken\": \"" + UUID.randomUUID() + "\", \"executionRoleArn\": \"" + ROLE + "\"}"; + } + + // The page a link opens, asked for on the address this test's Floci listens on, which the link's base URL is not. + private static Response page(String url) { + URI link = URI.create(url); + return given().urlEncodingEnabled(false).when().get(link.getRawPath() + "?" + link.getRawQuery()); + } +} diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionServiceTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionServiceTest.java new file mode 100644 index 0000000000..f5316e9783 --- /dev/null +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionServiceTest.java @@ -0,0 +1,322 @@ +package io.floci.aws.services.emrserverless; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.services.emrserverless.model.AutoStartConfiguration; +import io.floci.aws.services.emrserverless.model.CreateApplicationRequest; +import io.floci.aws.services.emrserverless.model.InteractiveConfiguration; +import io.floci.aws.services.emrserverless.model.Session; +import io.floci.aws.services.emrserverless.model.SessionSummary; +import io.floci.aws.services.emrserverless.model.StartSessionRequest; +import io.floci.aws.services.iam.IamService; +import io.floci.aws.testing.InMemoryStorageFactory; +import io.floci.aws.testing.MutableClock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class EmrServerlessSessionServiceTest { + + private static final String REGION = "us-east-1"; + private static final String ACCOUNT_ID = "000000000000"; + private static final String ROLE = "arn:aws:iam::000000000000:role/emr-serverless-session"; + + private final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule()); + private EmrServerlessService applications; + private EmrServerlessSessionService sessions; + private MutableClock clock; + + @BeforeEach + void setUp() { + EmulatorConfig config = mock(EmulatorConfig.class); + when(config.defaultAccountId()).thenReturn(ACCOUNT_ID); + clock = new MutableClock(); + RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT_ID); + applications = new EmrServerlessService(config, new InMemoryStorageFactory(ACCOUNT_ID), regionResolver, clock); + IamService iamService = mock(IamService.class); + when(iamService.resolveCallerArn(any())).thenReturn(Optional.empty()); + EmrServerlessJobRunService jobRuns = new EmrServerlessJobRunService(AccountAwareStorageBackend.inMemory( + ACCOUNT_ID), applications, iamService, regionResolver, null, objectMapper, 0, clock); + sessions = new EmrServerlessSessionService(AccountAwareStorageBackend.inMemory(ACCOUNT_ID), applications, + jobRuns, iamService, regionResolver, null, objectMapper, clock, "http://localhost:4566/"); + } + + @Test + void aSessionIsIdleOnceStartedAndKeepsTheDefaultIdleTimeoutOfAnHour() { + String applicationId = application("emr-7.13.0", "SPARK", true); + + Session session = sessions.startSession(applicationId, request()); + + assertEquals("IDLE", session.getState()); + assertEquals(session.getCreatedAt(), session.getStartedAt()); + assertEquals(session.getCreatedAt(), session.getIdleSince()); + assertEquals(60L, session.getIdleTimeoutMinutes()); + assertEquals("emr-7.13.0", session.getReleaseLabel()); + assertEquals(ROLE, session.getExecutionRoleArn()); + assertEquals("arn:aws:iam::000000000000:root", session.getCreatedBy()); + assertEquals("arn:aws:emr-serverless:us-east-1:000000000000:/applications/" + applicationId + "/sessions/" + + session.getSessionId(), session.getArn()); + assertEquals("STARTED", applications.getApplication(applicationId).getState()); + } + + @Test + void anIdleSessionEndsOnceItsIdleTimeoutHasPassed() { + String applicationId = application("emr-7.13.0", "SPARK", true); + StartSessionRequest request = request(); + request.setIdleTimeoutMinutes(30L); + Session started = sessions.startSession(applicationId, request); + + clock.advance(Duration.ofMinutes(29)); + assertEquals("IDLE", sessions.getSession(applicationId, started.getSessionId()).getState()); + clock.advance(Duration.ofMinutes(1)); + Session ended = sessions.getSession(applicationId, started.getSessionId()); + + assertEquals("TERMINATED", ended.getState()); + assertEquals(EmrServerlessSessionService.IDLE_TIMED_OUT, ended.getStateDetails()); + assertEquals(started.getIdleSince().plus(Duration.ofMinutes(30)), ended.getEndedAt()); + assertEquals(30 * 60L, ended.getTotalExecutionDurationSeconds()); + assertNull(ended.getIdleSince()); + } + + @Test + void aSessionWithNoIdleTimeoutEndsAtItsTwentyFourHours() { + String applicationId = application("emr-spark-8.0.0", "SPARK", true); + StartSessionRequest request = request(); + request.setIdleTimeoutMinutes(0L); + Session started = sessions.startSession(applicationId, request); + + clock.advance(Duration.ofHours(24).minusSeconds(1)); + assertEquals("IDLE", sessions.getSession(applicationId, started.getSessionId()).getState()); + clock.advance(Duration.ofSeconds(1)); + Session ended = sessions.getSession(applicationId, started.getSessionId()); + + assertEquals("TERMINATED", ended.getState()); + assertEquals(EmrServerlessSessionService.HARD_LIMIT_REACHED, ended.getStateDetails()); + assertEquals(started.getStartedAt().plus(Duration.ofHours(24)), ended.getEndedAt()); + } + + @Test + void aSessionIsRefusedWhereTheApplicationCannotHoldOne() { + assertRefused(application("emr-7.12.0", "SPARK", true), "ValidationException"); + assertRefused(application("emr-6.15.0", "SPARK", true), "ValidationException"); + assertRefused(application("emr-7.13.0", "HIVE", true), "ValidationException"); + assertRefused(application("emr-7.13.0", "SPARK", false), "ValidationException"); + String refused = application("emr-7.13.0", "SPARK", null); + assertRefused(refused, "ValidationException"); + // Refused before auto-start, which leaves the application as it was. + assertEquals("CREATED", applications.getApplication(refused).getState()); + } + + @Test + void aRuntimeConfigurationOfTheWrongShapeIsRefusedAndOneWithoutAClassificationIsInvalid() { + String applicationId = application("emr-7.13.0", "SPARK", true); + for (Object malformed : List.of("not-a-list", List.of("not-a-configuration"), + List.of(Map.of("classification", 1)), + List.of(Map.of("classification", "spark-defaults", "properties", Map.of("spark.a", 1))), + List.of(Map.of("classification", "spark-defaults", "configurations", "not-a-list")))) { + StartSessionRequest request = request(); + request.setConfigurationOverrides(Map.of("runtimeConfiguration", malformed)); + AwsException refused = assertThrows(AwsException.class, + () -> sessions.startSession(applicationId, request)); + assertEquals("SerializationException", refused.getErrorCode(), String.valueOf(malformed)); + } + StartSessionRequest unclassified = request(); + unclassified.setConfigurationOverrides(Map.of("runtimeConfiguration", + List.of(Map.of("properties", Map.of("spark.a", "b"))))); + AwsException invalid = assertThrows(AwsException.class, + () -> sessions.startSession(applicationId, unclassified)); + assertEquals("ValidationException", invalid.getErrorCode()); + assertTrue(invalid.getMessage().contains("configurationOverrides.runtimeConfiguration.1.member.classification"), + invalid.getMessage()); + + StartSessionRequest valid = request(); + valid.setConfigurationOverrides(Map.of("runtimeConfiguration", List.of(Map.of("classification", + "spark-defaults", "properties", Map.of("spark.executor.memory", "4g"))))); + assertEquals("IDLE", sessions.startSession(applicationId, valid).getState()); + } + + @Test + void aStoppedApplicationWithAutoStartOffRefusesASession() { + CreateApplicationRequest create = applicationRequest("emr-7.13.0", "SPARK", true); + AutoStartConfiguration autoStart = new AutoStartConfiguration(); + autoStart.setEnabled(false); + create.setAutoStartConfiguration(autoStart); + String applicationId = applications.createApplication(create).getApplicationId(); + + AwsException refused = assertThrows(AwsException.class, + () -> sessions.startSession(applicationId, request())); + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("before a session is started"), refused.getMessage()); + + applications.startApplication(applicationId); + assertEquals("IDLE", sessions.startSession(applicationId, request()).getState()); + } + + @Test + void anApplicationHoldsAtMostTwentyFiveSessionsThatHaveNotEnded() { + String applicationId = application("emr-7.13.0", "SPARK", true); + String first = null; + for (int i = 0; i < EmrServerlessSessionService.MAX_CONCURRENT_SESSIONS; i++) { + String sessionId = sessions.startSession(applicationId, request()).getSessionId(); + first = first != null ? first : sessionId; + } + + AwsException refused = assertThrows(AwsException.class, + () -> sessions.startSession(applicationId, request())); + assertEquals("ServiceQuotaExceededException", refused.getErrorCode()); + assertEquals(402, refused.getHttpStatus()); + + sessions.terminateSession(applicationId, first); + assertEquals("IDLE", sessions.startSession(applicationId, request()).getState()); + } + + @Test + void aRetryWithTheSameClientTokenReturnsTheSessionAndADifferentRequestConflicts() { + String applicationId = application("emr-7.13.0", "SPARK", true); + StartSessionRequest request = request(); + Session started = sessions.startSession(applicationId, request); + + assertEquals(started.getSessionId(), sessions.startSession(applicationId, request).getSessionId()); + request.setName("another"); + AwsException conflict = assertThrows(AwsException.class, + () -> sessions.startSession(applicationId, request)); + assertEquals("ConflictException", conflict.getErrorCode()); + assertEquals(409, conflict.getHttpStatus()); + } + + @Test + void stoppingTheApplicationTerminatesItsSessionsThatHaveNotEnded() { + String applicationId = application("emr-7.13.0", "SPARK", true); + String live = sessions.startSession(applicationId, request()).getSessionId(); + String terminated = sessions.startSession(applicationId, request()).getSessionId(); + sessions.terminateSession(applicationId, terminated); + Session before = sessions.getSession(applicationId, terminated); + + sessions.stopApplication(applicationId); + + assertEquals("STOPPED", applications.getApplication(applicationId).getState()); + Session stopped = sessions.getSession(applicationId, live); + assertEquals("TERMINATED", stopped.getState()); + assertEquals(EmrServerlessSessionService.APPLICATION_STOPPED, stopped.getStateDetails()); + assertEquals(before.getEndedAt(), sessions.getSession(applicationId, terminated).getEndedAt()); + assertEquals("", sessions.getSession(applicationId, terminated).getStateDetails()); + } + + @Test + void aSessionThatHasEndedCannotBeTerminatedNorConnectedTo() { + String applicationId = application("emr-7.13.0", "SPARK", true); + String sessionId = sessions.startSession(applicationId, request()).getSessionId(); + sessions.terminateSession(applicationId, sessionId); + + assertEquals("ValidationException", assertThrows(AwsException.class, + () -> sessions.terminateSession(applicationId, sessionId)).getErrorCode()); + assertEquals("ValidationException", assertThrows(AwsException.class, + () -> sessions.sessionEndpoint(applicationId, sessionId)).getErrorCode()); + } + + @Test + void anEndpointsTokenLastsAnHourAndEachCallGivesANewOne() { + String applicationId = application("emr-7.13.0", "SPARK", true); + String sessionId = sessions.startSession(applicationId, request()).getSessionId(); + + EmrServerlessSessionService.Endpoint endpoint = sessions.sessionEndpoint(applicationId, sessionId); + + assertEquals("http://localhost:4566/_aws/emr-serverless/sessions/" + applicationId + "/" + sessionId, + endpoint.url()); + assertEquals(64, endpoint.authToken().length()); + assertTrue(Duration.between(clock.instant(), endpoint.authTokenExpiresAt()).compareTo(Duration.ofMinutes(59)) + > 0); + assertNotEquals(endpoint.authToken(), sessions.sessionEndpoint(applicationId, sessionId).authToken()); + } + + @Test + void listSessionsFiltersByStateAndGroupsByTheFiltersOrder() { + String applicationId = application("emr-7.13.0", "SPARK", true); + String older = sessions.startSession(applicationId, request()).getSessionId(); + clock.advance(Duration.ofSeconds(1)); + String newer = sessions.startSession(applicationId, request()).getSessionId(); + clock.advance(Duration.ofSeconds(1)); + String ended = sessions.startSession(applicationId, request()).getSessionId(); + sessions.terminateSession(applicationId, ended); + + assertEquals(List.of(ended, newer, older), ids(sessions.listSessions(applicationId, null, null, null, null, + null).items())); + assertEquals(List.of(newer, older), ids(sessions.listSessions(applicationId, List.of("IDLE"), null, null, null, + null).items())); + assertEquals(List.of(ended, newer, older), ids(sessions.listSessions(applicationId, + List.of("TERMINATED", "IDLE"), null, null, null, null).items())); + assertEquals("ValidationException", assertThrows(AwsException.class, + () -> sessions.listSessions(applicationId, List.of("RUNNING"), null, null, null, null)) + .getErrorCode()); + } + + @Test + void aResourceDashboardIsOnlyForASession() { + String applicationId = application("emr-7.13.0", "SPARK", true); + String sessionId = sessions.startSession(applicationId, request()).getSessionId(); + + assertEquals(sessionId, sessions.dashboardResource(applicationId, sessionId, "SESSION").getSessionId()); + assertEquals("ValidationException", assertThrows(AwsException.class, + () -> sessions.dashboardResource(applicationId, sessionId, "JOB_RUN")).getErrorCode()); + assertEquals("ValidationException", assertThrows(AwsException.class, + () -> sessions.dashboardResource(applicationId, null, null)).getErrorCode()); + assertEquals("ResourceNotFoundException", assertThrows(AwsException.class, + () -> sessions.dashboardResource(applicationId, "00fmissing", "SESSION")).getErrorCode()); + } + + private void assertRefused(String applicationId, String code) { + AwsException refused = assertThrows(AwsException.class, + () -> sessions.startSession(applicationId, request())); + assertEquals(code, refused.getErrorCode(), refused.getMessage()); + } + + private static List ids(List summaries) { + return summaries.stream().map(SessionSummary::getSessionId).toList(); + } + + private static StartSessionRequest request() { + StartSessionRequest request = new StartSessionRequest(); + request.setClientToken(UUID.randomUUID().toString()); + request.setExecutionRoleArn(ROLE); + return request; + } + + // An application of type on releaseLabel; sessionEnabled is left out where it is null. + private String application(String releaseLabel, String type, Boolean sessionEnabled) { + return applications.createApplication(applicationRequest(releaseLabel, type, sessionEnabled)) + .getApplicationId(); + } + + private static CreateApplicationRequest applicationRequest(String releaseLabel, String type, + Boolean sessionEnabled) { + CreateApplicationRequest create = new CreateApplicationRequest(); + create.setName("sessions"); + create.setReleaseLabel(releaseLabel); + create.setType(type); + create.setClientToken(UUID.randomUUID().toString()); + if (sessionEnabled != null) { + InteractiveConfiguration interactive = new InteractiveConfiguration(); + interactive.setProperty("sessionEnabled", sessionEnabled); + create.setInteractiveConfiguration(interactive); + } + return create; + } +} diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessTagIntegrationTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessTagIntegrationTest.java index 3d1471ab68..b198424340 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessTagIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessTagIntegrationTest.java @@ -320,7 +320,7 @@ class EmrServerlessTagIntegrationTest { } @Test - void aJobRunArnMustBeTheRunsOwnAndSessionArnsNameNothing() { + void aJobRunArnMustBeTheRunsOwnAndAnUnknownSessionsArnNamesNothing() { String[] owner = createApplication("{}"); String[] other = createApplication("{}"); String[] run = startJobRun(owner[0], "{ \"team\": \"data\" }"); diff --git a/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEmrServerlessSyncTest.java b/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEmrServerlessSyncTest.java index 8c2799aa08..916c945234 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEmrServerlessSyncTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEmrServerlessSyncTest.java @@ -9,6 +9,7 @@ import io.floci.aws.services.emrserverless.EmrServerlessController; import io.floci.aws.services.emrserverless.EmrServerlessDashboards; import io.floci.aws.services.emrserverless.EmrServerlessJobRunService; import io.floci.aws.services.emrserverless.EmrServerlessService; +import io.floci.aws.services.emrserverless.EmrServerlessSessionService; import io.floci.aws.services.emrserverless.model.Application; import io.floci.aws.services.emrserverless.model.JobRun; import io.floci.aws.services.stepfunctions.model.Execution; @@ -58,6 +59,7 @@ class AslExecutorEmrServerlessSyncTest { private final AtomicLong testNanos = new AtomicLong(); private EmrServerlessService applications; private EmrServerlessJobRunService jobRuns; + private EmrServerlessSessionService sessions; private StepFunctionsService sfnService; private AslExecutor executor; private List history; @@ -67,6 +69,7 @@ class AslExecutorEmrServerlessSyncTest { void setUp() { applications = mock(EmrServerlessService.class); jobRuns = mock(EmrServerlessJobRunService.class); + sessions = mock(EmrServerlessSessionService.class); when(jobRuns.startJobRun(eq(APPLICATION_ID), any())).thenReturn(jobRun("RUNNING")); when(applications.createApplication(any())).thenReturn(application("CREATING")); sfnService = mock(StepFunctionsService.class); @@ -79,8 +82,8 @@ class AslExecutorEmrServerlessSyncTest { .sfnService(instance) .customResourceLiveness(null) .emrServerlessTaskInvoker(new EmrServerlessTaskInvoker( - new EmrServerlessController(applications, jobRuns, mock(EmrServerlessDashboards.class), - mock(RegionResolver.class)), objectMapper)) + new EmrServerlessController(applications, jobRuns, sessions, + mock(EmrServerlessDashboards.class), mock(RegionResolver.class)), objectMapper)) .nanoTime(testNanos::get) .sleeper(testNanos::addAndGet) .build(); @@ -226,7 +229,7 @@ class AslExecutorEmrServerlessSyncTest { run(task("startApplication.sync"), APPLICATION); verify(applications).startApplication(APPLICATION_ID); - verify(jobRuns).stopApplication(APPLICATION_ID); + verify(sessions).stopApplication(APPLICATION_ID); assertEquals(List.of(), history.stream().map(HistoryEvent::getType) .filter(type -> type.equals("TaskFailed") || type.equals("TaskSucceeded")).toList()); } @@ -238,7 +241,7 @@ class AslExecutorEmrServerlessSyncTest { Execution execution = run(timingOut("stopApplication.sync"), APPLICATION); assertEquals("States.Timeout", execution.getError()); - verify(jobRuns).stopApplication(APPLICATION_ID); + verify(sessions).stopApplication(APPLICATION_ID); verify(applications, never()).startApplication(anyString()); verify(applications, never()).deleteApplication(anyString()); }