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

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