feat(emr): keep persistent application UIs and answer their presigned URLs (#8711)

EMR's application UI operations, CreatePersistentAppUI,
DescribePersistentAppUI, GetPersistentAppUIPresignedURL and
GetOnClusterAppUIPresignedURL, were not served.

Floci now keeps a cluster's persistent application UIs, with the types
its release and applications give it (the Spark History Server from
5.25.0, the Tez UI and YARN timeline server from 5.30.1), refusing a
cluster with more than one primary node and an account past 200, and
reports whether the cluster's security configuration turns on runtime
roles. It serves none of those UIs: a presigned URL, persistent or
on-cluster, opens a signed one-hour page of Floci's about the cluster
and the interface asked for.

The link signing of EMR Serverless's dashboards and these pages is one
helper, core.common.LinkSigner, and their HTML page and table rows come
from core.common.Html.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-17 02:32:58 -04:00
1 parent 7199c8580e
commit 751c97dde6
20 files changed
+959 -88

No files matched your search

+31
View File
@@ -43,6 +43,10 @@ Floci emulates the Amazon EMR (Elastic MapReduce) management API. Clusters (job
| `DescribeNotebookExecution` | Returns a notebook execution's status, times and configuration |
| `StopNotebookExecution` | Stops a notebook execution that has not ended |
| `ListNotebookExecutions` | Lists notebook executions, newest first, by editor, status, time and cluster |
| `CreatePersistentAppUI` | Makes a cluster's persistent application UIs; see [Application UIs](#application-uis) |
| `DescribePersistentAppUI` | Returns a persistent application UI's types and status |
| `GetPersistentAppUIPresignedURL` | Returns a presigned URL to a persistent application UI, a page of Floci's |
| `GetOnClusterAppUIPresignedURL` | Returns a presigned URL to a running cluster's on-cluster UI, a page of Floci's |
| `AddInstanceGroups` | Adds instance groups to a running cluster |
| `ListInstanceGroups` | Lists the instance groups of a cluster |
| `AddInstanceFleet` | Adds an instance fleet to a cluster |
@@ -298,6 +302,33 @@ notebook.
("Returns a maximum of 50 notebook executions") after a `Marker`, which resumes only the listing it came from: the
same account, Region and filters.
## Application UIs
Floci keeps a cluster's persistent application UIs, but serves no Spark History Server, Tez UI, YARN timeline server
or on-cluster UI: a presigned URL opens a page Floci serves at `/_aws/emr/app-ui` on its own address (`base-url`, or
`hostname`), with the cluster as `DescribeCluster` gives it and the interface asked for. The link is signed with a key
Floci makes as it starts and lasts an hour, as no source gives AWS's; one changed, past its hour or given before
Floci restarted opens a `403` page, and one whose cluster has gone a `404`.
* **CreatePersistentAppUI** takes an EMR cluster's ARN of the account in the Region as its `TargetResourceArn`; Floci
keeps none for an EMR on EKS virtual cluster. The persistent Spark History Server is there "Starting with Amazon
EMR version 5.25.0", and the "Tez UI and YARN timeline server persistent application interfaces are available
starting with Amazon EMR version 5.30.1": the UI's `PersistentAppUITypeList` names `SHS` for a cluster with Spark,
and, from 5.30.1, `TEZ` for one with Tez and `YTS` for one with Hadoop; a `ProfilerType` makes the one it names
(`TEZUI` the Tez UI) the UI's only type, and one the cluster has not is refused. A cluster with none of them, an earlier
release, a cluster with more than one primary node ("not available for EMR clusters with multiple master nodes"),
and a UI past the account's 200 active ones ("the default limit for active application UIs is 200": a UI whose
cluster has gone, or ended more than 30 days ago, as "The logs are available for 30 days after the application
ends", no longer counts) are refused, each with
`InvalidRequestException` in Floci's own wording. `RuntimeRoleEnabledCluster` is whether the cluster's security
configuration sets `AuthorizationConfiguration.IAMConfiguration.EnableApplicationScopedIAMRole`. The UI's id is
`p-` and 13 letters and digits, its `PersistentAppUIStatus` `ACTIVE` and its `AuthorId` the account, none of which
any source gives. A tag without its `Key`, "the minimum required information for a valid tag", is refused, as it is
for sessions, Studios and notebook executions.
* **GetPersistentAppUIPresignedURL** gives a URL to one of the UI's types, its first by default; a type it has not is
refused. **GetOnClusterAppUIPresignedURL** gives one to an on-cluster UI, the `ResourceManager` by default, while
the cluster is `RUNNING` or `WAITING`, and none for a `DryRun`. Both are `PresignedURLReady` at once.
## Running steps
With `runner-mode` set to `docker` (`FLOCI_SERVICES_EMR_RUNNER_MODE=docker`), a step runs. Floci starts
+1 -1
View File
@@ -84,7 +84,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 65 |
| [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 12 |
| [Redshift Serverless](redshift-serverless.md) | `POST /` + `X-Amz-Target: RedshiftServerless.*` | JSON 1.1 | 58 |
| [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 59 |
| [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 63 |
| [EMR on EKS](emr-containers.md) | `/virtualclusters/*`, `/jobtemplates/*`, `/securityconfigurations/*`, `/tags/*` | REST JSON | 25 |
| [EMR Serverless](emr-serverless.md) | `/applications/*`, `/tags/*` | REST JSON | 15 |
| [Data Firehose](firehose.md) | `POST /` + `X-Amz-Target: Firehose_20150804.*` | JSON 1.1 | 12 |
@@ -1,5 +1,7 @@
package io.floci.aws.core.common;
import java.util.List;
/** Text put into an HTML page Floci serves, escaped so that it is shown as it is and never read as markup. */
public final class Html {
@@ -14,4 +16,19 @@ public final class Html {
return value.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
.replace("\"", "&quot;").replace("'", "&#39;");
}
/** A plain page titled {@code title}, the title escaped and repeated as its heading, its body's lines after it. */
public static String page(String title, List<String> body) {
return "<!doctype html>\n"
+ "<html lang=\"en\"><head><meta charset=\"utf-8\"><title>" + escape(title)
+ "</title></head>\n<body>\n<h1>" + escape(title) + "</h1>\n"
+ String.join("\n", body) + "\n</body></html>\n";
}
/** Adds a table row of {@code name} and {@code value}, both escaped; none when there is no value. */
public static void row(List<String> lines, String name, String value) {
if (value != null && !value.isEmpty()) {
lines.add("<tr><th>" + escape(name) + "</th><td>" + escape(value) + "</td></tr>");
}
}
}
@@ -0,0 +1,50 @@
package io.floci.aws.core.common;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.HexFormat;
/**
* Signs the links to pages Floci serves in place of a service's UI, such as an EMR Serverless run's dashboard or an
* EMR cluster's application UI: an HMAC-SHA256 over what a link names, with a key the signer holds. A signer made
* with {@link #withNewKey()} holds a key of its own process, so its links open nothing after a restart.
*/
public final class LinkSigner {
private static final String ALGORITHM = "HmacSHA256";
private static final int KEY_BYTES = 32;
private final byte[] key;
public LinkSigner(byte[] key) {
this.key = key.clone();
}
/** A signer with a new random key, which no other signer shares. */
public static LinkSigner withNewKey() {
byte[] key = new byte[KEY_BYTES];
new SecureRandom().nextBytes(key);
return new LinkSigner(key);
}
/** The signature over {@code fields}, in order, as hexadecimal. */
public String sign(String... fields) {
try {
Mac mac = Mac.getInstance(ALGORITHM);
mac.init(new SecretKeySpec(key, ALGORITHM));
return HexFormat.of().formatHex(mac.doFinal(String.join("\n", fields).getBytes(StandardCharsets.UTF_8)));
} catch (GeneralSecurityException e) {
throw new IllegalStateException("Could not sign a link", e);
}
}
/** Whether {@code signature} is this signer's over {@code fields}, compared in constant time. */
public boolean verifies(String signature, String... fields) {
return signature != null && MessageDigest.isEqual(sign(fields).getBytes(StandardCharsets.US_ASCII),
signature.getBytes(StandardCharsets.US_ASCII));
}
}
@@ -0,0 +1,74 @@
package io.floci.aws.services.emr;
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.emr.model.EmrCluster;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
/**
* The page a presigned URL of {@code GetPersistentAppUIPresignedURL} or {@code GetOnClusterAppUIPresignedURL} opens
* ({@link EmrAppUiService}). EMR opens the cluster's Spark History Server, Tez UI, YARN timeline server or on-cluster
* UI; Floci serves none of them, so the page shows the cluster as DescribeCluster gives it and which interface was
* asked for. A link that is not one of this process's, or whose hour has passed, opens a refusal instead, and so does
* one whose cluster has gone. Like the rest of Floci the page takes no AWS credentials: the link is all it asks for.
*/
@Path(EmrAppUiService.PATH)
public class EmrAppUiController {
// No source gives AWS's wording for these; they are Floci's.
static final String INVALID = "This application UI link is not valid, or its hour has passed. Call"
+ " GetPersistentAppUIPresignedURL or GetOnClusterAppUIPresignedURL for a new one.";
static final String NO_UI = "Floci serves no Spark History Server, Tez UI, YARN timeline server or on-cluster"
+ " application UI, so this page stands in for the interface EMR opens.";
private final EmrAppUiService appUis;
@Inject
public EmrAppUiController(EmrAppUiService appUis) {
this.appUis = appUis;
}
@GET
@Produces(MediaType.TEXT_HTML)
public Response page(@QueryParam("account") String accountId, @QueryParam("region") String region,
@QueryParam("cluster") String clusterId, @QueryParam("type") String type,
@QueryParam("application") String applicationId, @QueryParam("expires") String expires,
@QueryParam("signature") String signature) {
EmrAppUiService.Link link = appUis.verified(accountId, region, clusterId, type, applicationId, expires,
signature);
if (link == null) {
return page(403, "Application UI", List.of("<p>" + Html.escape(INVALID) + "</p>"));
}
EmrCluster cluster;
try {
cluster = RequestScopes.callAs(link.accountId(), link.region(), () -> appUis.clusterOf(link));
} catch (AwsException e) {
return page(404, "Cluster " + link.clusterId(), List.of("<p>" + Html.escape(e.getMessage()) + "</p>"));
}
List<String> lines = new ArrayList<>();
lines.add("<table>");
Html.row(lines, "Cluster", cluster.getId());
Html.row(lines, "Name", cluster.getName());
Html.row(lines, "State", cluster.getState());
Html.row(lines, "Release label", cluster.getReleaseLabel());
Html.row(lines, "Interface", link.type());
Html.row(lines, "Application", link.applicationId());
lines.add("</table>");
lines.add("<p>" + Html.escape(NO_UI) + "</p>");
return page(200, link.type() + " of cluster " + cluster.getId(), lines);
}
private static Response page(int status, String title, List<String> body) {
return Response.status(status).type(MediaType.TEXT_HTML).entity(Html.page(title, body)).build();
}
}
@@ -0,0 +1,303 @@
package io.floci.aws.services.emr;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.LinkSigner;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.SmithyValidationErrors;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrPersistentAppUi;
import io.floci.aws.services.emrserverless.EmrServerlessSparkRunner;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* A cluster's application user interfaces: the persistent ones "hosted off-cluster" (Amazon EMR Management Guide, "View
* persistent application user interfaces in Amazon EMR") and the on-cluster ones, both reached through presigned URLs.
* Floci keeps a persistent application UI's record, but serves no Spark History Server, Tez UI, YARN timeline server
* or on-cluster UI: a presigned URL opens a page of Floci's own about the cluster ({@link EmrAppUiController}), signed
* with a key of this process and valid for {@link #VALIDITY}.
*/
@ApplicationScoped
public class EmrAppUiService {
/** Where Floci serves the page a presigned URL opens. */
static final String PATH = "/_aws/emr/app-ui";
// No source gives how long AWS's presigned URLs last; Floci's open its page for an hour, as its other links do.
static final Duration VALIDITY = Duration.ofHours(1);
static final List<String> PROFILER_TYPES = List.of("SHS", "TEZUI", "YTS");
static final List<String> PERSISTENT_TYPES = List.of("SHS", "TEZ", "YTS");
static final List<String> ON_CLUSTER_TYPES = List.of("SparkHistoryServer", "YarnTimelineService", "TezUI",
"ApplicationMaster", "JobHistoryServer", "ResourceManager");
// "For each AWS account, the default limit for active application UIs is 200."
static final int MAX_PERSISTENT_APP_UIS = 200;
// "The logs are available for 30 days after the application ends."
static final Duration LOGS_KEPT = Duration.ofDays(30);
// No source gives AWS's status values; Floci reports this one for every persistent application UI.
static final String ACTIVE = "ACTIVE";
private final AccountAwareStorageBackend<EmrPersistentAppUi> store;
private final EmrService clusters;
private final RegionResolver regionResolver;
private final Clock clock;
private final String baseUrl;
private final LinkSigner signer;
@Inject
public EmrAppUiService(StorageFactory storageFactory, EmrService clusters, RegionResolver regionResolver,
EmulatorConfig config) {
this(storageFactory.create("emr", "emr-persistent-app-uis.json",
new TypeReference<Map<String, EmrPersistentAppUi>>() {}),
clusters, regionResolver, Clock.systemUTC(), config.effectiveBaseUrl(), LinkSigner.withNewKey());
}
EmrAppUiService(AccountAwareStorageBackend<EmrPersistentAppUi> store, EmrService clusters,
RegionResolver regionResolver, Clock clock, String baseUrl, LinkSigner signer) {
this.store = store;
this.clusters = clusters;
this.regionResolver = regionResolver;
this.clock = clock;
String base = baseUrl == null ? "" : baseUrl;
this.baseUrl = base.endsWith("/") ? base.substring(0, base.length() - 1) : base;
this.signer = signer;
}
/** CreatePersistentAppUI's answer: the new UI, and whether its cluster is a runtime role enabled one. */
public record Created(EmrPersistentAppUi appUi, boolean runtimeRoleEnabledCluster) {
}
/**
* Creates a persistent application UI for an EMR cluster of the account in the Region, which its
* {@code TargetResourceArn} names. Floci keeps none for an EMR on EKS virtual cluster. The guide's rules apply:
* the persistent Spark History Server is there "Starting with Amazon EMR version 5.25.0", and the "Tez UI and
* YARN timeline server persistent application interfaces are available starting with Amazon EMR version 5.30.1",
* each for a cluster that installs Spark, Tez or Hadoop; the feature "is currently not available for EMR clusters
* with multiple master nodes"; and an account has at most {@link #MAX_PERSISTENT_APP_UIS}. Each refusal is
* InvalidRequestException in Floci's own wording, as AWS's is not recorded.
*/
public synchronized Created create(String targetResourceArn, String profilerType, Map<String, String> tags) {
List<String> violations = new ArrayList<>();
if (targetResourceArn == null) {
violations.add(SmithyValidationErrors.notNull("targetResourceArn"));
}
EmrService.checkEnum(violations, "profilerType", profilerType, PROFILER_TYPES);
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
EmrCluster cluster = clusters.describeCluster(clusterIdOf(targetResourceArn));
if (!EmrService.releaseAtLeast(cluster.getReleaseLabel(), 5, 25, 0)) {
throw EmrService.invalid("Persistent application UIs need a cluster of release emr-5.25.0 or later.");
}
if (EmrSessions.highlyAvailable(cluster)) {
throw EmrService.invalid("Persistent application UIs are not available for a cluster with multiple"
+ " primary nodes.");
}
List<String> types = typesOf(cluster);
if (types.isEmpty()) {
throw EmrService.invalid("Cluster " + cluster.getId() + " installs none of Spark, Tez and Hadoop, whose"
+ " application UIs persist.");
}
if (profilerType != null) {
// The profiler asked for is the one interface the UI has: TEZUI is the Tez UI, as PersistentAppUIType's
// TEZ names it.
String type = "TEZUI".equals(profilerType) ? "TEZ" : profilerType;
if (!types.contains(type)) {
throw EmrService.invalid("Cluster " + cluster.getId() + " has no " + profilerType
+ " interface to persist; it has " + String.join(", ", types) + ".");
}
types = List.of(type);
}
if (activeAppUis() >= MAX_PERSISTENT_APP_UIS) {
throw EmrService.invalid("The account already has " + MAX_PERSISTENT_APP_UIS
+ " persistent application UIs.");
}
Instant now = clock.instant().truncatedTo(ChronoUnit.MILLIS);
EmrPersistentAppUi appUi = new EmrPersistentAppUi();
appUi.setId("p-" + EmrService.randomId(13));
appUi.setClusterId(cluster.getId());
appUi.setTypes(types);
appUi.setStatus(ACTIVE);
appUi.setAuthorId(regionResolver.getAccountId());
appUi.setCreationTime(now);
appUi.setLastModifiedTime(now);
appUi.setTags(tags != null ? new LinkedHashMap<>(tags) : new LinkedHashMap<>());
appUi.setRegion(regionResolver.getRegion());
store.put(appUi.getId(), appUi);
return new Created(copy(appUi), clusters.runtimeRoleEnabled(cluster));
}
/**
* The account's active persistent application UIs: those whose cluster runs, or ended within the 30 days for which
* "The logs are available ... after the application ends"; one whose cluster has gone, or ended earlier, frees its
* place.
*/
private long activeAppUis() {
Instant cutoff = clock.instant().minus(LOGS_KEPT);
return store.scan(key -> true).stream()
.filter(appUi -> {
EmrCluster cluster = RequestScopes.callAs(regionResolver.getAccountId(), appUi.getRegion(),
() -> clusters.findDescribedCluster(appUi.getClusterId()).orElse(null));
return cluster != null && (cluster.getEndDateTime() == null
|| cluster.getEndDateTime().isAfter(cutoff));
})
.count();
}
public synchronized EmrPersistentAppUi describe(String appUiId) {
return copy(require(appUiId));
}
/**
* A presigned URL to one of the persistent UI's types, by default its first, for the application asked for. It is
* ready at once, as Floci's page has nothing to prepare.
*/
public synchronized String persistentUrl(String appUiId, String type, String applicationId) {
List<String> violations = new ArrayList<>();
EmrService.checkEnum(violations, "persistentAppUIType", type, PERSISTENT_TYPES);
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
EmrPersistentAppUi appUi = require(appUiId);
if (type != null && !appUi.getTypes().contains(type)) {
throw EmrService.invalid("Persistent application UI " + appUiId + " has no " + type + " interface.");
}
return url(appUi.getClusterId(), type != null ? type : appUi.getTypes().get(0), applicationId);
}
/**
* A presigned URL to one of the cluster's on-cluster UIs, by default its ResourceManager, which there is only while
* the cluster runs or waits; for a dry run the request is checked and no URL is made.
*/
public String onClusterUrl(String clusterId, String type, String applicationId, boolean dryRun) {
List<String> violations = new ArrayList<>();
if (clusterId == null) {
violations.add(SmithyValidationErrors.notNull("clusterId"));
}
EmrService.checkEnum(violations, "onClusterAppUIType", type, ON_CLUSTER_TYPES);
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
EmrCluster cluster = clusters.describeCluster(clusterId);
if (!EmrClusterLifecycle.RUNNING.equals(cluster.getState())
&& !EmrClusterLifecycle.WAITING.equals(cluster.getState())) {
throw EmrService.invalid("Cluster " + clusterId + " is " + cluster.getState()
+ ", and its on-cluster application UIs are there only while it is RUNNING or WAITING.");
}
return dryRun ? null : url(clusterId, type != null ? type : "ResourceManager", applicationId);
}
/** What a page link names: an interface of a cluster, for an application or none, and when it expires. */
public record Link(String accountId, String region, String clusterId, String type, String applicationId,
long expires) {
}
/**
* 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.
*/
public Link verified(String accountId, String region, String clusterId, String type, String applicationId,
String expires, String signature) {
if (accountId == null || region == null || clusterId == null || type == null) {
return null;
}
Link link;
try {
link = new Link(accountId, region, clusterId, type, applicationId, Long.parseLong(expires));
} catch (NumberFormatException e) {
return null;
}
if (!signer.verifies(signature, signedFields(link)) || clock.instant().getEpochSecond() >= link.expires()) {
return null;
}
return link;
}
/** The cluster a page link names, as it now stands, read in its account and Region. */
public EmrCluster clusterOf(Link link) {
return clusters.describeCluster(link.clusterId());
}
private String url(String clusterId, String type, String applicationId) {
Link link = new Link(regionResolver.getAccountId(), regionResolver.getRegion(), clusterId, type,
applicationId, clock.instant().plus(VALIDITY).getEpochSecond());
return baseUrl + PATH + "?account=" + encoded(link.accountId()) + "&region=" + encoded(link.region())
+ "&cluster=" + encoded(clusterId) + "&type=" + encoded(type)
+ (applicationId != null ? "&application=" + encoded(applicationId) : "")
+ "&expires=" + link.expires() + "&signature=" + signer.sign(signedFields(link));
}
// Over what the link names, a link with no application told apart from one for an application named "null".
private static String[] signedFields(Link link) {
return new String[]{link.accountId(), link.region(), link.clusterId(), link.type(),
link.applicationId() != null ? "application" : "none",
link.applicationId() != null ? link.applicationId() : "", String.valueOf(link.expires())};
}
// The persistent UIs a cluster's release and applications give it.
private static List<String> typesOf(EmrCluster cluster) {
String release = cluster.getReleaseLabel();
List<String> types = new ArrayList<>();
if (EmrSparkSteps.names(cluster.getApplications(), EmrService.SNAPSHOT_MAPPER, "Spark")) {
types.add("SHS");
}
if (EmrService.releaseAtLeast(release, 5, 30, 1)
&& !(release != null && EmrServerlessSparkRunner.sparkRuntime(release))) {
if (EmrSparkSteps.names(cluster.getApplications(), EmrService.SNAPSHOT_MAPPER, "Tez")) {
types.add("TEZ");
}
if (EmrSparkSteps.names(cluster.getApplications(), EmrService.SNAPSHOT_MAPPER, "Hadoop")) {
types.add("YTS");
}
}
return types;
}
// The id of the EMR cluster of this account and Region an ARN names; InvalidRequestException for anything else.
private String clusterIdOf(String targetResourceArn) {
String clusterId = null;
if (AwsArnUtils.isArnFor(targetResourceArn, "elasticmapreduce")) {
AwsArnUtils.Arn arn = AwsArnUtils.parse(targetResourceArn);
if (regionResolver.getAccountId().equals(arn.accountId())
&& regionResolver.getRegion().equals(arn.region())) {
clusterId = EmrService.resourceIdOf(arn, EmrService.CLUSTER_RESOURCE);
}
}
if (clusterId == null) {
throw EmrService.invalid("TargetResourceArn " + targetResourceArn + " is not an EMR cluster of the"
+ " account in the Region; Floci keeps persistent application UIs for EMR clusters only.");
}
return clusterId;
}
private EmrPersistentAppUi require(String appUiId) {
if (appUiId == null) {
throw SmithyValidationErrors.validationException(SmithyValidationErrors.notNull("persistentAppUIId"));
}
return store.get(appUiId)
.filter(appUi -> regionResolver.getRegion().equals(appUi.getRegion()))
.orElseThrow(() -> EmrService.invalid("Persistent application UI " + appUiId + " does not exist."));
}
private static EmrPersistentAppUi copy(EmrPersistentAppUi appUi) {
return EmrService.SNAPSHOT_MAPPER.convertValue(appUi, EmrPersistentAppUi.class);
}
private static String encoded(String value) {
return URLEncoder.encode(value, StandardCharsets.UTF_8);
}
}
@@ -20,6 +20,7 @@ import io.floci.aws.services.emr.model.EmrErrorDetail;
import io.floci.aws.services.emr.model.EmrInstanceFleet;
import io.floci.aws.services.emr.model.EmrInstanceGroup;
import io.floci.aws.services.emr.model.EmrNotebookExecution;
import io.floci.aws.services.emr.model.EmrPersistentAppUi;
import io.floci.aws.services.emr.model.EmrSession;
import io.floci.aws.services.emr.model.EmrStep;
import io.floci.aws.services.emr.model.EmrStudio;
@@ -55,14 +56,16 @@ public class EmrHandler {
private final EmrService service;
private final EmrStudioService studios;
private final EmrNotebookExecutionService notebookExecutions;
private final EmrAppUiService appUis;
private final ObjectMapper objectMapper;
@Inject
public EmrHandler(EmrService service, EmrStudioService studios, EmrNotebookExecutionService notebookExecutions,
ObjectMapper objectMapper) {
EmrAppUiService appUis, ObjectMapper objectMapper) {
this.service = service;
this.studios = studios;
this.notebookExecutions = notebookExecutions;
this.appUis = appUis;
this.objectMapper = objectMapper;
}
@@ -102,6 +105,10 @@ public class EmrHandler {
case "DescribeNotebookExecution" -> handleDescribeNotebookExecution(request);
case "StopNotebookExecution" -> handleStopNotebookExecution(request);
case "ListNotebookExecutions" -> handleListNotebookExecutions(request);
case "CreatePersistentAppUI" -> handleCreatePersistentAppUi(request);
case "DescribePersistentAppUI" -> handleDescribePersistentAppUi(request);
case "GetPersistentAppUIPresignedURL" -> handleGetPersistentAppUiPresignedUrl(request);
case "GetOnClusterAppUIPresignedURL" -> handleGetOnClusterAppUiPresignedUrl(request);
case "AddInstanceGroups" -> handleAddInstanceGroups(request);
case "ListInstanceGroups" -> handleListInstanceGroups(request);
case "AddInstanceFleet" -> handleAddInstanceFleet(request);
@@ -526,7 +533,10 @@ public class EmrHandler {
}
}
// A TagList member: each Tag's Key and Value strings.
/**
* A TagList member: each Tag's Key and Value strings. A tag without its Key, "the minimum required information for
* a valid tag", is refused, in Floci's own wording.
*/
private static Map<String, String> tagList(JsonNode value, String member) {
Map<String, String> tags = new LinkedHashMap<>();
if (value.isMissingNode() || value.isNull()) {
@@ -540,9 +550,10 @@ public class EmrHandler {
throw malformed(member + " must be a list of tags");
}
String key = string(tag, "Key");
if (key != null) {
tags.put(key, string(tag, "Value"));
if (key == null) {
throw new AwsException("InvalidRequestException", "A tag in " + member + " has no Key.", 400);
}
tags.put(key, string(tag, "Value"));
}
return tags;
}
@@ -848,6 +859,62 @@ public class EmrHandler {
return values;
}
// ──────────────────────────── Application UIs ────────────────────────────
private Response handleCreatePersistentAppUi(JsonNode request) {
JsonNode containers = request.path("EMRContainersConfig");
if (!containers.isMissingNode() && !containers.isNull()) {
requireStructure(containers, "EMRContainersConfig");
string(containers, "JobRunId");
}
string(request, "XReferer");
EmrAppUiService.Created created = appUis.create(string(request, "TargetResourceArn"),
string(request, "ProfilerType"), tagList(request.path("Tags"), "Tags"));
ObjectNode response = objectMapper.createObjectNode();
response.put("PersistentAppUIId", created.appUi().getId());
response.put("RuntimeRoleEnabledCluster", created.runtimeRoleEnabledCluster());
return Response.ok(response).build();
}
private Response handleDescribePersistentAppUi(JsonNode request) {
EmrPersistentAppUi appUi = appUis.describe(string(request, "PersistentAppUIId"));
ObjectNode node = objectMapper.createObjectNode();
node.put("PersistentAppUIId", appUi.getId());
ArrayNode types = node.putArray("PersistentAppUITypeList");
appUi.getTypes().forEach(types::add);
node.put("PersistentAppUIStatus", appUi.getStatus());
node.put("AuthorId", appUi.getAuthorId());
putEpoch(node, "CreationTime", appUi.getCreationTime());
putEpoch(node, "LastModifiedTime", appUi.getLastModifiedTime());
putIfSet(node, "LastStateChangeReason", appUi.getLastStateChangeReason());
node.set("Tags", tagArray(appUi.getTags()));
ObjectNode response = objectMapper.createObjectNode();
response.set("PersistentAppUI", node);
return Response.ok(response).build();
}
private Response handleGetPersistentAppUiPresignedUrl(JsonNode request) {
bool(request, "AuthProxyCall");
string(request, "ExecutionRoleArn");
return presignedUrl(appUis.persistentUrl(string(request, "PersistentAppUIId"),
string(request, "PersistentAppUIType"), string(request, "ApplicationId")));
}
private Response handleGetOnClusterAppUiPresignedUrl(JsonNode request) {
string(request, "ExecutionRoleArn");
Boolean dryRun = bool(request, "DryRun");
return presignedUrl(appUis.onClusterUrl(string(request, "ClusterId"), string(request, "OnClusterAppUIType"),
string(request, "ApplicationId"), Boolean.TRUE.equals(dryRun)));
}
// A presigned URL's answer: ready at once, and the URL, none for a dry run.
private Response presignedUrl(String url) {
ObjectNode response = objectMapper.createObjectNode();
response.put("PresignedURLReady", true);
putIfSet(response, "PresignedURL", url);
return Response.ok(response).build();
}
// ──────────────────────────── Instance groups / fleets ────────────────────────────
private Response handleAddInstanceGroups(JsonNode request) {
@@ -4,7 +4,6 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
@@ -290,19 +289,9 @@ public class EmrNotebookExecutionService {
}
}
/**
* The execution's cluster as it now stands, or null once it is gone, which DescribeCluster answers with
* InvalidRequestException; any other failure is the caller's, not the execution's.
*/
// The execution's cluster as it now stands, or null once it is gone; any other failure is the caller's.
private EmrCluster clusterOf(EmrNotebookExecution execution) {
try {
return clusters.describeCluster(execution.getEngineId());
} catch (AwsException e) {
if ("InvalidRequestException".equals(e.getErrorCode())) {
return null;
}
throw e;
}
return clusters.findDescribedCluster(execution.getEngineId()).orElse(null);
}
private void end(EmrNotebookExecution execution, String status, String reason, Instant at) {
@@ -115,7 +115,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
// The service a step's driver belongs to, which names it and labels it.
private static final String SERVICE = "emr";
// The resource of a cluster's ARN, before its id.
private static final String CLUSTER_RESOURCE = "cluster/";
static final String CLUSTER_RESOURCE = "cluster/";
// The reason of a cluster a failed bootstrap action ended, as Terraform reported a real one's
// (hashicorp/terraform-provider-aws#4378) and the Management Guide's VPC errors page quotes it.
private static final String BOOTSTRAP_ACTION_FAILED =
@@ -503,6 +503,14 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
return call(() -> snapshotOf(requireCluster(id)));
}
/**
* The cluster of that id in the request's Region, as DescribeCluster gives it, or empty when there is none: what a
* notebook execution or an application UI asks of the cluster it names, which may have gone since.
*/
public Optional<EmrCluster> findDescribedCluster(String id) {
return id == null ? Optional.empty() : call(() -> findCluster(id).map(EmrService::snapshotOf));
}
public List<EmrCluster> listClusters(String region, List<String> states,
Instant createdAfter, Instant createdBefore) {
return call(() -> {
@@ -1048,6 +1056,23 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
return sc;
}
/**
* Whether the cluster's security configuration turns on runtime roles, its
* {@code AuthorizationConfiguration.IAMConfiguration.EnableApplicationScopedIAMRole}: false for a cluster with
* none, or whose configuration has since been deleted.
*/
public boolean runtimeRoleEnabled(EmrCluster cluster) {
if (cluster.getSecurityConfiguration() == null) {
return false;
}
return secConfigStore.get(securityConfigurationKey(regionOf(cluster), cluster.getSecurityConfiguration()))
.map(SecurityConfiguration::getSecurityConfiguration)
.map(EmrService::rawJson)
.map(json -> json.path("AuthorizationConfiguration").path("IAMConfiguration")
.path("EnableApplicationScopedIAMRole").asBoolean(false))
.orElse(false);
}
public SecurityConfiguration describeSecurityConfiguration(String name, String region) {
return secConfigStore.get(securityConfigurationKey(region, name)).orElseThrow(() -> new AwsException(
"InvalidRequestException", "Security configuration does not exist: " + name, 400));
@@ -137,7 +137,7 @@ final class EmrSessions {
}
// More than one primary node: a primary instance group of more than one instance, or a primary fleet's capacity.
private static boolean highlyAvailable(EmrCluster cluster) {
static boolean highlyAvailable(EmrCluster cluster) {
for (EmrInstanceGroup group : cluster.getInstanceGroups()) {
if (EmrService.isMasterGroup(group) && group.getRequestedInstanceCount() > 1) {
return true;
@@ -0,0 +1,53 @@
package io.floci.aws.services.emr.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* A persistent application user interface, as DescribePersistentAppUI reports it, with the cluster it was made for and
* the Region it is in.
*/
@RegisterForReflection
public class EmrPersistentAppUi {
private String id;
private String clusterId;
private List<String> types = new ArrayList<>();
private String status;
private String authorId;
private Instant creationTime;
private Instant lastModifiedTime;
private String lastStateChangeReason;
private Map<String, String> tags = new LinkedHashMap<>();
private String region;
public EmrPersistentAppUi() {}
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getClusterId() { return clusterId; }
public void setClusterId(String clusterId) { this.clusterId = clusterId; }
public List<String> getTypes() { return types; }
public void setTypes(List<String> types) { this.types = types; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public String getAuthorId() { return authorId; }
public void setAuthorId(String authorId) { this.authorId = authorId; }
public Instant getCreationTime() { return creationTime; }
public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; }
public Instant getLastModifiedTime() { return lastModifiedTime; }
public void setLastModifiedTime(Instant lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; }
public String getLastStateChangeReason() { return lastStateChangeReason; }
public void setLastStateChangeReason(String lastStateChangeReason) {
this.lastStateChangeReason = lastStateChangeReason;
}
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
}
@@ -86,19 +86,19 @@ public class EmrServerlessDashboardController {
JobRun run = view.run();
List<String> lines = new ArrayList<>();
lines.add("<table>");
row(lines, "Application", run.getApplicationId());
row(lines, "Job run", run.getJobRunId());
row(lines, "Name", run.getName());
row(lines, "Attempt", run.getAttempt() != null ? String.valueOf(run.getAttempt()) : null);
row(lines, "State", run.getState());
row(lines, "State details", run.getStateDetails());
row(lines, "Release label", run.getReleaseLabel());
row(lines, "Created", run.getCreatedAt() != null ? run.getCreatedAt().toString() : null);
row(lines, "Updated", run.getUpdatedAt() != null ? run.getUpdatedAt().toString() : null);
row(lines, "Driver logs in S3", view.logs().s3Folder());
row(lines, "Driver logs in CloudWatch Logs", view.logs().logGroup());
row(lines, "Driver stdout stream", view.logs().stdoutStream());
row(lines, "Driver stderr stream", view.logs().stderrStream());
Html.row(lines, "Application", run.getApplicationId());
Html.row(lines, "Job run", run.getJobRunId());
Html.row(lines, "Name", run.getName());
Html.row(lines, "Attempt", run.getAttempt() != null ? String.valueOf(run.getAttempt()) : null);
Html.row(lines, "State", run.getState());
Html.row(lines, "State details", run.getStateDetails());
Html.row(lines, "Release label", run.getReleaseLabel());
Html.row(lines, "Created", run.getCreatedAt() != null ? run.getCreatedAt().toString() : null);
Html.row(lines, "Updated", run.getUpdatedAt() != null ? run.getUpdatedAt().toString() : null);
Html.row(lines, "Driver logs in S3", view.logs().s3Folder());
Html.row(lines, "Driver logs in CloudWatch Logs", view.logs().logGroup());
Html.row(lines, "Driver stdout stream", view.logs().stdoutStream());
Html.row(lines, "Driver stderr stream", view.logs().stderrStream());
lines.add("</table>");
lines.add("<p>" + Html.escape(NO_UI) + "</p>");
return lines;
@@ -107,16 +107,16 @@ public class EmrServerlessDashboardController {
private static List<String> body(Session session) {
List<String> lines = new ArrayList<>();
lines.add("<table>");
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()));
Html.row(lines, "Application", session.getApplicationId());
Html.row(lines, "Session", session.getSessionId());
Html.row(lines, "Name", session.getName());
Html.row(lines, "State", session.getState());
Html.row(lines, "State details", session.getStateDetails());
Html.row(lines, "Release label", session.getReleaseLabel());
Html.row(lines, "Created", text(session.getCreatedAt()));
Html.row(lines, "Started", text(session.getStartedAt()));
Html.row(lines, "Idle since", text(session.getIdleSince()));
Html.row(lines, "Ended", text(session.getEndedAt()));
lines.add("</table>");
lines.add("<p>" + Html.escape(NO_SESSION_UI) + "</p>");
return lines;
@@ -126,18 +126,7 @@ public class EmrServerlessDashboardController {
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<String> lines, String name, String value) {
if (value != null && !value.isEmpty()) {
lines.add("<tr><th>" + Html.escape(name) + "</th><td>" + Html.escape(value) + "</td></tr>");
}
}
private static Response page(int status, String title, List<String> body) {
String html = "<!doctype html>\n"
+ "<html lang=\"en\"><head><meta charset=\"utf-8\"><title>" + Html.escape(title)
+ "</title></head>\n<body>\n<h1>" + Html.escape(title) + "</h1>\n"
+ String.join("\n", body) + "\n</body></html>\n";
return Response.status(status).type(MediaType.TEXT_HTML).entity(html).build();
return Response.status(status).type(MediaType.TEXT_HTML).entity(Html.page(title, body)).build();
}
}
@@ -1,19 +1,14 @@
package io.floci.aws.services.emrserverless;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.LinkSigner;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Clock;
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",
@@ -30,22 +25,24 @@ public class EmrServerlessDashboards {
/** Where Floci serves the page a link opens. */
static final String PATH = "/_aws/emr-serverless/dashboard";
static final Duration VALIDITY = Duration.ofHours(1);
private static final String ALGORITHM = "HmacSHA256";
private static final int KEY_BYTES = 32;
private final String baseUrl;
private final Clock clock;
private final byte[] key;
private final LinkSigner signer;
@Inject
public EmrServerlessDashboards(EmulatorConfig config, Clock clock) {
this(config.effectiveBaseUrl(), clock, newKey());
this(config.effectiveBaseUrl(), clock, LinkSigner.withNewKey());
}
EmrServerlessDashboards(String baseUrl, Clock clock, byte[] key) {
this(baseUrl, clock, new LinkSigner(key));
}
private EmrServerlessDashboards(String baseUrl, Clock clock, LinkSigner signer) {
this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
this.clock = clock;
this.key = key.clone();
this.signer = signer;
}
/**
@@ -86,8 +83,7 @@ public class EmrServerlessDashboards {
} catch (NumberFormatException e) {
return null;
}
byte[] expected = signature(link).getBytes(StandardCharsets.US_ASCII);
if (!MessageDigest.isEqual(expected, signature.getBytes(StandardCharsets.US_ASCII))
if (!signer.verifies(signature, signedFields(link))
|| clock.instant().getEpochSecond() >= link.expires()) {
return null;
}
@@ -109,23 +105,14 @@ public class EmrServerlessDashboards {
// 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() != null ? "jobRun" : "session",
link.jobRunId() != null ? link.jobRunId() : link.sessionId(),
String.valueOf(link.attempt()), String.valueOf(link.expires()));
try {
Mac mac = Mac.getInstance(ALGORITHM);
mac.init(new SecretKeySpec(key, ALGORITHM));
return HexFormat.of().formatHex(mac.doFinal(signed.getBytes(StandardCharsets.UTF_8)));
} catch (GeneralSecurityException e) {
throw new IllegalStateException("Could not sign an EMR Serverless dashboard link", e);
}
return signer.sign(signedFields(link));
}
private static byte[] newKey() {
byte[] key = new byte[KEY_BYTES];
new SecureRandom().nextBytes(key);
return key;
private static String[] signedFields(Link link) {
return new String[]{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())};
}
private static String encoded(String value) {
@@ -2,7 +2,11 @@ package io.floci.aws.core.common;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class HtmlTest {
@@ -12,6 +16,19 @@ class HtmlTest {
Html.escape("<a href=\"x\" title='y'>R&D</a>"));
}
@Test
void aPageEscapesItsTitleAndARowEscapesItsCellsAndIsLeftOutWithoutAValue() {
List<String> lines = new ArrayList<>();
Html.row(lines, "Name", "<b>");
Html.row(lines, "Empty", "");
Html.row(lines, "Absent", null);
assertEquals(List.of("<tr><th>Name</th><td>&lt;b&gt;</td></tr>"), lines);
String page = Html.page("A & B", lines);
assertTrue(page.contains("<title>A &amp; B</title>"), page);
assertTrue(page.contains("<h1>A &amp; B</h1>\n<tr><th>Name</th>"), page);
}
@Test
void anEntityAlreadyWrittenIsEscapedAgainRatherThanReadAsOne() {
assertEquals("&amp;lt;", Html.escape("&lt;"));
@@ -0,0 +1,27 @@
package io.floci.aws.core.common;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class LinkSignerTest {
private static final byte[] KEY = "a key of this process, 32 bytes!".getBytes(StandardCharsets.US_ASCII);
@Test
void aSignatureVerifiesForTheSameFieldsAndKeyAndForNothingElse() {
LinkSigner signer = new LinkSigner(KEY);
String signature = signer.sign("123456789012", "us-east-1", "j-1", "SHS");
assertEquals(signature, new LinkSigner(KEY).sign("123456789012", "us-east-1", "j-1", "SHS"));
assertTrue(signer.verifies(signature, "123456789012", "us-east-1", "j-1", "SHS"));
assertFalse(signer.verifies(signature, "123456789012", "us-east-1", "j-1", "TEZ"));
assertFalse(signer.verifies(signature, "123456789012", "us-east-1", "j-1"));
assertFalse(signer.verifies(null, "123456789012", "us-east-1", "j-1", "SHS"));
assertFalse(LinkSigner.withNewKey().verifies(signature, "123456789012", "us-east-1", "j-1", "SHS"));
}
}
@@ -0,0 +1,183 @@
package io.floci.aws.services.emr;
import io.floci.aws.core.common.Html;
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 java.net.URI;
import java.util.List;
import java.util.UUID;
import static io.floci.aws.testing.EmrRequests.emr;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* A cluster's application UIs over the AWS JSON 1.1 wire protocol: CreatePersistentAppUI, DescribePersistentAppUI and
* the two presigned URL operations, and the page Floci serves for their URLs, as it serves no application UI itself.
*/
@QuarkusTest
class EmrAppUiIntegrationTest {
private static final String ARN = "arn:aws:elasticmapreduce:us-east-1:000000000000:cluster/";
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void aPersistentAppUiIsMadeForAClusterAndItsPresignedUrlOpensFlocisPage() {
String clusterId = cluster("emr-6.15.0", "[{\"Name\":\"Spark\"},{\"Name\":\"Tez\"},{\"Name\":\"Hadoop\"}]", "");
String appUiId = emr("CreatePersistentAppUI", "{\"TargetResourceArn\":\"" + ARN + clusterId + "\","
+ "\"Tags\":[{\"Key\":\"team\",\"Value\":\"data\"}]}")
.then().statusCode(200)
.body("PersistentAppUIId", matchesPattern("p-[A-Z0-9]{13}"))
.body("RuntimeRoleEnabledCluster", equalTo(false))
.extract().path("PersistentAppUIId");
emr("DescribePersistentAppUI", "{\"PersistentAppUIId\":\"" + appUiId + "\"}")
.then().statusCode(200)
.body("PersistentAppUI.PersistentAppUIId", equalTo(appUiId))
.body("PersistentAppUI.PersistentAppUITypeList", equalTo(List.of("SHS", "TEZ", "YTS")))
.body("PersistentAppUI.PersistentAppUIStatus", equalTo("ACTIVE"))
.body("PersistentAppUI.AuthorId", equalTo("000000000000"))
.body("PersistentAppUI.CreationTime", notNullValue())
.body("PersistentAppUI.Tags[0].Key", equalTo("team"));
String url = emr("GetPersistentAppUIPresignedURL", "{\"PersistentAppUIId\":\"" + appUiId + "\","
+ "\"PersistentAppUIType\":\"TEZ\",\"ApplicationId\":\"application_1_0001\"}")
.then().statusCode(200)
.body("PresignedURLReady", equalTo(true))
.extract().path("PresignedURL");
page(url).then().statusCode(200).contentType(containsString("text/html"))
.body(containsString("<h1>TEZ of cluster " + clusterId + "</h1>"))
.body(containsString("<tr><th>Application</th><td>application_1_0001</td></tr>"))
.body(containsString(Html.escape(EmrAppUiController.NO_UI)));
page(url.replace("type=TEZ", "type=SHS")).then().statusCode(403)
.body(containsString(Html.escape(EmrAppUiController.INVALID)));
String withoutApplication = emr("GetPersistentAppUIPresignedURL", "{\"PersistentAppUIId\":\"" + appUiId
+ "\"}")
.then().statusCode(200).extract().path("PresignedURL");
page(withoutApplication).then().statusCode(200);
// A link with no application is not one for an application named "null".
page(withoutApplication.replace("&expires=", "&application=null&expires=")).then().statusCode(403);
terminate(clusterId);
}
@Test
void theProfilerTypeAskedForIsTheUisOneInterfaceAndATagNeedsAKey() {
String clusterId = cluster("emr-6.15.0", "[{\"Name\":\"Spark\"},{\"Name\":\"Tez\"}]", "");
String appUiId = emr("CreatePersistentAppUI", "{\"TargetResourceArn\":\"" + ARN + clusterId + "\","
+ "\"ProfilerType\":\"TEZUI\"}")
.then().statusCode(200).extract().path("PersistentAppUIId");
emr("DescribePersistentAppUI", "{\"PersistentAppUIId\":\"" + appUiId + "\"}")
.then().statusCode(200)
.body("PersistentAppUI.PersistentAppUITypeList", equalTo(List.of("TEZ")));
emr("CreatePersistentAppUI", "{\"TargetResourceArn\":\"" + ARN + clusterId + "\",\"ProfilerType\":\"YTS\"}")
.then().statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
emr("CreatePersistentAppUI", "{\"TargetResourceArn\":\"" + ARN + clusterId + "\","
+ "\"Tags\":[{\"Value\":\"no-key\"}]}")
.then().statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
terminate(clusterId);
}
@Test
void anOnClusterUrlIsThereWhileTheClusterRunsAndADryRunGivesNone() {
String clusterId = cluster("emr-6.15.0", "[{\"Name\":\"Spark\"},{\"Name\":\"Hadoop\"}]", "");
String url = emr("GetOnClusterAppUIPresignedURL", "{\"ClusterId\":\"" + clusterId + "\","
+ "\"OnClusterAppUIType\":\"SparkHistoryServer\"}")
.then().statusCode(200)
.body("PresignedURLReady", equalTo(true))
.extract().path("PresignedURL");
page(url).then().statusCode(200)
.body(containsString("<h1>SparkHistoryServer of cluster " + clusterId + "</h1>"));
emr("GetOnClusterAppUIPresignedURL", "{\"ClusterId\":\"" + clusterId + "\",\"DryRun\":true}")
.then().statusCode(200)
.body("PresignedURLReady", equalTo(true))
.body("PresignedURL", nullValue());
emr("GetOnClusterAppUIPresignedURL", "{\"ClusterId\":\"" + clusterId + "\","
+ "\"OnClusterAppUIType\":\"Ganglia\"}")
.then().statusCode(400)
.body("__type", equalTo("ValidationException"));
terminate(clusterId);
emr("GetOnClusterAppUIPresignedURL", "{\"ClusterId\":\"" + clusterId + "\"}")
.then().statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
}
@Test
void aPersistentAppUiIsRefusedForAnOldReleaseAnotherResourceOrAnInterfaceTheClusterHasNot() {
String old = cluster("emr-5.24.0", "[{\"Name\":\"Spark\"}]", "");
emr("CreatePersistentAppUI", "{\"TargetResourceArn\":\"" + ARN + old + "\"}")
.then().statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
emr("CreatePersistentAppUI", "{\"TargetResourceArn\":\"arn:aws:emr-containers:us-east-1:000000000000:"
+ "/virtualclusters/abc\"}")
.then().statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
emr("CreatePersistentAppUI", "{}")
.then().statusCode(400)
.body("__type", equalTo("ValidationException"));
String sparkOnly = cluster("emr-5.29.0", "[{\"Name\":\"Spark\"}]", "");
String appUiId = emr("CreatePersistentAppUI", "{\"TargetResourceArn\":\"" + ARN + sparkOnly + "\"}")
.then().statusCode(200).extract().path("PersistentAppUIId");
emr("DescribePersistentAppUI", "{\"PersistentAppUIId\":\"" + appUiId + "\"}")
.then().statusCode(200)
.body("PersistentAppUI.PersistentAppUITypeList", equalTo(List.of("SHS")));
emr("GetPersistentAppUIPresignedURL", "{\"PersistentAppUIId\":\"" + appUiId + "\","
+ "\"PersistentAppUIType\":\"TEZ\"}")
.then().statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
terminate(old);
terminate(sparkOnly);
}
@Test
void aClusterWhoseSecurityConfigurationTurnsOnRuntimeRolesIsReportedAsOne() {
String name = "runtime-roles-" + UUID.randomUUID();
emr("CreateSecurityConfiguration", "{\"Name\":\"" + name + "\",\"SecurityConfiguration\":"
+ "\"{\\\"AuthorizationConfiguration\\\":{\\\"IAMConfiguration\\\":"
+ "{\\\"EnableApplicationScopedIAMRole\\\":true}}}\"}")
.then().statusCode(200);
String clusterId = cluster("emr-6.15.0", "[{\"Name\":\"Spark\"}]",
"\"SecurityConfiguration\": \"" + name + "\",");
emr("CreatePersistentAppUI", "{\"TargetResourceArn\":\"" + ARN + clusterId + "\"}")
.then().statusCode(200)
.body("RuntimeRoleEnabledCluster", equalTo(true));
terminate(clusterId);
}
private static String cluster(String releaseLabel, String applications, String extra) {
return emr("RunJobFlow", """
{"Name": "app-uis", "ReleaseLabel": "%s", "Applications": %s, %s
"Instances": {"KeepJobFlowAliveWhenNoSteps": true,
"InstanceGroups": [{"Name": "primary", "InstanceRole": "MASTER", "InstanceType": "m5.xlarge",
"InstanceCount": 1}]}}
""".formatted(releaseLabel, applications, extra))
.then().statusCode(200).extract().path("JobFlowId");
}
private static void terminate(String clusterId) {
emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + clusterId + "\"]}").then().statusCode(200);
}
// 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());
}
}
@@ -0,0 +1,57 @@
package io.floci.aws.services.emr;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.LinkSigner;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrPersistentAppUi;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import static io.floci.aws.services.emr.EmrServiceFixture.ACCOUNT;
import static io.floci.aws.services.emr.EmrServiceFixture.REGION;
import static io.floci.aws.services.emr.EmrServiceFixture.cluster;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** The account's cap on persistent application UIs, which ended clusters' UIs leave, via {@link EmrAppUiService}. */
class EmrAppUiServiceTest {
private final EmrServiceFixture fixture = new EmrServiceFixture(0, 0, 0);
private final EmrAppUiService appUis = new EmrAppUiService(
AccountAwareStorageBackend.<EmrPersistentAppUi>inMemory(ACCOUNT), fixture.service,
new RegionResolver(REGION, ACCOUNT), fixture.clock, "http://localhost:4566", LinkSigner.withNewKey());
@Test
void aUiOfAClusterThatEndedMoreThanThirtyDaysAgoNoLongerCountsAgainstTheCap() {
String ended = sparkCluster();
for (int i = 0; i < EmrAppUiService.MAX_PERSISTENT_APP_UIS; i++) {
appUis.create(arn(ended), null, null);
}
String next = sparkCluster();
AwsException full = assertThrows(AwsException.class, () -> appUis.create(arn(next), null, null));
assertTrue(full.getMessage().contains("200 persistent application UIs"), full.getMessage());
fixture.service.terminateJobFlows(List.of(ended));
fixture.clock.advance(EmrAppUiService.LOGS_KEPT.minus(Duration.ofMinutes(1)));
assertThrows(AwsException.class, () -> appUis.create(arn(next), null, null));
fixture.clock.advance(Duration.ofMinutes(2));
assertEquals("ACTIVE", appUis.create(arn(next), null, null).appUi().getStatus());
}
private String sparkCluster() {
EmrCluster cluster = cluster("app-uis", true);
cluster.setReleaseLabel("emr-6.15.0");
cluster.setApplications("[{\"Name\":\"Spark\"}]");
return fixture.service.runJobFlow(cluster, REGION).getId();
}
private static String arn(String clusterId) {
return "arn:aws:elasticmapreduce:us-east-1:000000000000:cluster/" + clusterId;
}
}
@@ -136,8 +136,8 @@ class EmrNotebookExecutionServiceTest {
EmrCluster cluster = clusterSpec("emr-6.15.0", NOTEBOOK_APPS);
cluster.setId("j-FAILING");
cluster.setState("WAITING");
when(failing.describeCluster("j-FAILING")).thenReturn(cluster)
.thenThrow(new IllegalStateException("storage unavailable"));
when(failing.describeCluster("j-FAILING")).thenReturn(cluster);
when(failing.findDescribedCluster("j-FAILING")).thenThrow(new IllegalStateException("storage unavailable"));
EmrNotebookExecutionService service = new EmrNotebookExecutionService(store, failing,
new RegionResolver(REGION, ACCOUNT), fixture.clock, RUN);
String id = service.start(request("j-FAILING")).getId();
@@ -1113,7 +1113,7 @@ class EmrServiceContainerStepsTest {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode answer = (JsonNode) new EmrHandler(service, mock(EmrStudioService.class),
mock(EmrNotebookExecutionService.class), objectMapper)
mock(EmrNotebookExecutionService.class), mock(EmrAppUiService.class), objectMapper)
.handle("DescribeStep", objectMapper.createObjectNode().put("ClusterId", cluster.getId())
.put("StepId", cluster.getSteps().get(0).getId()), REGION).getEntity();
@@ -2042,7 +2042,7 @@ class EmrServiceContainerStepsTest {
String waitingId = bootstrapping.service.runJobFlow(cluster("waiting", true), REGION).getId();
ObjectMapper objectMapper = new ObjectMapper();
EmrHandler handler = new EmrHandler(bootstrapping.service, mock(EmrStudioService.class),
mock(EmrNotebookExecutionService.class), objectMapper);
mock(EmrNotebookExecutionService.class), mock(EmrAppUiService.class), objectMapper);
String page = ERROR_CODE_PAGES + "BOOTSTRAP_FAILURE_PRIMARY_WITH_NON_ZERO_CODE.html";
JsonNode expected = objectMapper.readTree("""
[{"ErrorCode": "BOOTSTRAP_FAILURE_PRIMARY_WITH_NON_ZERO_CODE",
@@ -3,6 +3,7 @@ package io.floci.aws.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.emr.EmrAppUiService;
import io.floci.aws.services.emr.EmrHandler;
import io.floci.aws.services.emr.EmrNotebookExecutionService;
import io.floci.aws.services.emr.EmrService;
@@ -75,7 +76,8 @@ class AslExecutorEmrSyncTest {
.customResourceLiveness(null)
.emrTaskInvoker(new EmrTaskInvoker(
new EmrHandler(emrService, mock(EmrStudioService.class),
mock(EmrNotebookExecutionService.class), objectMapper), objectMapper))
mock(EmrNotebookExecutionService.class), mock(EmrAppUiService.class), objectMapper),
objectMapper))
.nanoTime(testNanos::get)
.sleeper(testNanos::addAndGet)
.build();