feat(emr): serve a cluster's nodes their instance metadata (#8449)

Every node of an EMR cluster is an EC2 instance, so any process on it,
a bootstrap action, a step or a Spark executor, reads its instance
metadata at 169.254.169.254. In the docker runner mode nothing answered
there: a bootstrap script reading its availability zone got nothing.

A relay container on the cluster's own Docker network now holds that
address as a link-local one, as ECS's credentials endpoint is held, and
each of the cluster's containers gets a link-local address of its own
there, so none needs privileges. The relay forwards to Floci's EC2
metadata server, naming its caller in X-Forwarded-For, which the server
reads only from the relays it trusts; the server answers each container
as the instance it is: the bootstrap actions and each step as the
primary node, each core or task node's container as that node, with the
instance id, type, private address and name ListInstances gives, the
cluster's availability zone and its JobFlowRole instance profile. The
metadata server now starts for the docker runner mode too.

DescribeCluster's Ec2InstanceAttributes now gives Ec2AvailabilityZone,
the one RunJobFlow's Instances.Placement names, else the Region's first,
so the metadata and the cluster agree.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-15 09:59:49 -04:00
1 parent 0f223224ce
commit c1a8a3b3ac
20 files changed
+1459 -53

No files matched your search

@@ -0,0 +1,96 @@
package io.floci.aws.services.ec2;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.services.ec2.model.Instance;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
/**
* A relay that holds 169.254.169.254 for containers that cannot hold it themselves names each caller in
* {@code X-Forwarded-For}, which the server reads from a relay it trusts alone, so no other caller can claim another
* instance's metadata by sending the header itself.
*/
class Ec2MetadataForwarderTest {
// The address a relay's caller has on its cluster's network.
private static final String CALLER = "169.254.1.5";
private final HttpClient client = HttpClient.newHttpClient();
private Ec2MetadataTestFixture fixture;
@BeforeEach
void startServer() throws Exception {
fixture = new Ec2MetadataTestFixture();
fixture.startUnregistered(mock(EmulatorConfig.class, RETURNS_DEEP_STUBS));
Instance node = Ec2MetadataTestFixture.instance("i-00000000000000001");
fixture.server().registerContainer(CALLER, node.getInstanceId(), node);
}
@AfterEach
void stopServer() throws Exception {
try (client) {
fixture.close();
}
}
@Test
void aTrustedRelaysCallerIsAnsweredAsTheInstanceItsAddressIs() throws Exception {
fixture.server().trustForwarder(Ec2MetadataTestFixture.CALLER_IP);
HttpResponse<String> answered = get("/latest/meta-data/instance-id", CALLER, null);
assertEquals(200, answered.statusCode());
assertEquals("i-00000000000000001", answered.body());
}
@Test
void aTrustedRelaysCallerGetsAndUsesAnImdsV2Token() throws Exception {
fixture.server().trustForwarder(Ec2MetadataTestFixture.CALLER_IP);
HttpResponse<String> token = client.send(HttpRequest.newBuilder(
URI.create(fixture.endpoint() + "/latest/api/token")).timeout(Duration.ofSeconds(5))
.header(Ec2MetadataTestFixture.TTL_HEADER, "60").header("X-Forwarded-For", CALLER)
.PUT(HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofString());
HttpResponse<String> answered = get("/latest/meta-data/instance-id", CALLER, token.body());
assertEquals(200, answered.statusCode());
assertEquals("i-00000000000000001", answered.body());
}
@Test
void anotherCallerNamingAnAddressIsAnsweredForItsOwn() throws Exception {
HttpResponse<String> refused = get("/latest/meta-data/instance-id", CALLER, null);
assertEquals(404, refused.statusCode());
}
@Test
void aRelayNoLongerTrustedIsAnsweredForItsOwnAddress() throws Exception {
fixture.server().trustForwarder(Ec2MetadataTestFixture.CALLER_IP);
fixture.server().distrustForwarder(Ec2MetadataTestFixture.CALLER_IP);
HttpResponse<String> refused = get("/latest/meta-data/instance-id", CALLER, null);
assertEquals(404, refused.statusCode());
}
private HttpResponse<String> get(String path, String forwardedFor, String token) throws Exception {
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(fixture.endpoint() + path))
.timeout(Duration.ofSeconds(5)).header("X-Forwarded-For", forwardedFor).GET();
if (token != null) {
request.header(Ec2MetadataTestFixture.TOKEN_HEADER, token);
}
return client.send(request.build(), HttpResponse.BodyHandlers.ofString());
}
}
@@ -32,6 +32,7 @@ import io.floci.aws.core.common.docker.ContainerSpec;
import io.floci.aws.core.common.docker.ContainerStorageHelper;
import io.floci.aws.core.common.docker.CurrentContainerNetworkResolver;
import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.emrserverless.EmrServerlessSparkRunner;
import io.floci.aws.services.emrserverless.SparkJobRunner;
import io.floci.aws.services.iam.model.SessionCreds;
@@ -884,6 +885,173 @@ class EmrClusterStorageTest {
verify(lifecycle, never()).removeIfExistsStrict(otherName);
}
@Test
void aClustersMetadataNetworkIsItsOwnWithItsRelayReachingFlociOnTheHost() {
EmrMetadataRelays relays = mock(EmrMetadataRelays.class);
when(awsEnv.flociEndpoint(false)).thenReturn("http://host.docker.internal:4566");
String network = withRelays(relays).metadataNetwork("j-1", "123456789012", "us-east-1", "sha256:image",
"floci-network");
assertEquals(hdfsName, network);
verify(lifecycle).ensureNetwork(eq(hdfsName), any());
verify(relays).start("j-1", "123456789012", "us-east-1", hdfsName, "sha256:image", "host.docker.internal");
}
@Test
void aClusterWhoseStepsShareANamespaceHasNoMetadataRelay() {
EmrMetadataRelays relays = mock(EmrMetadataRelays.class);
when(containerBuilder.resolveDockerNetwork(Optional.of("host"))).thenReturn(Optional.of("host"));
assertNull(withRelays(relays).metadataNetwork("j-1", "123456789012", "us-east-1", "sha256:image", "host"));
verify(relays, never()).start(anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
}
@Test
void eachNodeIsGivenAnAddressItsRelayAnswersAsThatNodeAndItGoesWithIt() {
nodesStart(coreName, taskName);
EmrMetadataRelays relays = mock(EmrMetadataRelays.class);
Map<String, Instance> instances = Map.of("0-1", nodeInstance("i-00000000000000001"),
"1-1", nodeInstance("i-00000000000000002"), "2-1", nodeInstance("i-00000000000000003"));
when(relays.give("j-1", instances.get("0-1"))).thenReturn("169.254.0.1");
when(relays.give("j-1", instances.get("1-1"))).thenReturn("169.254.0.2");
when(relays.give("j-1", instances.get("2-1"))).thenReturn("169.254.0.3");
when(relays.serves("j-1")).thenReturn(true);
EmrClusterStorage storage = withRelays(relays);
storage.identify("j-1", instances::get);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES,
NOT_STOPPED);
verify(spec).withLinkLocalIp("169.254.0.1");
verify(spec).withLinkLocalIp("169.254.0.2");
verify(spec).withLinkLocalIp("169.254.0.3");
storage.remove("j-1");
// The primary's with its container; the rest with the relay, which releases every address on its network.
verify(relays).release("169.254.0.1");
verify(relays).stop("j-1");
}
@Test
void aNodeAnEarlierFlociGaveAnAddressStartsAgainSoNoAddressIsGivenTwice() {
nodesStart(coreName, taskName);
runningNodes(node(coreName, "running", IMAGE, CORE_HOST, true), node(taskName, "running", IMAGE, TASK_HOST, false));
EmrMetadataRelays relays = mock(EmrMetadataRelays.class);
when(relays.give(eq("j-1"), any())).thenReturn("169.254.0.9");
when(relays.serves("j-1")).thenReturn(true);
EmrClusterStorage storage = withRelays(relays);
storage.identify("j-1", node -> nodeInstance("i-" + node));
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES,
NOT_STOPPED);
verify(lifecycle).removeIfExistsStrict(coreName);
verify(lifecycle).removeIfExistsStrict(taskName);
verify(spec).withName(coreName);
verify(spec).withName(taskName);
}
@Test
void theMetadataRelaysAnEarlierFlociLeftGoAtStart() {
Container relay = mock(Container.class);
when(relay.getId()).thenReturn("relay-old");
when(relay.getNames()).thenReturn(new String[] {"/floci-emr-j-1-metadata"});
when(relay.getLabels()).thenReturn(Map.of(ContainerStorageHelper.COMPONENT_LABEL, "emr-metadata",
ContainerStorageHelper.RESOURCE_ID_LABEL, "j-1"));
AtomicReference<Map<String, String>> filter = new AtomicReference<>();
ListContainersCmd list = mock(ListContainersCmd.class, RETURNS_SELF);
when(docker.listContainersCmd()).thenReturn(list);
when(list.withLabelFilter(any(Map.class))).thenAnswer(asked -> {
filter.set(asked.getArgument(0));
return list;
});
when(list.exec()).thenAnswer(reading -> "emr-metadata".equals(filter.get()
.get(ContainerStorageHelper.COMPONENT_LABEL)) ? List.of(relay) : List.of());
ListNetworksCmd networks = mock(ListNetworksCmd.class, RETURNS_SELF);
when(docker.listNetworksCmd()).thenReturn(networks);
when(networks.exec()).thenReturn(List.of());
ListVolumesCmd volumes = mock(ListVolumesCmd.class, RETURNS_SELF);
when(docker.listVolumesCmd()).thenReturn(volumes);
when(volumes.exec()).thenReturn(mock(ListVolumesResponse.class));
storage.removeAllBut(Set.of("j-1"));
verify(lifecycle).stopAndRemove("relay-old", null, 0);
}
@Test
void aNodeDockerKeepsKeepsItsAddressSoNoOtherContainerIsGivenIt() {
nodesStart(coreName, taskName);
EmrMetadataRelays relays = mock(EmrMetadataRelays.class);
Map<String, Instance> instances = Map.of("0-1", nodeInstance("i-00000000000000001"),
"1-1", nodeInstance("i-00000000000000002"), "2-1", nodeInstance("i-00000000000000003"));
when(relays.give("j-1", instances.get("0-1"))).thenReturn("169.254.0.1");
when(relays.give("j-1", instances.get("1-1"))).thenReturn("169.254.0.2");
when(relays.give("j-1", instances.get("2-1"))).thenReturn("169.254.0.3");
when(relays.serves("j-1")).thenReturn(true);
EmrClusterStorage storage = withRelays(relays);
storage.identify("j-1", instances::get);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES,
NOT_STOPPED);
doThrow(new IllegalStateException("Docker kept it")).doNothing().when(lifecycle).removeIfExistsStrict(coreName);
storage.stopManagedContainers();
// Its container may still be there, at that address, which the relay would answer as another's.
verify(relays, never()).release("169.254.0.2");
verify(relays).release("169.254.0.3");
storage.stopManagedContainers();
verify(relays).release("169.254.0.2");
}
@Test
void anHdfsInTheHostsNamespaceFoundRunningServesEachStepAsNoRelayServesItsCluster() {
when(containerBuilder.resolveDockerNetwork(Optional.of("host"))).thenReturn(Optional.of("host"));
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING);
runningOn(hdfsName, "host");
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
EmrMetadataRelays relays = mock(EmrMetadataRelays.class);
EmrClusterStorage storage = withRelays(relays);
storage.identify("j-1", node -> nodeInstance("i-" + node));
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", null, null, NOT_STOPPED);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", null, null, NOT_STOPPED);
// The other steps of its cluster use it.
verify(lifecycle, never()).removeIfExistsStrict(hdfsName);
verify(lifecycle, never()).createAndStart(any());
verify(relays, never()).give(anyString(), any());
}
@Test
void aRelayDockerKeepsLeavesItsClustersStorageToBeRemovedAgain() {
when(lifecycle.removeNetwork(any())).thenReturn(true);
when(lifecycle.removeVolume(any())).thenReturn(true);
runningNodes();
EmrMetadataRelays relays = mock(EmrMetadataRelays.class);
when(relays.stop("j-1")).thenReturn(false, true);
EmrClusterStorage storage = withRelays(relays);
assertFalse(storage.remove("j-1"));
assertTrue(storage.remove("j-1"));
}
private EmrClusterStorage withRelays(EmrMetadataRelays relays) {
return new EmrClusterStorage(lifecycle, containerBuilder, awsEnv, roleCredentials, currentContainer, config,
s3, Duration.ofSeconds(120), System::nanoTime, Runnable::run, Duration.ZERO, relays);
}
private static Instance nodeInstance(String id) {
Instance instance = new Instance();
instance.setInstanceId(id);
return instance;
}
@Test
void aStoppedNodesLogsComeFromTheWholeFolderOnceAndNeverItsLaunchScript() throws IOException {
runningNodes(node(taskName, "exited", IMAGE, TASK_HOST, false));
@@ -549,4 +549,25 @@ class EmrIntegrationTest {
cluster.setKeepJobFlowAliveWhenNoSteps(true);
return emrService.runJobFlow(cluster, "us-east-1");
}
@Test
@Order(20)
void aClustersAvailabilityZoneIsTheOneItsPlacementNamesElseItsRegionsFirst() {
String placed = emr("RunJobFlow", "{\"Name\":\"placed\",\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true,"
+ "\"Placement\":{\"AvailabilityZone\":\"us-east-1c\"}}}").then().statusCode(200).extract()
.path("JobFlowId");
String unplaced = emr("RunJobFlow",
"{\"Name\":\"unplaced\",\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true}}")
.then().statusCode(200).extract().path("JobFlowId");
try {
emr("DescribeCluster", "{\"ClusterId\":\"" + placed + "\"}")
.then().statusCode(200)
.body("Cluster.Ec2InstanceAttributes.Ec2AvailabilityZone", equalTo("us-east-1c"));
emr("DescribeCluster", "{\"ClusterId\":\"" + unplaced + "\"}")
.then().statusCode(200)
.body("Cluster.Ec2InstanceAttributes.Ec2AvailabilityZone", equalTo("us-east-1a"));
} finally {
emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + placed + "\",\"" + unplaced + "\"]}")
.then().statusCode(200);
}
}
}
@@ -0,0 +1,258 @@
package io.floci.aws.services.emr;
import com.github.dockerjava.api.DockerClient;
import com.sun.net.httpserver.HttpServer;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.docker.ContainerBuilder;
import io.floci.aws.core.common.docker.ContainerExecStubs;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.common.docker.ContainerSpec;
import io.floci.aws.core.common.docker.ContainerStorageHelper;
import io.floci.aws.services.ec2.Ec2MetadataServer;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.lambda.launcher.BootstrapProcess;
import io.floci.aws.testutil.FreePorts;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** A cluster's instance metadata relay, and the link-local addresses its containers are given. */
class EmrMetadataRelaysTest {
private static final String NETWORK = "floci-emr-j-1-hdfs";
private static final String IMAGE = "sha256:image";
private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
private final DockerClient docker = mock(DockerClient.class);
private final ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
private final ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
private final ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
private final Ec2MetadataServer server = mock(Ec2MetadataServer.class);
private final EmrMetadataRelays relays = new EmrMetadataRelays(containerBuilder, lifecycle, server, config);
private final String relayName = ContainerStorageHelper.dockerName(config, EmrMetadataRelays.name("j-1"));
@BeforeEach
void docker() {
when(lifecycle.getDockerClient()).thenReturn(docker);
when(containerBuilder.newContainer(IMAGE)).thenReturn(spec);
when(spec.build()).thenReturn(new ContainerSpec(IMAGE));
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("relay-1", Map.of()));
when(lifecycle.resolveContainerNetworkIp("relay-1", NETWORK)).thenReturn("172.20.0.3");
when(config.services().ec2().imdsPort()).thenReturn(9169);
ContainerExecStubs.completeEveryExec(docker, "relay-1", 0L, "", "");
}
@Test
void aClustersRelayHoldsTheMetadataAddressOnItsNetworkAndIsTrustedOnceItListens() {
relays.start("j-1", "123456789012", "us-east-1", NETWORK, IMAGE, "floci");
verify(spec).withLinkLocalIp("169.254.169.254");
verify(spec).withDockerNetwork(Optional.of(NETWORK));
verify(spec).withUser("root");
verify(spec).withEntrypoint(List.of("python3", "-c", EmrMetadataRelays.RELAY_SCRIPT, "floci", "9169"));
verify(server).trustForwarder("172.20.0.3");
assertTrue(relays.serves("j-1"));
}
@Test
void aRelayThatStoppedIsTrustedNoMoreBeforeItGivesWayToANewOne() {
relays.start("j-1", "123456789012", "us-east-1", NETWORK, IMAGE, "floci");
when(lifecycle.createAndStart(any()))
.thenReturn(new ContainerLifecycleManager.ContainerInfo("relay-2", Map.of()));
when(lifecycle.resolveContainerNetworkIp("relay-2", NETWORK)).thenReturn("172.20.0.4");
ContainerExecStubs.completeEveryExec(docker, "relay-2", 0L, "", "");
relays.start("j-1", "123456789012", "us-east-1", NETWORK, IMAGE, "floci");
// Docker may give the stopped one's address to another container once it has gone.
InOrder order = inOrder(server, lifecycle);
order.verify(server).distrustForwarder("172.20.0.3");
order.verify(lifecycle).removeIfExistsStrict(relayName);
order.verify(server).trustForwarder("172.20.0.4");
}
@Test
void aRelayDockerKeepsIsTrustedNoMoreAndTheNextStopRemovesIt() {
relays.start("j-1", "123456789012", "us-east-1", NETWORK, IMAGE, "floci");
doThrow(new IllegalStateException("Docker kept it")).doNothing()
.when(lifecycle).removeIfExistsStrict(relayName);
assertFalse(relays.stop("j-1"));
verify(server).distrustForwarder("172.20.0.3");
assertFalse(relays.serves("j-1"));
relays.stopManagedContainers();
// Once as it started, then as its cluster ended, and again as Floci stopped.
verify(lifecycle, times(3)).removeIfExistsStrict(relayName);
}
@Test
void eachContainerGetsAnAddressOfItsOwnWhichTheServerAnswersAsItsInstance() {
Instance primary = instance("i-00000000000000001");
Instance core = instance("i-00000000000000002");
String bootstrap = relays.give("j-1", primary);
String step = relays.give("j-1", primary);
String node = relays.give("j-1", core);
assertEquals(3, Set.of(bootstrap, step, node).size());
assertTrue(Set.of(bootstrap, step, node).stream().allMatch(address -> address.startsWith("169.254.")));
assertTrue(Set.of(bootstrap, step, node).stream().noneMatch("169.254.169.254"::equals));
verify(server).reconcileClusterNodeAddresses(Set.of(bootstrap, step), primary);
verify(server).reconcileClusterNodeAddresses(Set.of(node), core);
}
@Test
void anInstanceIsForgottenWithTheLastAddressItWasGiven() {
Instance primary = instance("i-00000000000000001");
String bootstrap = relays.give("j-1", primary);
String step = relays.give("j-1", primary);
relays.release(bootstrap);
verify(server).reconcileClusterNodeAddresses(Set.of(step), primary);
verify(server, never()).unregisterInstance(primary);
relays.release(step);
verify(server).unregisterInstance(primary);
// A released address is given again.
assertEquals(bootstrap, relays.give("j-1", instance("i-00000000000000003")));
}
@Test
void aClustersEndRemovesItsRelayAndEveryAddressGivenOnItsNetwork() {
relays.start("j-1", "123456789012", "us-east-1", NETWORK, IMAGE, "floci");
Instance primary = instance("i-00000000000000001");
Instance other = instance("i-00000000000000001");
relays.give("j-1", primary);
String kept = relays.give("j-2", other);
assertTrue(relays.stop("j-1"));
verify(server).distrustForwarder("172.20.0.3");
// Once as it started, which a container of its name left would have kept from it, and once as it went.
verify(lifecycle, times(2)).removeIfExistsStrict(relayName);
verify(server).unregisterInstance(primary);
verify(server, never()).unregisterInstance(other);
assertNotEquals(kept, relays.give("j-2", instance("i-00000000000000002")));
}
@Test
void theRelayNamesItsCallerInPlaceOfAnyItClaimsAndPassesTheAnswerBack() throws Exception {
boolean python;
try {
python = BootstrapProcess.run(new ProcessBuilder("python3", "--version")).exit() == 0;
} catch (IOException e) {
python = false;
}
assumeTrue(python, "the host has no python3");
List<String> seen = new CopyOnWriteArrayList<>();
HttpServer target = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
target.createContext("/", exchange -> {
seen.add(exchange.getRequestMethod() + " " + exchange.getRequestURI() + " "
+ exchange.getRequestHeaders().getFirst("X-Forwarded-For") + " "
+ exchange.getRequestHeaders().getFirst("X-aws-ec2-metadata-token-ttl-seconds"));
byte[] body = "i-00000000000000001".getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("X-aws-ec2-metadata-token-ttl-seconds", "60");
if ("HEAD".equals(exchange.getRequestMethod())) {
// The length of the body a GET would have, which a HEAD's answer gives.
exchange.getResponseHeaders().set("Content-Length", String.valueOf(body.length));
}
exchange.sendResponseHeaders(200, "HEAD".equals(exchange.getRequestMethod()) ? -1 : body.length);
try (OutputStream out = exchange.getResponseBody()) {
if (!"HEAD".equals(exchange.getRequestMethod())) {
out.write(body);
}
}
});
target.start();
int port = FreePorts.loopbackIpv4Port();
String script = EmrMetadataRelays.RELAY_SCRIPT.replace("Server(('169.254.169.254', 80)",
"Server(('127.0.0.1', " + port + ")");
Process relay = new ProcessBuilder("python3", "-I", "-c", script, "127.0.0.1",
String.valueOf(target.getAddress().getPort())).redirectErrorStream(true).start();
try (HttpClient client = HttpClient.newHttpClient()) {
awaitListening(port, relay);
String base = "http://127.0.0.1:" + port;
HttpResponse<String> got = client.send(HttpRequest.newBuilder(URI.create(base + "/latest/meta-data/instance-id"))
.header("X-Forwarded-For", "203.0.113.9").timeout(Duration.ofSeconds(5)).GET().build(),
HttpResponse.BodyHandlers.ofString());
HttpResponse<String> token = client.send(HttpRequest.newBuilder(URI.create(base + "/latest/api/token"))
.header("X-aws-ec2-metadata-token-ttl-seconds", "60").timeout(Duration.ofSeconds(5))
.PUT(HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofString());
HttpResponse<String> head = client.send(HttpRequest.newBuilder(URI.create(base + "/latest/meta-data/"))
.timeout(Duration.ofSeconds(5)).method("HEAD", HttpRequest.BodyPublishers.noBody()).build(),
HttpResponse.BodyHandlers.ofString());
assertEquals(200, got.statusCode());
assertEquals("i-00000000000000001", got.body());
assertEquals("60", token.headers().firstValue("X-aws-ec2-metadata-token-ttl-seconds").orElseThrow());
assertEquals(200, head.statusCode());
assertEquals("", head.body());
assertEquals("19", head.headers().firstValue("Content-Length").orElseThrow());
assertEquals(List.of("GET /latest/meta-data/instance-id 127.0.0.1 null",
"PUT /latest/api/token 127.0.0.1 60", "HEAD /latest/meta-data/ 127.0.0.1 null"), seen);
} finally {
relay.destroyForcibly();
target.stop(0);
}
}
// Until the relay takes a connection on port, or has exited, within ten seconds.
private static void awaitListening(int port, Process relay) throws Exception {
long deadline = System.nanoTime() + Duration.ofSeconds(10).toNanos();
while (System.nanoTime() < deadline && relay.isAlive()) {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress("127.0.0.1", port), 200);
return;
} catch (IOException notYet) {
// Not listening yet: Python is starting.
Thread.onSpinWait();
}
}
throw new AssertionError("The relay did not listen: "
+ new String(relay.getInputStream().readAllBytes(), StandardCharsets.UTF_8));
}
private static Instance instance(String id) {
Instance instance = new Instance();
instance.setInstanceId(id);
return instance;
}
}
@@ -6,6 +6,7 @@ import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.ContainerTeardown;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrErrorDetail;
import io.floci.aws.services.emr.model.EmrInstanceFleet;
@@ -689,6 +690,79 @@ class EmrServiceContainerStepsTest {
assertEquals(List.of("--master", "yarn", "--deploy-mode", "cluster", REPORT), runner.jobs.get(0).application());
}
@Test
void aStepReadsItsPrimaryNodesInstanceMetadataAtAnAddressItsClusterGivesIt() {
fixture.clusterStorage.metadata = true;
EmrCluster requested = cluster("metadata", true, sparkStep("report", "CONTINUE"));
requested.setJobFlowRole("EMR_EC2_DefaultRole");
EmrInstanceGroup primaryGroup = new EmrInstanceGroup();
primaryGroup.setInstanceGroupType("MASTER");
primaryGroup.setInstanceType("m5.xlarge");
primaryGroup.setRequestedInstanceCount(1);
requested.setInstanceGroups(new ArrayList<>(List.of(primaryGroup)));
EmrCluster cluster = service.runJobFlow(requested, REGION);
fixture.runStepThread();
// The relay runs in the step's image, and the step's container is given an address on the cluster's network.
assertEquals(List.of(List.of(cluster.getId(), "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest")),
fixture.clusterStorage.relays);
assertEquals("169.254.0.1", runner.jobs.get(0).storage().metadataAddress());
// Answered as the primary node, as ListInstances and DescribeCluster give it.
Instance primary = fixture.clusterStorage.given.get(0);
assertEquals("i-00000000000000001", primary.getInstanceId());
assertEquals("m5.xlarge", primary.getInstanceType());
assertEquals("10.0.0.1", primary.getPrivateIpAddress());
assertEquals("ip-10-0-0-1.ec2.internal", primary.getPrivateDnsName());
assertEquals("us-east-1a", primary.getPlacement().getAvailabilityZone());
assertEquals("arn:aws:iam::000000000000:instance-profile/EMR_EC2_DefaultRole",
primary.getIamInstanceProfileArn());
// Released once the step ended, and its nodes known as the cluster numbers them.
assertEquals(List.of("169.254.0.1"), fixture.clusterStorage.released);
assertEquals("i-00000000000000001",
fixture.clusterStorage.identities.get(cluster.getId()).apply("0-1").getInstanceId());
}
@Test
void aStepOnAClusterWithoutARelayHasNoMetadataAddress() {
service.runJobFlow(cluster("no-metadata", true, sparkStep("report", "CONTINUE")), REGION);
fixture.runStepThread();
assertNull(runner.jobs.get(0).storage().metadataAddress());
assertEquals(List.of(), fixture.clusterStorage.given);
}
@Test
void aNodeIsAnInstanceOfItsClustersAccountWithThePublicNameListInstancesGivesIt() {
EmrCluster requested = cluster("other-account", true);
requested.setJobFlowRole("EMR_EC2_DefaultRole");
EmrCluster cluster = service.runJobFlow(requested, REGION);
Instance primary = service.nodeInstance(cluster, "111111111111", 0, 1);
// Its owner is its cluster's account, which its identity document and its credentials name.
assertEquals("111111111111", primary.getOwnerId());
assertEquals("arn:aws:iam::111111111111:instance-profile/EMR_EC2_DefaultRole",
primary.getIamInstanceProfileArn());
assertEquals("ec2-203-0-113-1.compute-1.amazonaws.com", primary.getPublicDnsName());
}
@Test
void aRelayThatCannotStartFailsTheStepThatWouldReadIt() {
fixture.clusterStorage.metadata = true;
fixture.clusterStorage.metadataFailure = new IllegalStateException("The relay did not listen");
EmrCluster cluster = service.runJobFlow(cluster("no-relay", true, sparkStep("report", "CONTINUE")), REGION);
fixture.runStepThread();
EmrStep failed = service.describeStep(cluster.getId(), cluster.getSteps().get(0).getId());
assertEquals("FAILED", failed.getState());
assertEquals("The step could not start: The instance metadata of EMR cluster " + cluster.getId()
+ " could not start: The relay did not listen", failed.getFailureMessage());
assertEquals(List.of(), runner.jobs);
}
@Test
void aClusterOfTheAwsRuntimeForSparkRunsYarnFromTheHadoopItsImageKeepsApart() {
fixture.clusterStorage.ownNetwork = true;
@@ -1483,6 +1557,55 @@ class EmrServiceContainerStepsTest {
assertEquals(List.of(EmrServiceFixture.RecordingReleaseImages.IMAGE), bootstrapping.releaseImages.released);
}
@Test
void aBootstrapRunsOnItsClustersNetworkAtAnAddressItsRelayAnswersAsThePrimaryNode() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
bootstrapping.clusterStorage.metadata = true;
EmrCluster cluster = bootstrapping.service.runJobFlow(bootstrapped(cluster("bootstrapped-metadata", true)),
REGION);
bootstrapping.runStepThread();
BootstrapRunner.Bootstrap ran = bootstrap.bootstraps.get(0);
assertEquals(EmrServiceFixture.RecordingStorage.HDFS_NETWORK, ran.metadataNetwork());
assertEquals("169.254.0.1", ran.metadataAddress());
assertEquals("i-00000000000000001", bootstrapping.clusterStorage.given.get(0).getInstanceId());
assertEquals(List.of("169.254.0.1"), bootstrapping.clusterStorage.released);
assertEquals(cluster.getId(), bootstrapping.clusterStorage.relays.get(0).get(0));
}
@Test
void aClusterWhoseBootstrapAloneHadAMetadataRelayRemovesItAsItEnds() {
bootstrap.outcome = BootstrapRunner.Outcome.actionFailed(1, 1);
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
bootstrapping.clusterStorage.metadata = true;
EmrCluster cluster = bootstrapping.service.runJobFlow(bootstrapped(cluster("bootstrap-only", true)), REGION);
bootstrapping.runStepThread();
assertEquals("TERMINATED_WITH_ERRORS", bootstrapping.service.describeCluster(cluster.getId()).getState());
bootstrapping.runStepThread();
// Its network and relay go as its storage does, though no step of it ran.
assertEquals(List.of(cluster.getId()), bootstrapping.clusterStorage.removed);
}
@Test
void aBootstrapWhoseRelayCannotStartEndsItsClusterWhoseNetworkThenGoes() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
bootstrapping.clusterStorage.metadata = true;
bootstrapping.clusterStorage.metadataFailure = new IllegalStateException("The relay did not listen");
EmrCluster cluster = bootstrapping.service.runJobFlow(bootstrapped(cluster("no-relay", true)), REGION);
bootstrapping.runStepThread();
EmrCluster ended = bootstrapping.service.describeCluster(cluster.getId());
assertEquals("TERMINATED_WITH_ERRORS", ended.getState());
assertEquals("INTERNAL_ERROR", ended.getStateChangeReasonCode());
assertEquals(List.of(), bootstrap.bootstraps);
bootstrapping.runStepThread();
assertEquals(List.of(cluster.getId()), bootstrapping.clusterStorage.removed);
}
@Test
void aClusterWithHiveThatEndsBeforeItsBootstrapOrStepRunsMakesNoImage() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
@@ -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.services.ec2.model.Instance;
import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrStep;
import io.floci.aws.services.emrserverless.SparkJobRunner;
@@ -16,11 +17,14 @@ import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
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.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -83,6 +87,50 @@ final class EmrServiceFixture {
final List<ClusterStorage.Yarn> resizes = new ArrayList<>();
boolean refuse;
Runnable whileCreating = () -> { };
// Whether a cluster's network has an instance metadata relay, as where its steps have a network of Floci's.
boolean metadata;
// What a relay's start throws, if anything.
RuntimeException metadataFailure;
// Each relay started: its cluster and image; each instance given an address, by id; each address released.
final List<List<String>> relays = new ArrayList<>();
final List<Instance> given = new ArrayList<>();
final List<String> released = new ArrayList<>();
// How each cluster's nodes are known as EC2 instances.
final Map<String, Function<String, Instance>> identities = new HashMap<>();
@Override
public boolean metadataServed(String dockerNetwork) {
return metadata;
}
@Override
public String metadataNetwork(String clusterId, String accountId, String region, String relayImage,
String dockerNetwork) {
if (!metadata) {
return null;
}
relays.add(List.of(clusterId, relayImage));
if (metadataFailure != null) {
throw metadataFailure;
}
return HDFS_NETWORK;
}
@Override
public String metadataAddress(String clusterId, Instance instance) {
given.add(instance);
return "169.254.0." + given.size();
}
@Override
public void releaseMetadataAddress(String address) {
released.add(address);
}
@Override
public void identify(String clusterId, Function<String, Instance> nodes) {
identities.put(clusterId, nodes);
}
@Override
public SparkJobRunner.Storage volumes(String clusterId) {
@@ -369,7 +369,7 @@ class EmrServerlessSparkRunnerTest {
verify(lifecycle, never()).resolveImageForLaunch(anyString(), any(), any());
// An EMR Serverless run has no cluster, nor its storage or network.
verify(spec, never()).withNamedVolume(anyString(), anyString());
verify(lifecycle, never()).connectToNetwork(anyString(), anyString());
verify(lifecycle, never()).connectToNetwork(anyString(), anyString(), any());
}
@Test
@@ -945,7 +945,7 @@ class EmrServerlessSparkRunnerTest {
verify(spec).withExtraHost("ip-10-0-0-1.ec2.internal", "172.18.0.5");
InOrder order = inOrder(lifecycle);
order.verify(lifecycle).create(any());
order.verify(lifecycle).connectToNetwork("driver", "floci-aws-emr-j-2AXXXXXXGAPLF-hdfs");
order.verify(lifecycle).connectToNetwork("driver", "floci-aws-emr-j-2AXXXXXXGAPLF-hdfs", null);
order.verify(lifecycle).startCreated(eq("driver"), any());
// After Floci's S3 settings, before the cluster's spark-defaults, which win.
assertEquals("spark.hadoop.aws.region=eu-west-1", arguments.get(19));
@@ -1031,9 +1031,9 @@ class EmrServerlessSparkRunnerTest {
InOrder order = inOrder(lifecycle);
order.verify(lifecycle).create(any());
order.verify(lifecycle).ensureConnected("driver", "floci-aws-emr-j-2AXXXXXXGAPLF-hdfs", "s-1a2b3c4d5e6f7");
order.verify(lifecycle).ensureConnected("driver", "floci-aws-emr-j-2AXXXXXXGAPLF-hdfs", "s-1a2b3c4d5e6f7", null);
order.verify(lifecycle).startCreated(eq("driver"), any());
verify(lifecycle, never()).connectToNetwork(anyString(), anyString());
verify(lifecycle, never()).connectToNetwork(anyString(), anyString(), any());
// Floci's address on the cluster's network, where its executors reach it too, not on Floci's own.
verify(spec).withCmd(argThat((List<String> arguments) ->
arguments.contains("spark.hadoop.fs.s3a.endpoint=http://floci-on-cluster:4566")