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

@@ -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 {