feat(emr): open a cluster's on-cluster application UIs for real in the docker runner mode (#8773)

With runner-mode docker, GetOnClusterAppUIPresignedURL now opens the
interfaces that run on the cluster's primary node for real: its
ResourceManager, an application master through the ResourceManager's
web proxy, its MapReduce JobHistory server, and the NodeManager of a
primary node that works.

Each opens on a host of its own, as AWS's application UIs do under
emrappui-prod.<region>.amazonaws.com, which are on the Public Suffix
List: http://<secret>-<port>.emrappui.<Floci's host and port>/, the
secret 26 random base32 characters only the link holds, so the host is
the link's authority, as the interface takes no AWS credentials.
EmrAppUiProxy, a Vert.x route ahead of the REST layer, sends a request
to that host on to the node's port, which the primary node publishes on
the host's loopback interface (Floci in a container joins the cluster's
network instead). It asks the interface under the browser's host, so
the links the interface writes itself are the browser's, and makes each
link the node's daemons write to one another by the node's name a link
to that interface's own host under the same secret, in text answers and
Location headers; an answer too large to hold goes on unchanged. A
request's body streams on as it arrives, an interface that sends nothing
for a minute has the request given up, and a link of a cluster that has
ended opens nothing, the node's port it found asked for again every ten
seconds while the cluster runs.

A link asked for before the primary node runs, as on a cluster no step
has run on yet, starts the node as a step would, through runOnCluster,
running nothing, and is not PresignedURLReady until the node is; its
host answers 503 meanwhile. With an ApplicationId each interface lands
on the application's page. The link lasts an hour, as Floci's page
links do. An interface Floci does not run (the Spark History Server,
the YARN timeline server, the Tez UI), and any link in the immediate
mode, still opens Floci's own page.

Floci's TLS certificate names *.emrappui.localhost and
*.emrappui.localhost.floci.io.

Lambda's CreateFunction and UpdateFunctionCode now refuse a direct
ZipFile upload over 50 MB from its Base64 length, before decoding it,
so a request already over the limit takes no more memory than it came
in; its RequestEntityTooLargeException is as before, and the test of it
builds its oversized upload without the bytes behind it.

EmrAppUiNightlyIntegrationTest runs it for real on an emr-7.5.0
cluster: the ResourceManager's link starts the primary node and opens
the ResourceManager, and after a MapReduce step its REST answer's links
open the application master's logs on the NodeManager's host and,
through the web proxy's redirect, the job on the JobHistory server's
host, as the JobHistory server's own link does. The nightly job's
timeout and image prefetch take the new check.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-17 19:48:12 -04:00
1 parent 87a93ebe92
commit 4b342dad3f
17 files changed
+1279 -33

No files matched your search

+4 -3
View File
@@ -115,10 +115,11 @@ starts ElbV2LambdaTargetDataPlaneIntegrationTest && ecr public.ecr.aws/lambda/py
# default template names (EmrServerlessSparkRunner), 3.5 GB, so it is queued last, behind the Lambda runtimes;
# Of the nightly checks, EmrHiveStepsNightlyIntegrationTest runs a cluster's other steps in it,
# EmrServerlessCustomImageNightlyIntegrationTest builds its custom image on it,
# EmrFlociContainerNightlyIntegrationTest runs a cluster's steps in it from Floci in a container, and
# EmrPigStepsNightlyIntegrationTest a cluster's Pig steps.
# EmrFlociContainerNightlyIntegrationTest runs a cluster's steps in it from Floci in a container,
# EmrPigStepsNightlyIntegrationTest a cluster's Pig steps, and EmrAppUiNightlyIntegrationTest a cluster's MapReduce one.
starts EmrDockerRunnerDockerIntegrationTest EmrHiveStepsNightlyIntegrationTest EmrServerlessCustomImageNightlyIntegrationTest \
EmrFlociContainerNightlyIntegrationTest EmrPigStepsNightlyIntegrationTest EmrNotebookExecutionNightlyIntegrationTest \
EmrAppUiNightlyIntegrationTest \
&& ecr public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest
# EmrServerlessHiveDockerIntegrationTest runs EMR Serverless Hive job runs, and EmrHiveStepsNightlyIntegrationTest EMR
# Hive steps, in the emr-7.5.0 Hive image the runner's default Hive template names, 2.7 GB; every EMR cluster runs its
@@ -127,7 +128,7 @@ starts EmrDockerRunnerDockerIntegrationTest EmrHiveStepsNightlyIntegrationTest E
# Hadoop comes from it too).
starts EmrServerlessHiveDockerIntegrationTest EmrHiveStepsNightlyIntegrationTest EmrDockerRunnerDockerIntegrationTest \
EmrFlociContainerNightlyIntegrationTest EmrPigStepsNightlyIntegrationTest EmrSessionServerNightlyIntegrationTest \
EmrNotebookExecutionNightlyIntegrationTest \
EmrNotebookExecutionNightlyIntegrationTest EmrAppUiNightlyIntegrationTest \
&& ecr public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest
# The nightly EmrServerlessSparkConnectNightlyIntegrationTest runs a session's Spark Connect server, and its client, in
# the emr-7.13.0 image, 3.7 GB, the first release with sessions.
+5 -4
View File
@@ -33,10 +33,11 @@ jobs:
# EmrFlociContainerNightlyIntegrationTest's 20 and 4 for its setup,
# EmrServerlessCustomImageNightlyIntegrationTest's 85 and 21 for its setup,
# EmrServerlessSparkConnectNightlyIntegrationTest's 30, EmrSessionServerNightlyIntegrationTest's 40,
# EmrHiveStepsNightlyIntegrationTest's five two-minute tests, one five-minute test and six-minute setup, and
# EmrNotebookExecutionNightlyIntegrationTest's 40, 291 in all. A check added, or a bound raised, raises this with it,
# so a slow check fails with its own message rather than the job being cancelled with none.
timeout-minutes: 311
# EmrHiveStepsNightlyIntegrationTest's five two-minute tests, one five-minute test and six-minute setup,
# EmrNotebookExecutionNightlyIntegrationTest's 40, and EmrAppUiNightlyIntegrationTest's 30, 321 in all. A check
# added, or a bound raised, raises this with it, so a slow check fails with its own message rather than the job
# being cancelled with none.
timeout-minutes: 341
# A fork's schedule would spend its owner's minutes on checks it never asked for; a draft waits until it is
# ready for review, as the CI shards do.
if: >-
+32 -8
View File
@@ -46,7 +46,7 @@ Floci emulates the Amazon EMR (Elastic MapReduce) management API. Clusters (job
| `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 |
| `GetOnClusterAppUIPresignedURL` | Returns a presigned URL to a running cluster's on-cluster UI, which opens for real in the `docker` mode; see [Application UIs](#application-uis) |
| `GetClusterSessionCredentials` | Returns temporary basic credentials for a runtime role enabled cluster; see [Application UIs](#application-uis) |
| `AddInstanceGroups` | Adds instance groups to a running cluster |
| `ListInstanceGroups` | Lists the instance groups of a cluster |
@@ -373,11 +373,29 @@ not Jupyter:
## 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`.
Floci keeps a cluster's persistent application UIs, but serves no Spark History Server, Tez UI or YARN timeline
server: a presigned URL to one of those 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, and so does
one to an on-cluster UI in the `immediate` mode. 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`.
In the `docker` mode, an on-cluster UI that runs on the cluster's primary node opens for real: the `ResourceManager`
("YARN ResourceManager | http://master-public-dns-name:8088/"), an `ApplicationMaster` through the ResourceManager's
web proxy, and the `JobHistoryServer`, on a cluster whose primary node runs YARN (see **YARN**). Each opens on a host of
its own, as AWS's application UIs are on hosts of their own under "emrappui-prod.us-east-1.amazonaws.com", which "are
registered in the Public Suffix List": `http://<secret>-<port>.emrappui.<Floci's host and port>/`, the secret 26
random letters and digits that only this link holds, so the host itself is the link's authority, as the interface
takes no AWS credentials. Floci's host must resolve its subdomains: `localhost` and `localhost.floci.io` do, and Floci's
TLS certificate names `*.emrappui.localhost` and `*.emrappui.localhost.floci.io`. Requests to the host go on to that
port of the primary node, which Floci reaches at a port Docker publishes on the host's loopback interface alone, or,
Floci in a container, on the cluster's network, which its container joins; the node's daemons write their links to
one another by the node's name, and Floci makes each such link, in the text it sends, a link to that interface's own
host under the same secret, so the ResourceManager's links to a job's history and to its containers' logs on the
NodeManager of a primary node that works open too. A NodeManager on a core or task node, which Floci does not reach,
keeps its links as written. The link lasts an hour, as the page's does, after which its host answers with a `403`
page; once its cluster has ended, its host answers with a `404` one. A request's body goes on to the interface as it
arrives, and an interface that sends nothing for a minute has the request given up with a `502` page.
* **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
@@ -395,8 +413,14 @@ Floci restarted opens a `403` page, and one whose cluster has gone a `404`.
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.
refused, and the URL is `PresignedURLReady` at once. **GetOnClusterAppUIPresignedURL** gives one to an on-cluster UI,
the `ResourceManager` by default, while the cluster is `RUNNING` or `WAITING`, and none for a `DryRun`. With an
`ApplicationId`, the ResourceManager's link lands on the application's page, an application master's on its UI
through the web proxy, and the JobHistory server's on the job of that id (`job_` in place of `application_`); without
one, on the cluster's applications, its running ones, and its jobs. A link Floci opens for real is
`PresignedURLReady` once the primary node is: until then, as on a cluster no step has run on yet, the node starts as
a step's would ("Used to determine if the presigned URL is ready"), and its host answers with a `503` page meanwhile.
Any other is ready at once.
* **GetClusterSessionCredentials** gives "temporary, HTTP basic credentials that are associated with a given runtime
IAM role and used by a cluster with fine-grained access control activated": a random username and password that
expire in an hour, as no source gives AWS's lifetime, for a `RUNNING` or `WAITING` cluster on `emr-6.11.0` or later
@@ -78,6 +78,7 @@ public class TlsConfigSource implements ConfigSource {
"*.execute-api.localhost.floci.io",
"*.execute-api.localhost.localstack.cloud",
"*.cloudfront.localhost.floci.io", "*.cloudfront.localhost",
"*.emrappui.localhost.floci.io", "*.emrappui.localhost",
"host.docker.internal"));
for (String region : AwsRegions.KNOWN_IDS.stream().sorted().toList()) {
sans.add("*.dkr.ecr." + region + ".localhost.floci.io");
@@ -1,10 +1,12 @@
package io.floci.aws.services.emr;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.emrserverless.SparkJobRunner;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.BooleanSupplier;
import java.util.function.Function;
@@ -157,6 +159,14 @@ public interface ClusterStorage {
}
}
/**
* Where Floci reaches {@code port}, a web interface's, on {@code clusterId}'s primary node: empty while the node is
* not running and ready, or where Floci cannot reach it.
*/
default Optional<ContainerLifecycleManager.EndpointInfo> webInterface(String clusterId, int port) {
return Optional.empty();
}
/**
* Removes {@code clusterId}'s HDFS and the volumes of its storage once it no longer needs them: true when the
* volumes are gone, false when Docker refused, so the caller can try again.
@@ -0,0 +1,251 @@
package io.floci.aws.services.emr;
import io.floci.aws.core.common.Html;
import io.floci.aws.core.common.ServiceConfigAccess;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.http.HttpClientResponse;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.http.RequestOptions;
import io.vertx.core.net.SocketAddress;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* The on-cluster application UIs Floci opens for real ({@link EmrAppUiService}): a request to an interface's own host,
* {@code <secret>-<port>.emrappui.<Floci's host>}, goes on to that port of the cluster's primary node, and its answer
* comes back with each link to one of the node's interfaces, which its daemons write by the node's name, made a link
* to that interface's own host. The secret in the host is the link's authority, as no request to the interface carries
* AWS credentials; one that is not this process's, or whose hour has passed, is answered with a page saying so.
*/
@ApplicationScoped
public class EmrAppUiProxy {
private static final Logger LOG = Logger.getLogger(EmrAppUiProxy.class);
// What does not go on: the connection's own headers, the host, which the interface is asked for under the
// browser's, and the encodings the browser takes, as only an answer that is not compressed can have its links made
// the browser's.
private static final Set<String> NOT_FORWARDED = Set.of("host", "connection", "keep-alive", "proxy-connection",
"transfer-encoding", "upgrade", "te", "trailer", "proxy-authorization", "proxy-authenticate",
"accept-encoding");
// The answers whose links are made the browser's: the interfaces' pages, scripts and REST answers.
private static final List<String> TEXT_TYPES = List.of("text/", "application/json", "application/javascript",
"application/xml");
// The most of an answer held to make its links the browser's; a larger one, a long log for one, goes on as it is.
private static final int MAX_REWRITTEN = 8 * 1024 * 1024;
// How long the interface may send nothing, its answer or the rest of it, before the request is given up.
private static final Duration IDLE_TIMEOUT = Duration.ofMinutes(1);
private final EmrAppUiService appUis;
private final ServiceConfigAccess serviceConfigAccess;
private final Vertx vertx;
private final HttpClient client;
private final Duration idleTimeout;
@Inject
public EmrAppUiProxy(EmrAppUiService appUis, ServiceConfigAccess serviceConfigAccess, Vertx vertx) {
this(appUis, serviceConfigAccess, vertx, IDLE_TIMEOUT);
}
EmrAppUiProxy(EmrAppUiService appUis, ServiceConfigAccess serviceConfigAccess, Vertx vertx,
Duration idleTimeout) {
this.appUis = appUis;
this.serviceConfigAccess = serviceConfigAccess;
this.vertx = vertx;
this.idleTimeout = idleTimeout;
this.client = vertx.createHttpClient(new HttpClientOptions().setConnectTimeout(5_000));
}
@PreDestroy
void close() {
client.close();
}
void register(@Observes Router router) {
router.route().handler(this::handle);
}
void handle(RoutingContext context) {
HttpServerRequest request = context.request();
String hostHeader = request.getHeader("host");
// This route runs ahead of the filter that refuses a disabled service, so it checks for itself.
if (hostHeader == null || !hostHeader.toLowerCase(Locale.ROOT).contains("." + EmrAppUiService.UI_HOST + ".")
|| !serviceConfigAccess.isEnabled("emr")) {
context.next();
return;
}
request.pause();
// Finding the interface may ask Docker where it is, so off the event loop.
vertx.<EmrAppUiService.UiRoute>executeBlocking(() -> appUis.route(hostHeader, request.scheme()), false)
.onComplete(routed -> {
if (routed.failed()) {
LOG.warnv(routed.cause(), "EMR application UI request to {0} could not be routed",
hostHeader);
refuse(request, 502, "The interface could not be reached.");
} else if (routed.result() == null) {
request.resume();
context.next();
} else if (routed.result().refusal() != null) {
refuse(request, routed.result().status(), routed.result().refusal());
} else {
forward(request, hostHeader, routed.result());
}
});
}
private void forward(HttpServerRequest request, String hostHeader, EmrAppUiService.UiRoute route) {
URI authority = URI.create("http://" + hostHeader);
RequestOptions options = new RequestOptions().setMethod(request.method())
.setServer(SocketAddress.inetSocketAddress(route.port(), route.host()))
.setHost(authority.getHost())
.setPort(authority.getPort() > 0 ? authority.getPort() : "https".equals(request.scheme()) ? 443 : 80)
.setURI(request.uri())
.setIdleTimeout(idleTimeout.toMillis());
for (Map.Entry<String, String> header : request.headers()) {
if (!NOT_FORWARDED.contains(header.getKey().toLowerCase(Locale.ROOT))) {
options.addHeader(header.getKey(), header.getValue());
}
}
options.putHeader("accept-encoding", "identity");
HttpServerResponse response = request.response();
client.request(options).onComplete(opened -> {
if (opened.failed()) {
route.unreachable().run();
refuse(request, 502, "The cluster's interface did not answer: " + opened.cause().getMessage());
return;
}
HttpClientRequest upstream = opened.result();
// A body sent in chunks goes on in chunks.
if (request.getHeader("content-length") == null && request.getHeader("transfer-encoding") != null) {
upstream.setChunked(true);
}
// A browser that goes away takes its request with it.
response.closeHandler(closed -> upstream.reset());
// The answer is held as it arrives, its body read once the relay is ready for it.
upstream.response().map(HttpClientResponse::pause).onComplete(answered -> {
if (answered.failed()) {
route.unreachable().run();
if (response.headWritten()) {
response.reset();
} else {
refuse(request, 502, "The cluster's interface did not answer: "
+ answered.cause().getMessage());
}
return;
}
relay(answered.result(), response, request.method(),
request.method() == HttpMethod.HEAD ? Map.of() : route.rewrites());
});
// The request's body goes on as it arrives, held back while the interface takes it more slowly, so none
// is held whole.
request.pipeTo(upstream).onFailure(failure -> {
upstream.reset();
if (!response.ended()) {
response.reset();
}
});
});
}
// The interface's answer, its links to the node's interfaces made the browser's in the text it sends.
private static void relay(HttpClientResponse answer, HttpServerResponse response, HttpMethod method,
Map<String, String> rewrites) {
boolean rewritten = rewritable(answer.getHeader("content-type")) && !rewrites.isEmpty();
response.setStatusCode(answer.statusCode()).setStatusMessage(answer.statusMessage());
MultiMap headers = answer.headers();
for (Map.Entry<String, String> header : headers) {
String name = header.getKey().toLowerCase(Locale.ROOT);
if (NOT_FORWARDED.contains(name) || rewritten && name.equals("content-length")) {
continue;
}
response.headers().add(header.getKey(), name.equals("location")
? rewrite(header.getValue(), rewrites) : header.getValue());
}
if (!rewritten) {
// One the interface streams, with no length, goes on in chunks as it came.
int status = answer.statusCode();
if (answer.getHeader("content-length") == null && method != HttpMethod.HEAD && status != 204
&& status != 304 && status >= 200) {
response.setChunked(true);
}
answer.pipeTo(response).onFailure(failure -> response.reset());
return;
}
Buffer held = Buffer.buffer();
boolean[] streaming = {false};
answer.handler(chunk -> {
Buffer out = chunk;
if (!streaming[0]) {
held.appendBuffer(chunk);
if (held.length() <= MAX_REWRITTEN) {
return;
}
streaming[0] = true;
response.setChunked(true);
out = held;
}
response.write(out);
if (response.writeQueueFull()) {
answer.pause();
response.drainHandler(drained -> answer.resume());
}
});
answer.exceptionHandler(failure -> response.reset());
answer.endHandler(ended -> {
if (streaming[0]) {
response.end();
} else {
// Byte for byte: the links are ASCII, and every other byte goes back as it came.
response.end(Buffer.buffer(rewrite(held.toString(StandardCharsets.ISO_8859_1), rewrites)
.getBytes(StandardCharsets.ISO_8859_1)));
}
});
answer.resume();
}
static boolean rewritable(String contentType) {
if (contentType == null) {
return false;
}
String type = contentType.toLowerCase(Locale.ROOT);
return TEXT_TYPES.stream().anyMatch(type::startsWith);
}
static String rewrite(String text, Map<String, String> rewrites) {
String result = text;
for (Map.Entry<String, String> rewrite : rewrites.entrySet()) {
result = result.replace(rewrite.getKey(), rewrite.getValue());
}
return result;
}
private static void refuse(HttpServerRequest request, int status, String message) {
request.resume();
HttpServerResponse response = request.response();
if (response.ended()) {
return;
}
response.setStatusCode(status).putHeader("content-type", "text/html; charset=utf-8")
.end(Html.page("Application UI", List.of("<p>" + Html.escape(message) + "</p>")));
}
}
@@ -7,6 +7,7 @@ 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.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.emr.model.EmrCluster;
@@ -15,8 +16,10 @@ import io.floci.aws.services.emrserverless.EmrServerlessSparkRunner;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
@@ -24,14 +27,25 @@ import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 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}.
* In the docker runner mode, an on-cluster UI that runs on the cluster's primary node, its ResourceManager, an
* application master through it, its MapReduce JobHistory server, or the NodeManager of a primary node that works,
* opens for real through {@link EmrAppUiProxy}, on a host of its own under {@link #UI_HOST}, as AWS's are under
* "emrappui-prod.us-east-1.amazonaws.com" (Management Guide, "View Amazon EMR application history"). Floci keeps a
* persistent application UI's record, but serves no Spark History Server, Tez UI or YARN timeline server: a link to
* one of those, and to any on-cluster UI elsewhere, opens a page of Floci's own about the cluster
* ({@link EmrAppUiController}). Either link is valid for {@link #VALIDITY}: the page's is signed with a key of this
* process, and a proxied interface's host holds a secret this process gave it.
*/
@ApplicationScoped
public class EmrAppUiService {
@@ -50,6 +64,23 @@ public class EmrAppUiService {
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";
/** The label under Floci's host name an on-cluster UI's own host is in. */
static final String UI_HOST = "emrappui";
// A link's secret: 26 characters of base32, 130 random bits, in lower case, as a host name is read without case.
private static final int SECRET_LENGTH = 26;
private static final String BASE32 = "abcdefghijklmnopqrstuvwxyz234567";
static final String RESOURCE_MANAGER = "ResourceManager";
static final String APPLICATION_MASTER = "ApplicationMaster";
static final String JOB_HISTORY_SERVER = "JobHistoryServer";
// No source gives AWS's wording for these; they are Floci's.
static final String NO_SUCH_INTERFACE = "This link opens none of the cluster's interfaces on that port.";
static final String CLUSTER_ENDED = "Cluster %s is no longer running, and its on-cluster application UIs are"
+ " there only while it is RUNNING or WAITING.";
// How long a port found on the cluster's primary node is used before it is asked for again.
private static final Duration ENDPOINT_RECHECK = Duration.ofSeconds(10);
static final String NOT_READY = "The cluster's primary node is not running yet: it starts once a step runs, or a"
+ " link to one of its interfaces is asked for. Try again in a moment.";
private static final Pattern APPLICATION_ID = Pattern.compile("application_(\\d+_\\d+)");
private final AccountAwareStorageBackend<EmrPersistentAppUi> store;
private final EmrService clusters;
@@ -57,6 +88,9 @@ public class EmrAppUiService {
private final Clock clock;
private final String baseUrl;
private final LinkSigner signer;
// The links to proxied interfaces this process has given, by their secret, until they expire.
private final Map<String, Grant> grants = new ConcurrentHashMap<>();
private final SecureRandom random = new SecureRandom();
@Inject
public EmrAppUiService(StorageFactory storageFactory, EmrService clusters, RegionResolver regionResolver,
@@ -179,11 +213,17 @@ public class EmrAppUiService {
return url(appUi.getClusterId(), type != null ? type : appUi.getTypes().get(0), applicationId);
}
/** A presigned URL, and whether what it opens is ready: none for a dry run. */
public record Presigned(String url, boolean ready) {
}
/**
* 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.
* the cluster runs or waits; for a dry run the request is checked and no URL is made. One Floci proxies is ready
* once the cluster's primary node is: until then, as on a cluster no step has run on yet, the node starts, and the
* URL is not ready, as "Used to determine if the presigned URL is ready" says of {@code PresignedURLReady}.
*/
public String onClusterUrl(String clusterId, String type, String applicationId, boolean dryRun) {
public Presigned onClusterUrl(String clusterId, String type, String applicationId, boolean dryRun) {
List<String> violations = new ArrayList<>();
if (clusterId == null) {
violations.add(SmithyValidationErrors.notNull("clusterId"));
@@ -198,7 +238,147 @@ public class EmrAppUiService {
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);
if (dryRun) {
return new Presigned(null, true);
}
String asked = type != null ? type : RESOURCE_MANAGER;
Optional<EmrService.WebInterfaces> served = clusters.webInterfaces(cluster);
Integer port = served.map(interfaces -> portOf(asked, interfaces)).orElse(null);
if (port == null) {
return new Presigned(url(clusterId, asked, applicationId), true);
}
Instant now = clock.instant();
grants.values().removeIf(grant -> !now.isBefore(grant.expires()));
String secret = secret();
grants.put(secret, new Grant(regionResolver.getAccountId(), regionResolver.getRegion(), clusterId,
served.get().primaryHost(), served.get().ports(), now.plus(VALIDITY), new ConcurrentHashMap<>()));
boolean ready = clusters.webInterface(clusterId, port).isPresent();
if (!ready) {
clusters.startPrimaryNode(clusterId);
}
URI base = URI.create(baseUrl);
return new Presigned(base.getScheme() + "://" + secret + "-" + port + "." + UI_HOST + "."
+ base.getRawAuthority() + landing(asked, applicationId), ready);
}
// The interface's port on the primary node, where Floci serves it: an application master's UI through the
// ResourceManager's web proxy.
private static Integer portOf(String type, EmrService.WebInterfaces interfaces) {
int port = switch (type) {
case RESOURCE_MANAGER, APPLICATION_MASTER -> EmrClusterStorage.RESOURCE_MANAGER_WEB_PORT;
case JOB_HISTORY_SERVER -> EmrServerlessSparkRunner.JOB_HISTORY_WEB_PORT;
default -> 0;
};
return interfaces.ports().contains(port) ? port : null;
}
// Where the link lands: the interface's page of the application asked for, else its first. A MapReduce job's id
// is its application's, job_ in place of application_.
private static String landing(String type, String applicationId) {
String application = applicationId != null ? pathSegment(applicationId) : null;
return switch (type) {
case APPLICATION_MASTER -> application != null ? "/proxy/" + application + "/" : "/cluster/apps/RUNNING";
case JOB_HISTORY_SERVER -> {
Matcher matcher = applicationId != null ? APPLICATION_ID.matcher(applicationId) : null;
yield matcher != null && matcher.matches() ? "/jobhistory/job/job_" + matcher.group(1) : "/jobhistory";
}
default -> application != null ? "/cluster/app/" + application : "/cluster";
};
}
private static String pathSegment(String value) {
return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20");
}
private String secret() {
StringBuilder secret = new StringBuilder(SECRET_LENGTH);
for (int i = 0; i < SECRET_LENGTH; i++) {
secret.append(BASE32.charAt(random.nextInt(BASE32.length())));
}
return secret.toString();
}
/**
* A link to a proxied interface: the cluster's, as the account in the Region; its primary node's name and web
* interfaces' ports; when it expires; and where Floci reaches each port, once found.
*/
private record Grant(String accountId, String region, String clusterId, String primaryHost, Set<Integer> ports,
Instant expires, Map<Integer, Found> endpoints) {
}
// Where Floci found a port of the cluster's own primary node's container, and when, which is asked again once
// ENDPOINT_RECHECK has passed: a port the node no longer has may be another container's by then.
private record Found(ContainerLifecycleManager.EndpointInfo endpoint, Instant at) {
}
/**
* Where a request to a proxied interface's host goes: the interface's address on the primary node, and each link
* to one of the node's interfaces its pages hold, by the node's name, as the browser reaches that interface; else
* why it is refused, with its HTTP status.
*/
public record UiRoute(String host, int port, Map<String, String> rewrites, Runnable unreachable, int status,
String refusal) {
static UiRoute refused(int status, String refusal) {
return new UiRoute(null, 0, Map.of(), () -> { }, status, refusal);
}
}
/**
* The route of a request whose {@code Host} is {@code hostHeader}, over {@code scheme}; null where the host is not
* a proxied interface's, {@code <secret>-<port>.}{@value #UI_HOST}{@code .<Floci's host>}.
*/
public UiRoute route(String hostHeader, String scheme) {
String host = hostHeader.toLowerCase(Locale.ROOT);
int dot = host.indexOf('.');
int dash = dot > 0 ? host.lastIndexOf('-', dot) : -1;
if (dash != SECRET_LENGTH || !host.startsWith(UI_HOST + ".", dot + 1)) {
return null;
}
String secret = host.substring(0, dash);
int port;
try {
port = Integer.parseInt(host.substring(dash + 1, dot));
} catch (NumberFormatException e) {
return null;
}
Grant grant = grants.get(secret);
if (grant == null || !clock.instant().isBefore(grant.expires())) {
return UiRoute.refused(403, EmrAppUiController.INVALID);
}
if (!grant.ports().contains(port)) {
return UiRoute.refused(404, NO_SUCH_INTERFACE);
}
// The interface is there only while its cluster runs or waits: once it ends, its node's ports are no longer
// its own.
EmrCluster cluster = RequestScopes.callAs(grant.accountId(), grant.region(),
() -> clusters.findDescribedCluster(grant.clusterId()).orElse(null));
if (cluster == null || !EmrClusterLifecycle.RUNNING.equals(cluster.getState())
&& !EmrClusterLifecycle.WAITING.equals(cluster.getState())) {
return UiRoute.refused(404, String.format(CLUSTER_ENDED, grant.clusterId()));
}
Instant now = clock.instant();
Found found = grant.endpoints().get(port);
if (found == null || !now.isBefore(found.at().plus(ENDPOINT_RECHECK))) {
ContainerLifecycleManager.EndpointInfo endpoint = RequestScopes.callAs(grant.accountId(), grant.region(),
() -> clusters.webInterface(grant.clusterId(), port)).orElse(null);
if (endpoint == null) {
grant.endpoints().remove(port);
return UiRoute.refused(503, NOT_READY);
}
found = new Found(endpoint, now);
grant.endpoints().put(port, found);
}
// The node's daemons write links to one another by the node's name, which the browser reaches as each
// interface's own host, under this one's Floci host and port.
String rest = host.substring(dot);
Map<String, String> rewrites = new LinkedHashMap<>();
for (int other : grant.ports()) {
rewrites.put("http://" + grant.primaryHost() + ":" + other, scheme + "://" + secret + "-" + other + rest);
}
Found routed = found;
return new UiRoute(found.endpoint().host(), found.endpoint().port(), rewrites,
() -> grant.endpoints().remove(port, routed), 0, null);
}
/** What a page link names: an interface of a cluster, for an application or none, and when it expires. */
@@ -131,9 +131,15 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
// The nodes being decommissioned, one host name to a line, as HDFS and YARN read them on the primary node.
private static final String DFS_EXCLUDE = HDFS_CONF + "/dfs.exclude";
private static final String YARN_EXCLUDE = HDFS_CONF + "/yarn.exclude";
/** The ResourceManager's web port, "YARN ResourceManager | http://master-public-dns-name:8088/". */
static final int RESOURCE_MANAGER_WEB_PORT = 8088;
/** A NodeManager's web port, "YARN NodeManager | http://coretask-public-dns-name:8042/". */
static final int NODE_MANAGER_WEB_PORT = 8042;
// The ResourceManager's cluster metrics on its web port, which say when the NodeManager has registered.
private static final String RESOURCE_MANAGER_METRICS = "http://" + BIND + ":8088/ws/v1/cluster/metrics";
private static final String RESOURCE_MANAGER_NODES = "http://" + BIND + ":8088/ws/v1/cluster/nodes?states=";
private static final String RESOURCE_MANAGER_METRICS = "http://" + BIND + ":" + RESOURCE_MANAGER_WEB_PORT
+ "/ws/v1/cluster/metrics";
private static final String RESOURCE_MANAGER_NODES = "http://" + BIND + ":" + RESOURCE_MANAGER_WEB_PORT
+ "/ws/v1/cluster/nodes?states=";
// The MapReduce JobHistory server's information on its web port, which says it has started.
private static final String JOB_HISTORY_INFO = "http://" + BIND + ":"
+ EmrServerlessSparkRunner.JOB_HISTORY_WEB_PORT + "/ws/v1/history/info";
@@ -1298,6 +1304,15 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
spec.withLinkLocalIp(address);
}
}
if (yarn != null && !shared) {
// Its web interfaces, which Floci's application UI links reach, published on the host's loopback interface
// alone, as Floci on the host reaches them there, and they take no credentials.
spec.withLoopbackPortBinding(RESOURCE_MANAGER_WEB_PORT, 0)
.withLoopbackPortBinding(EmrServerlessSparkRunner.JOB_HISTORY_WEB_PORT, 0);
if (yarn.primaryWorks()) {
spec.withLoopbackPortBinding(NODE_MANAGER_WEB_PORT, 0);
}
}
if (yarn != null) {
spec.withEnv(YARN_MEMORY_VARIABLE, String.valueOf(yarn.memoryMb()))
.withEnv(YARN_VCORES_VARIABLE, String.valueOf(yarn.vcores()))
@@ -1430,6 +1445,33 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
return null;
}
/**
* Where Floci reaches a web interface's port on the cluster's primary node, once the node is ready: Floci on the
* host at the port Docker published for it on the host's loopback interface; Floci in a container of its own at
* the node's address on the cluster's network, which its container joins, as the node's daemons listen there
* alone (see BIND_SETUP).
*/
@Override
public Optional<ContainerLifecycleManager.EndpointInfo> webInterface(String clusterId, int port) {
String name = hdfsName(clusterId);
try {
if (lifecycleManager.probeContainer(name) != ContainerLiveness.RUNNING
|| ContainerExec.run(lifecycleManager.getDockerClient(), name,
new String[]{"test", "-f", HDFS_READY}, 10).exitCode() != 0) {
return Optional.empty();
}
if (currentContainer.resolveContainerId().isPresent() && !attachFloci(name)) {
return Optional.empty();
}
return Optional.of(lifecycleManager.resolveEndpoint(name, port, name));
} catch (RuntimeException e) {
// Stopped since it was looked at, or started before its ports were published.
LOG.debugv(e, "Port {0} of the primary node of EMR cluster {1} is not reachable: {2}", port, clusterId,
e.getMessage());
return Optional.empty();
}
}
// Whether the container became ready by the deadline, false when it stopped first, or the step did, or a teardown
// has run since it asked; a failure to become ready in time is thrown.
private boolean awaitReady(String clusterId, String containerId, long deadline, long teardown,
@@ -898,8 +898,8 @@ public class EmrHandler {
private Response handleGetPersistentAppUiPresignedUrl(JsonNode request) {
bool(request, "AuthProxyCall");
string(request, "ExecutionRoleArn");
return presignedUrl(appUis.persistentUrl(string(request, "PersistentAppUIId"),
string(request, "PersistentAppUIType"), string(request, "ApplicationId")));
return presignedUrl(new EmrAppUiService.Presigned(appUis.persistentUrl(string(request, "PersistentAppUIId"),
string(request, "PersistentAppUIType"), string(request, "ApplicationId")), true));
}
private Response handleGetOnClusterAppUiPresignedUrl(JsonNode request) {
@@ -909,11 +909,11 @@ public class EmrHandler {
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) {
// A presigned URL's answer: whether it is ready, and the URL, none for a dry run.
private Response presignedUrl(EmrAppUiService.Presigned presigned) {
ObjectNode response = objectMapper.createObjectNode();
response.put("PresignedURLReady", true);
putIfSet(response, "PresignedURL", url);
response.put("PresignedURLReady", presigned.ready());
putIfSet(response, "PresignedURL", presigned.url());
return Response.ok(response).build();
}
@@ -23,6 +23,7 @@ import io.floci.aws.core.common.SparkConnectEndpoint;
import io.floci.aws.core.common.SparkConnectProxy;
import io.floci.aws.core.common.SparkConnectTargets;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
@@ -114,6 +115,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
private static final int SESSION_PASSWORD_BYTES = 24;
// No source gives how long GetClusterSessionCredentials' credentials last; Floci's expire in an hour.
private static final Duration SESSION_CREDENTIALS_VALIDITY = Duration.ofHours(1);
// How long the command that starts a cluster's primary node for its application UIs may run: it runs nothing.
private static final Duration PRIMARY_NODE_START = Duration.ofMinutes(5);
// AWS's answer to a change on a terminated cluster, for AddJobFlowSteps and ModifyInstanceFleet; Floci
// gives it to AddInstanceGroups and AddInstanceFleet too, for one shutting down.
private static final String JOB_FLOW_SHUT_DOWN =
@@ -171,6 +174,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
private final Executor stepExecutor;
// The commands other EMR services run on a cluster ({@link #runOnCluster}), by run id, with their cluster's id.
private final Map<String, String> clusterRuns = new HashMap<>();
// The clusters whose primary node an application UI link is starting, by account and id, and how many it has.
private final Set<String> primaryNodeStarts = ConcurrentHashMap.newKeySet();
private final AtomicLong primaryNodeStartCount = new AtomicLong();
// The Spark Connect servers of the sessions, in the docker runner mode, and the tokens given for every session.
private final SparkConnectServers sessionServers;
private final SessionOwner sessionOwner = new SessionOwner();
@@ -962,6 +968,68 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
return e.getMessage() != null ? e.getMessage() : e.toString();
}
/**
* The web interfaces of a cluster's primary node an on-cluster application UI link opens, by port, and the name
* its daemons write into the links of their pages, the node's private DNS name.
*/
public record WebInterfaces(String primaryHost, Set<Integer> ports) {
}
/**
* The web interfaces Floci serves of a cluster's primary node, where it runs YARN there, in the docker runner
* mode: its ResourceManager, its MapReduce JobHistory server, and, where the node works, its NodeManager; empty
* elsewhere.
*/
public Optional<WebInterfaces> webInterfaces(EmrCluster cluster) {
if (!runsOnClusters() || !runsYarn(cluster)) {
return Optional.empty();
}
Set<Integer> ports = new LinkedHashSet<>(List.of(EmrClusterStorage.RESOURCE_MANAGER_WEB_PORT,
EmrServerlessSparkRunner.JOB_HISTORY_WEB_PORT));
if (yarnOf(cluster).primaryWorks()) {
ports.add(EmrClusterStorage.NODE_MANAGER_WEB_PORT);
}
return Optional.of(new WebInterfaces(masterPrivateDnsName(cluster), Set.copyOf(ports)));
}
/** Where Floci reaches a web interface's port on the cluster's primary node, once the node is ready. */
public Optional<ContainerLifecycleManager.EndpointInfo> webInterface(String clusterId, int port) {
return clusterStorage == null ? Optional.empty() : clusterStorage.webInterface(clusterId, port);
}
/**
* Starts the cluster's primary node, its HDFS and YARN, as its first step would, by running nothing on it
* ({@link #runOnCluster}), unless such a start is under way already: an application UI link may be asked for
* before any step has run.
*/
public void startPrimaryNode(String clusterId) {
String key = regionResolver.getAccountId() + "/" + clusterId;
if (!primaryNodeStarts.add(key)) {
return;
}
runOnCluster(clusterId, "ui-" + clusterId + "-" + primaryNodeStartCount.incrementAndGet(), null,
List.of("true"), Map.of(), PRIMARY_NODE_START, new ClusterRun() {
@Override
public void started() {
// The node is ready before the command's container starts.
}
@Override
public void ended(SparkJobRunner.Outcome outcome) {
primaryNodeStarts.remove(key);
if (outcome.failure() != null) {
LOG.warnv("Could not start the primary node of EMR cluster {0} for its application"
+ " UIs: {1}", clusterId, outcome.failure());
}
}
@Override
public boolean cancelled() {
return false;
}
});
}
/** Stops a command {@link #runOnCluster} runs, which then ends as stopped. */
public void stopOnCluster(String runId) {
if (sparkRunner != null) {
@@ -3909,15 +3909,30 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider {
return encoded.toString();
}
// An upload over the limit is refused from its Base64 length, before it is decoded, so it takes no more memory
// than it came in.
private void extractZipCode(LambdaFunction fn, String zipFileBase64, String region) {
if (decodedLength(zipFileBase64) > ZipExtractor.DIRECT_UPLOAD_MAX_COMPRESSED_BYTES) {
throw tooLargeUpload();
}
byte[] zipBytes = Base64.getDecoder().decode(zipFileBase64);
if (zipBytes.length > ZipExtractor.DIRECT_UPLOAD_MAX_COMPRESSED_BYTES) {
throw new AwsException("RequestEntityTooLargeException",
"Request must be smaller than 52428800 bytes.", 413);
throw tooLargeUpload();
}
extractZipCodePackage(fn, DeploymentPackage.of(zipBytes), region);
}
// The bytes Base64 text decodes to: three for every four characters, its padding, which may be left out, aside.
static long decodedLength(String base64) {
int padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
return (long) (base64.length() - padding) * 3 / 4;
}
private static AwsException tooLargeUpload() {
return new AwsException("RequestEntityTooLargeException", "Request must be smaller than 52428800 bytes.",
413);
}
private void extractZipCodePackage(LambdaFunction fn, DeploymentPackage zip, String region) {
Path codePath = codeStore.getCodePath(ownerAccount(fn), region, fn.getFunctionName());
try {
@@ -0,0 +1,173 @@
package io.floci.aws.services.emr;
import io.floci.aws.services.emrserverless.EmrServerlessSparkRunner;
import io.floci.aws.testing.DockerAvailability;
import io.floci.aws.testing.EmrRequests;
import io.floci.aws.testing.PartitionCleanup;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import java.util.function.BooleanSupplier;
import static io.floci.aws.testing.EmrRequests.awaitStep;
import static io.floci.aws.testing.EmrRequests.emr;
import static io.floci.aws.testing.EmrRequests.terminateClusterAndAwaitCleanup;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* On-cluster application UIs open for real: on an emr-7.5.0 cluster no step has run on yet, the ResourceManager's link
* starts the primary node and is ready once the node is, then opens the ResourceManager through Floci on a host of its
* own; after a MapReduce step, the ResourceManager's answer links to the job on the JobHistory server's own host, which
* opens it, as the JobHistory server's link does.
*
* <p>A nightly check: the cluster's image, its HDFS and YARN, and a MapReduce job take minutes and gigabytes.
*/
@QuarkusTest
@TestProfile(EmrAppUiNightlyIntegrationTest.Profile.class)
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
// Bounded waits: the cluster's image of up to twenty minutes, its HDFS and YARN, and a MapReduce step; the Nightly
// checks job's timeout counts the 30.
@Timeout(value = 30, unit = TimeUnit.MINUTES)
class EmrAppUiNightlyIntegrationTest {
/** Clusters run their steps in containers, and Floci listens on a fixed port, its links'. */
public static final class Profile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of(
"floci.services.emr.runner-mode", "docker",
"quarkus.http.test-port", String.valueOf(PORT),
"floci.port", String.valueOf(PORT),
"floci.base-url", "http://localhost:" + PORT);
}
}
private static final int PORT = 4598;
private static final String EXAMPLES = "/usr/lib/hadoop-mapreduce/hadoop-mapreduce-examples.jar";
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Inject
EmrService emrService;
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void theResourceManagerAndTheJobHistoryServerOpenThroughTheirLinks() throws InterruptedException {
// Enabled, the check needs Docker: without a daemon it fails rather than pass having run nothing.
assertTrue(DockerAvailability.isAvailable(), "the nightly check needs a Docker daemon");
String clusterId = emr("RunJobFlow", "{\"Name\":\"app-uis\",\"ReleaseLabel\":\"emr-7.5.0\","
+ "\"Applications\":[{\"Name\":\"Hadoop\"},{\"Name\":\"Spark\"}],"
+ "\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true,\"InstanceGroups\":[{\"Name\":\"primary\","
+ "\"InstanceRole\":\"MASTER\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1}]}}")
.then().statusCode(200).extract().jsonPath().getString("JobFlowId");
cleanup.register(() -> terminateClusterAndAwaitCleanup(clusterId, emrService));
await(() -> emr("DescribeCluster", "{\"ClusterId\":\"" + clusterId + "\"}").jsonPath()
.getString("Cluster.Status.State").equals("WAITING"), Duration.ofMinutes(5));
// No step has run: the link starts the primary node, and is ready once the node is.
assertFalse(link(clusterId, "ResourceManager", null).getBoolean("PresignedURLReady"));
String resourceManager = readyLink(clusterId, "ResourceManager", null);
Response cluster = open(resourceManager);
assertEquals(200, cluster.statusCode(), cluster.asString());
assertTrue(cluster.asString().contains("All Applications"), cluster.asString());
String step = EmrRequests.addStep(clusterId, "pi", "command-runner.jar", "hadoop", "jar", EXAMPLES, "pi",
"1", "10");
assertEquals("COMPLETED", awaitStep(clusterId, step).jsonPath().getString("Step.Status.State"));
// The ResourceManager's REST answer, through its link's host: the links it holds to the node's interfaces are
// their own hosts', under the same link.
URI linked = URI.create(resourceManager);
String secret = linked.getHost().substring(0, 26);
String origin = "http://" + secret + "-%d.emrappui.localhost:" + PORT;
Response answer = open(linked.getScheme() + "://" + linked.getRawAuthority() + "/ws/v1/cluster/apps");
JsonPath apps = answer.jsonPath();
String job = "apps.app.find { it.applicationType == 'MAPREDUCE' }";
String applicationId = apps.getString(job + ".id");
String jobPath = "/jobhistory/job/" + applicationId.replace("application_", "job_");
// The job's application master's logs, on the NodeManager of the primary node, which works.
String amLogs = apps.getString(job + ".amContainerLogs");
assertTrue(amLogs.startsWith(String.format(origin, EmrClusterStorage.NODE_MANAGER_WEB_PORT)), amLogs);
Response logs = open(amLogs);
assertEquals(200, logs.statusCode(), logs.asString());
assertTrue(logs.asString().contains("syslog"), logs.asString());
// Its tracking URL, the ResourceManager's proxy, sends the browser on to the job's page on the JobHistory
// server's own host.
String tracking = apps.getString(job + ".trackingUrl");
assertEquals(String.format(origin, EmrClusterStorage.RESOURCE_MANAGER_WEB_PORT) + "/proxy/" + applicationId
+ "/", tracking);
Response proxied = open(tracking);
assertTrue(proxied.statusCode() / 100 == 3, proxied.statusCode() + " " + proxied.asString());
String history = proxied.getHeader("Location");
assertTrue(history.startsWith(String.format(origin, EmrServerlessSparkRunner.JOB_HISTORY_WEB_PORT) + jobPath),
history);
Response page = open(history);
assertEquals(200, page.statusCode(), page.asString());
assertTrue(page.asString().contains("QuasiMonteCarlo"), page.asString());
// The JobHistory server's own link lands on the job.
String jobLink = readyLink(clusterId, "JobHistoryServer", applicationId);
assertEquals(jobPath, URI.create(jobLink).getPath());
assertTrue(open(jobLink).asString().contains("QuasiMonteCarlo"));
}
private static JsonPath link(String clusterId, String type, String applicationId) {
return emr("GetOnClusterAppUIPresignedURL", "{\"ClusterId\":\"" + clusterId + "\",\"OnClusterAppUIType\":\""
+ type + "\"" + (applicationId != null ? ",\"ApplicationId\":\"" + applicationId + "\"" : "") + "}")
.then().statusCode(200).extract().jsonPath();
}
// The link once it is ready: the primary node's image, HDFS and YARN start first.
private static String readyLink(String clusterId, String type, String applicationId) {
String[] url = new String[1];
await(() -> {
JsonPath answer = link(clusterId, type, applicationId);
url[0] = answer.getString("PresignedURL");
return answer.getBoolean("PresignedURLReady");
}, Duration.ofMinutes(20));
return url[0];
}
// A browser's request to the link: to Floci, under the link's host.
private static Response open(String url) {
URI uri = URI.create(url);
return given().header("Host", uri.getRawAuthority()).header("Accept", "application/json, text/html")
.redirects().follow(false)
.get("http://localhost:" + PORT + uri.getRawPath()
+ (uri.getRawQuery() != null ? "?" + uri.getRawQuery() : ""));
}
private static void await(BooleanSupplier condition, Duration limit) {
long deadline = System.nanoTime() + limit.toNanos();
while (!condition.getAsBoolean()) {
if (System.nanoTime() - deadline > 0) {
fail("not reached within " + limit);
}
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(2));
}
}
}
@@ -0,0 +1,236 @@
package io.floci.aws.services.emr;
import io.floci.aws.core.common.ServiceConfigAccess;
import io.vertx.core.Future;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientResponse;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.http.RequestOptions;
import io.vertx.core.net.SocketAddress;
import io.vertx.ext.web.Router;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Requests to an on-cluster application UI's own host through {@link EmrAppUiProxy}: a server stands in for the
* interface on the cluster's primary node, and a route for what the link's host resolves to.
*/
class EmrAppUiProxyTest {
private static final String HOST = "s".repeat(26) + "-8088.emrappui.localhost";
private static final String NODE_ORIGIN = "http://ip-10-0-0-1.ec2.internal:19888";
private static final String BROWSER_ORIGIN = "http://" + "s".repeat(26) + "-19888.emrappui.localhost:4566";
private static final Map<String, String> REWRITES = Map.of(NODE_ORIGIN, BROWSER_ORIGIN);
private final EmrAppUiService appUis = mock(EmrAppUiService.class);
private final AtomicReference<MultiMap> interfaceSaw = new AtomicReference<>();
private final AtomicReference<String> interfaceSawUri = new AtomicReference<>();
private final AtomicReference<Buffer> interfaceSawBody = new AtomicReference<>();
// What the interface answers each request with.
private volatile Answer answer = (response, body) -> response.end();
private Vertx vertx;
private HttpServer floci;
private HttpServer node;
private HttpClient client;
/** How the stand-in interface answers. */
private interface Answer {
void answer(HttpServerResponse response, Buffer body);
}
@BeforeEach
void setUp() throws Exception {
vertx = Vertx.vertx();
node = await(vertx.createHttpServer().requestHandler(request -> request.body().onSuccess(body -> {
interfaceSaw.set(MultiMap.caseInsensitiveMultiMap().addAll(request.headers()));
interfaceSawUri.set(request.uri());
interfaceSawBody.set(body);
answer.answer(request.response(), body);
})).listen(0, "127.0.0.1"));
ServiceConfigAccess services = mock(ServiceConfigAccess.class);
when(services.isEnabled("emr")).thenReturn(true);
Router router = Router.router(vertx);
// An interface that sends nothing for two seconds is given up.
new EmrAppUiProxy(appUis, services, vertx, Duration.ofSeconds(2)).register(router);
router.route().handler(context -> context.response().setStatusCode(404).end("not a link"));
floci = await(vertx.createHttpServer().requestHandler(router).listen(0, "127.0.0.1"));
client = vertx.createHttpClient();
}
@AfterEach
void tearDown() throws Exception {
await(vertx.close());
}
@Test
void aPageComesBackWithItsLinksToTheNodesInterfacesMadeTheBrowsers() throws Exception {
routeTo(node.actualPort());
answer = (response, body) -> response.putHeader("content-type", "text/html; charset=utf-8")
.end("<a href=\"" + NODE_ORIGIN + "/jobhistory/job/job_1_0001\">History</a> é");
Answered response = send(HttpMethod.GET, "/cluster/app/application_1_0001?a=b", null);
assertEquals(200, response.statusCode());
assertEquals("<a href=\"" + BROWSER_ORIGIN + "/jobhistory/job/job_1_0001\">History</a> é",
response.body().toString());
assertEquals("/cluster/app/application_1_0001?a=b", interfaceSawUri.get());
// The interface is asked under the browser's host, so the links it writes itself are the browser's.
assertEquals(HOST + ":4566", interfaceSaw.get().get("host"));
assertEquals("identity", interfaceSaw.get().get("accept-encoding"));
}
@Test
void aRedirectToAnotherInterfaceGoesToItsOwnHost() throws Exception {
routeTo(node.actualPort());
answer = (response, body) -> response.setStatusCode(302)
.putHeader("location", NODE_ORIGIN + "/jobhistory/job/job_1_0001").end();
Answered response = send(HttpMethod.GET, "/proxy/application_1_0001/", null);
assertEquals(302, response.statusCode());
assertEquals(BROWSER_ORIGIN + "/jobhistory/job/job_1_0001", response.getHeader("location"));
}
@Test
void whatIsNotTextGoesBackAsItCameAndARequestsBodyGoesOn() throws Exception {
routeTo(node.actualPort());
byte[] image = Buffer.buffer(NODE_ORIGIN).appendByte((byte) 0).appendByte((byte) 0xff).getBytes();
answer = (response, body) -> response.putHeader("content-type", "image/png").end(Buffer.buffer(image));
Answered response = send(HttpMethod.POST, "/ws/v1/cluster/apps/new-application", "{\"a\":1}");
assertArrayEquals(image, response.body().getBytes());
assertEquals(String.valueOf(image.length), response.getHeader("content-length"));
assertEquals("{\"a\":1}", interfaceSawBody.get().toString());
}
@Test
void anAnswerStreamedWithNoLengthGoesOnInChunksAsItCame() throws Exception {
routeTo(node.actualPort());
answer = (response, body) -> response.putHeader("content-type", "application/octet-stream").setChunked(true)
.write("first part, ").compose(written -> response.end("then the rest"));
Answered response = send(HttpMethod.GET, "/node/containerlogs/container_1/hadoop/stderr", null);
assertEquals(200, response.statusCode());
assertEquals("first part, then the rest", response.body().toString());
}
@Test
void aLargeUploadGoesOnAsItArrives() throws Exception {
routeTo(node.actualPort());
String upload = "u".repeat(9 * 1024 * 1024);
Answered response = send(HttpMethod.PUT, "/ws/v1/cluster/apps/application_1_0001/state", upload);
assertEquals(200, response.statusCode());
assertEquals(upload.length(), interfaceSawBody.get().length());
}
@Test
void anInterfaceThatStopsAnsweringIsGivenUp() throws Exception {
routeTo(node.actualPort());
// It takes the request and sends nothing.
answer = (response, body) -> { };
Answered response = send(HttpMethod.GET, "/cluster", null);
assertEquals(502, response.statusCode());
}
@Test
void anAnswerTooLargeToHoldGoesOnAsItCame() throws Exception {
routeTo(node.actualPort());
String large = NODE_ORIGIN + "x".repeat(9 * 1024 * 1024);
answer = (response, body) -> response.putHeader("content-type", "text/plain").setChunked(true).end(large);
Answered response = send(HttpMethod.GET, "/logs/yarn.log", null);
assertEquals(large, response.body().toString());
}
@Test
void aRefusedLinkIsAnsweredWithAPageSayingWhy() throws Exception {
when(appUis.route(eq(HOST + ":4566"), anyString()))
.thenReturn(EmrAppUiService.UiRoute.refused(403, EmrAppUiController.INVALID));
Answered response = send(HttpMethod.GET, "/cluster", null);
assertEquals(403, response.statusCode());
assertTrue(response.body().toString().contains("not valid, or its hour has passed"));
}
@Test
void anInterfaceThatDoesNotAnswerIsABadGatewayAndForgotten() throws Exception {
int closed = node.actualPort();
await(node.close());
AtomicBoolean forgotten = new AtomicBoolean();
when(appUis.route(eq(HOST + ":4566"), anyString())).thenReturn(new EmrAppUiService.UiRoute("127.0.0.1",
closed, REWRITES, () -> forgotten.set(true), 0, null));
Answered response = send(HttpMethod.GET, "/cluster", null);
assertEquals(502, response.statusCode());
assertTrue(forgotten.get());
}
@Test
void aHostThatIsNoLinksGoesOnToTheRestOfFloci() throws Exception {
when(appUis.route(eq(HOST + ":4566"), anyString())).thenReturn(null);
Answered response = send(HttpMethod.GET, "/", null);
assertEquals(404, response.statusCode());
assertEquals("not a link", response.body().toString());
}
private void routeTo(int port) {
when(appUis.route(eq(HOST + ":4566"), eq("http"))).thenReturn(new EmrAppUiService.UiRoute("127.0.0.1", port,
REWRITES, () -> { }, 0, null));
}
/** An answer through the proxy, its body read as it came. */
private record Answered(HttpClientResponse response, Buffer body) {
int statusCode() {
return response.statusCode();
}
String getHeader(String name) {
return response.getHeader(name);
}
}
private Answered send(HttpMethod method, String uri, String body) throws Exception {
RequestOptions options = new RequestOptions().setMethod(method)
.setServer(SocketAddress.inetSocketAddress(floci.actualPort(), "127.0.0.1"))
.setHost(HOST).setPort(4566).setURI(uri);
return await(client.request(options).compose(request -> body == null ? request.send()
: request.send(Buffer.buffer(body)))
.compose(response -> response.body().map(read -> new Answered(response, read))));
}
private static <T> T await(Future<T> future) throws Exception {
return future.toCompletionStage().toCompletableFuture().get(30, TimeUnit.SECONDS);
}
}
@@ -84,6 +84,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
@@ -1326,6 +1327,10 @@ class EmrClusterStorageTest {
verify(spec).withJavaTrustStore();
verify(spec).withEmbeddedDns();
verify(spec).withJoinedNetwork("floci-network");
// Its web interfaces, which Floci's application UI links reach, on the host's loopback interface alone.
verify(spec).withLoopbackPortBinding(EmrClusterStorage.RESOURCE_MANAGER_WEB_PORT, 0);
verify(spec).withLoopbackPortBinding(EmrServerlessSparkRunner.JOB_HISTORY_WEB_PORT, 0);
verify(spec).withLoopbackPortBinding(EmrClusterStorage.NODE_MANAGER_WEB_PORT, 0);
// Its configuration names the primary node, listens where HDFS does and offers what it was given.
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(String.join(" ",
"\"<property><name>yarn.resourcemanager.hostname</name><value>$FLOCI_HDFS_HOST</value></property>\"",
@@ -1403,6 +1408,27 @@ class EmrClusterStorageTest {
assertNull(started.flociEndpoint());
verify(spec, never()).withEnv(eq("FLOCI_YARN_MEMORY_MB"), anyString());
verify(spec, never()).withHostDockerInternalOnLinux();
verify(spec, never()).withLoopbackPortBinding(anyInt(), anyInt());
}
@Test
void aPrimaryNodesWebInterfaceIsReachedOnceTheNodeIsReady() {
ContainerLifecycleManager.EndpointInfo published = new ContainerLifecycleManager.EndpointInfo("localhost",
32801);
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING);
when(lifecycle.resolveEndpoint(hdfsName, EmrClusterStorage.RESOURCE_MANAGER_WEB_PORT, hdfsName))
.thenReturn(published);
when(currentContainer.resolveContainerId()).thenReturn(Optional.empty());
ContainerExecStubs.completeEveryExec(docker, hdfsName, 1L, "", "");
// Starting: its HDFS_READY is not there yet.
assertTrue(storage.webInterface("j-1", EmrClusterStorage.RESOURCE_MANAGER_WEB_PORT).isEmpty());
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
assertEquals(Optional.of(published),
storage.webInterface("j-1", EmrClusterStorage.RESOURCE_MANAGER_WEB_PORT));
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
assertTrue(storage.webInterface("j-1", EmrClusterStorage.RESOURCE_MANAGER_WEB_PORT).isEmpty());
}
@Test
@@ -0,0 +1,198 @@
package io.floci.aws.services.emr;
import io.floci.aws.core.common.LinkSigner;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrPersistentAppUi;
import io.floci.aws.services.emrserverless.EmrServerlessSparkRunner;
import io.floci.aws.services.emrserverless.SparkJobRunner;
import io.floci.aws.services.iam.IamService;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
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.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
/**
* On-cluster application UI links in the docker runner mode ({@link EmrAppUiService}): an interface of the cluster's
* primary node opens on a host of its own, which routes to the node's port, its pages' links to the node's other
* interfaces made the browser's; until the node runs, the link starts it and is not ready.
*/
class EmrOnClusterAppUiTest {
private static final int RESOURCE_MANAGER = EmrClusterStorage.RESOURCE_MANAGER_WEB_PORT;
private static final int JOB_HISTORY = EmrServerlessSparkRunner.JOB_HISTORY_WEB_PORT;
private static final ContainerLifecycleManager.EndpointInfo RESOURCE_MANAGER_ON_HOST =
new ContainerLifecycleManager.EndpointInfo("localhost", 32801);
private final RecordingRunner runner = new RecordingRunner();
private final EmrServiceFixture fixture = EmrServiceFixture.docker(runner, mock(IamService.class));
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 theResourceManagersLinkOpensItOnAHostOfItsOwnWhoseLinksToTheNodesOtherInterfacesAreTheBrowsers() {
fixture.clusterStorage.webInterfaces.put(RESOURCE_MANAGER, RESOURCE_MANAGER_ON_HOST);
EmrCluster cluster = yarnCluster();
EmrAppUiService.Presigned link = appUis.onClusterUrl(cluster.getId(), null, null, false);
assertTrue(link.ready());
URI url = URI.create(link.url());
assertEquals("/cluster", url.getPath());
assertTrue(url.getAuthority().matches("[a-z2-7]{26}-8088\\.emrappui\\.localhost:4566"), link.url());
String secret = url.getHost().substring(0, 26);
EmrAppUiService.UiRoute route = appUis.route(url.getAuthority(), "http");
assertNull(route.refusal());
assertEquals("localhost", route.host());
assertEquals(32801, route.port());
String primary = EmrService.masterPrivateDnsName(cluster);
assertEquals("http://" + secret + "-" + JOB_HISTORY + ".emrappui.localhost:4566",
route.rewrites().get("http://" + primary + ":" + JOB_HISTORY));
assertEquals("http://" + secret + "-" + RESOURCE_MANAGER + ".emrappui.localhost:4566",
route.rewrites().get("http://" + primary + ":" + RESOURCE_MANAGER));
// The NodeManager of a primary node that works, as on a cluster of one node.
assertTrue(route.rewrites().containsKey("http://" + primary + ":" + EmrClusterStorage.NODE_MANAGER_WEB_PORT));
assertEquals(0, fixture.stepThreadsWaiting());
}
@Test
void eachInterfaceLandsOnTheApplicationAskedFor() {
fixture.clusterStorage.webInterfaces.put(RESOURCE_MANAGER, RESOURCE_MANAGER_ON_HOST);
String clusterId = yarnCluster().getId();
String application = "application_1763395200000_0002";
assertEquals("/cluster/app/" + application,
path(appUis.onClusterUrl(clusterId, "ResourceManager", application, false)));
assertEquals("/proxy/" + application + "/",
path(appUis.onClusterUrl(clusterId, "ApplicationMaster", application, false)));
assertEquals("/jobhistory/job/job_1763395200000_0002",
path(appUis.onClusterUrl(clusterId, "JobHistoryServer", application, false)));
assertTrue(appUis.onClusterUrl(clusterId, "JobHistoryServer", null, false).url().contains("-19888."));
}
@Test
void aLinkAskedBeforeThePrimaryNodeRunsStartsItOnceAndIsNotReadyUntilThen() {
String clusterId = yarnCluster().getId();
EmrAppUiService.Presigned first = appUis.onClusterUrl(clusterId, null, null, false);
EmrAppUiService.Presigned second = appUis.onClusterUrl(clusterId, null, null, false);
assertFalse(first.ready());
assertFalse(second.ready());
// One start, its command run as a step's on the cluster, its HDFS and YARN started first.
assertEquals(1, fixture.stepThreadsWaiting());
EmrAppUiService.UiRoute notYet = appUis.route(URI.create(first.url()).getAuthority(), "http");
assertEquals(503, notYet.status());
assertEquals(EmrAppUiService.NOT_READY, notYet.refusal());
fixture.runStepThread();
assertEquals(List.of("true"), runner.jobs.get(0).command());
fixture.clusterStorage.webInterfaces.put(RESOURCE_MANAGER, RESOURCE_MANAGER_ON_HOST);
assertNull(appUis.route(URI.create(first.url()).getAuthority(), "http").refusal());
assertTrue(appUis.onClusterUrl(clusterId, null, null, false).ready());
}
@Test
void aLinkPastItsHourNotThisProcesssOrForAnotherPortIsRefused() {
fixture.clusterStorage.webInterfaces.put(RESOURCE_MANAGER, RESOURCE_MANAGER_ON_HOST);
String authority = URI.create(appUis.onClusterUrl(yarnCluster().getId(), null, null, false).url())
.getAuthority();
String secret = authority.substring(0, 26);
assertEquals(404, appUis.route(secret + "-9870.emrappui.localhost:4566", "http").status());
assertEquals(403, appUis.route("a".repeat(26) + "-8088.emrappui.localhost:4566", "http").status());
// Not a link's host at all, which goes on to the rest of Floci.
assertNull(appUis.route("bucket.emrappui.localhost:4566", "http"));
fixture.clock.advance(EmrAppUiService.VALIDITY);
EmrAppUiService.UiRoute expired = appUis.route(authority, "http");
assertEquals(403, expired.status());
assertEquals(EmrAppUiController.INVALID, expired.refusal());
}
@Test
void aLinkOfAClusterThatHasEndedReachesNothing() {
fixture.clusterStorage.webInterfaces.put(RESOURCE_MANAGER, RESOURCE_MANAGER_ON_HOST);
String clusterId = yarnCluster().getId();
String authority = URI.create(appUis.onClusterUrl(clusterId, null, null, false).url()).getAuthority();
assertNull(appUis.route(authority, "http").refusal());
fixture.service.terminateJobFlows(List.of(clusterId));
EmrAppUiService.UiRoute ended = appUis.route(authority, "http");
// Its node's port, still within the link's hour, may be another container's by then.
assertEquals(404, ended.status());
assertEquals(String.format(EmrAppUiService.CLUSTER_ENDED, clusterId), ended.refusal());
}
@Test
void aPortFoundOnThePrimaryNodeIsAskedForAgainAfterAFewSeconds() {
fixture.clusterStorage.webInterfaces.put(RESOURCE_MANAGER, RESOURCE_MANAGER_ON_HOST);
String authority = URI.create(appUis.onClusterUrl(yarnCluster().getId(), null, null, false).url())
.getAuthority();
assertEquals(32801, appUis.route(authority, "http").port());
// The node started again, its port published anew.
fixture.clusterStorage.webInterfaces.put(RESOURCE_MANAGER,
new ContainerLifecycleManager.EndpointInfo("localhost", 32901));
assertEquals(32801, appUis.route(authority, "http").port());
fixture.clock.advance(Duration.ofSeconds(10));
assertEquals(32901, appUis.route(authority, "http").port());
}
@Test
void anInterfaceFlociDoesNotRunOpensFlocisOwnPage() {
fixture.clusterStorage.webInterfaces.put(RESOURCE_MANAGER, RESOURCE_MANAGER_ON_HOST);
EmrAppUiService.Presigned link = appUis.onClusterUrl(yarnCluster().getId(), "SparkHistoryServer", null,
false);
assertTrue(link.ready());
assertTrue(link.url().startsWith("http://localhost:4566" + EmrAppUiService.PATH + "?"), link.url());
assertEquals(0, fixture.stepThreadsWaiting());
}
private EmrCluster yarnCluster() {
fixture.clusterStorage.ownNetwork = true;
EmrCluster cluster = cluster("app-uis", true);
cluster.setReleaseLabel("emr-7.5.0");
cluster.setApplications("[{\"Name\":\"Hadoop\"},{\"Name\":\"Spark\"}]");
return fixture.service.runJobFlow(cluster, REGION);
}
private static String path(EmrAppUiService.Presigned link) {
return URI.create(link.url()).getPath();
}
/** Runs each command at once, as the Docker runner would. */
private static final class RecordingRunner implements SparkJobRunner {
final List<Job> jobs = new CopyOnWriteArrayList<>();
@Override
public Outcome run(Job job, Progress progress) {
jobs.add(job);
progress.started();
return Outcome.exitedWith(0);
}
@Override
public void stop(String runId) {
}
@Override
public void removeLeftoverDrivers(String service) {
}
}
}
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrStep;
@@ -98,6 +99,8 @@ final class EmrServiceFixture {
final List<List<String>> relays = new ArrayList<>();
final List<Instance> given = new ArrayList<>();
final List<String> released = new ArrayList<>();
// Where each port of a primary node's web interfaces is reached, once the node is ready.
final Map<Integer, ContainerLifecycleManager.EndpointInfo> webInterfaces = new HashMap<>();
// How each cluster's nodes are known as EC2 instances.
final Map<String, Function<String, Instance>> identities = new HashMap<>();
@@ -151,6 +154,11 @@ final class EmrServiceFixture {
return ownNetwork;
}
@Override
public Optional<ContainerLifecycleManager.EndpointInfo> webInterface(String clusterId, int port) {
return Optional.ofNullable(webInterfaces.get(port));
}
@Override
public void resize(String clusterId, Supplier<Yarn> yarn) {
resizes.add(yarn.get());
@@ -1174,8 +1174,9 @@ class LambdaServiceTest {
@Test
void createFunctionRejectsOversizedDirectZipUploadWithAwsError() {
Map<String, Object> request = baseRequest("oversized-zip");
byte[] oversized = new byte[(int) ZipExtractor.DIRECT_UPLOAD_MAX_COMPRESSED_BYTES + 1];
request.put("Code", Map.of("ZipFile", Base64.getEncoder().encodeToString(oversized)));
// Zero bytes, one more than the limit allows, as Base64: refused from its length, before it is decoded.
long chunks = ZipExtractor.DIRECT_UPLOAD_MAX_COMPRESSED_BYTES / 3 + 1;
request.put("Code", Map.of("ZipFile", "A".repeat((int) (chunks * 4))));
AwsException error = assertThrows(AwsException.class,
() -> service.createFunction(REGION, request));
@@ -1184,6 +1185,17 @@ class LambdaServiceTest {
assertEquals(413, error.getHttpStatus());
}
@Test
void anUploadsDecodedLengthIsReadFromItsBase64LengthPaddedOrNot() {
assertEquals(0, LambdaService.decodedLength(""));
assertEquals(3, LambdaService.decodedLength("AAAA"));
assertEquals(4, LambdaService.decodedLength("AAAAAA=="));
assertEquals(4, LambdaService.decodedLength("AAAAAA"));
assertEquals(5, LambdaService.decodedLength("AAAAAAA="));
byte[] limit = new byte[1024];
assertEquals(limit.length, LambdaService.decodedLength(Base64.getEncoder().encodeToString(limit)));
}
@Test
void hotReload_disabledByDefault_throwsInvalidParameter() {
// The package-private test constructor leaves config=null, which means disabled.