diff --git a/docs/services/emr.md b/docs/services/emr.md index cbdd68f329..5a73aa9ec0 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -519,6 +519,20 @@ holding the driver and its executors, or a command or a script. The cluster itse * **Credentials**: the container gets a session for the step's `ExecutionRoleArn`, or else for the role of the cluster's `JobFlowRole` instance profile, when IAM knows it and the profile holds one role, and otherwise the account's placeholder credentials, with `AWS_ENDPOINT_URL` pointing at Floci. +* **Instance metadata**: each node of an EMR cluster is an EC2 instance, so any process on it, a bootstrap action, a + step's command or a Spark executor YARN runs, reads its instance metadata at `http://169.254.169.254`, IMDSv1 and + IMDSv2. On a cluster with a Docker network of its own (see **Storage**), a relay container on that network holds + that address, as ECS's credentials endpoint is held, and each of the cluster's containers gets a link-local address + of its own there, so no container needs privileges; the relay forwards to Floci's EC2 metadata server, which answers + each as the instance it is: the bootstrap actions and each step's container as the primary node, each core or task + node's container as that node. Each answers with the instance id, type, private address and name and public name + `ListInstances` gives it, the cluster's account, the cluster's availability zone, which `DescribeCluster`'s + `Ec2InstanceAttributes` gives as `Ec2AvailabilityZone` (the one `RunJobFlow`'s `Instances.Placement` names, else the + Region's first), and the `JobFlowRole` instance profile, whose role's credentials `iam/security-credentials` gives + when IAM holds the profile with one role. Only the cluster's own containers reach its relay, and the metadata server + trusts the caller the relay names only from the relays Floci started. A relay that cannot start fails the step that + would read it, or ends the cluster as bootstrap actions that could not run do. Where the steps share a namespace or + have none, there is no relay. * **Output**: the driver's output goes to Floci's log, prefixed `emr:`. With a `LogUri` on the cluster, its standard output and error also go to Floci's S3 once the step ends, gzipped, as `stdout.gz` and `stderr.gz` under `//steps//`, the step log folder of the diff --git a/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java index 71a518e621..950a9bf00d 100644 --- a/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java +++ b/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java @@ -3,6 +3,7 @@ package io.floci.aws.core.common.docker; import com.fasterxml.jackson.annotation.JsonProperty; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.async.ResultCallback; +import com.github.dockerjava.api.command.ConnectToNetworkCmd; import com.github.dockerjava.api.command.CreateContainerCmd; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.InspectContainerResponse; @@ -1053,10 +1054,12 @@ public class ContainerLifecycleManager { /** Connects the created container {@code containerId} to {@code networkName} too, before it starts. */ public void connectToNetwork(String containerId, String networkName) { - dockerClient.connectToNetworkCmd() - .withContainerId(containerId) - .withNetworkId(networkName) - .exec(); + connectToNetwork(containerId, networkName, null); + } + + /** Connects {@code containerId} to {@code networkName}, with {@code linkLocalIp} there too unless it is null. */ + public void connectToNetwork(String containerId, String networkName, String linkLocalIp) { + connect(containerId, networkName, null, linkLocalIp); } /** @@ -1064,17 +1067,32 @@ public class ContainerLifecycleManager { * as {@code alias}, unless it is on it already. */ public void ensureConnected(String containerId, String networkName, String alias) { + ensureConnected(containerId, networkName, alias, null); + } + + /** As {@link #ensureConnected(String, String, String)}, with {@code linkLocalIp} there too unless it is null. */ + public void ensureConnected(String containerId, String networkName, String alias, String linkLocalIp) { if (networksOf(containerId).containsKey(networkName)) { return; } - dockerClient.connectToNetworkCmd() - .withContainerId(containerId) - .withNetworkId(networkName) - .withContainerNetwork(new ContainerNetwork().withAliases(alias)) - .exec(); + connect(containerId, networkName, new ContainerNetwork().withAliases(alias), linkLocalIp); LOG.debugv("Connected {0} to network {1} as {2}", containerId, networkName, alias); } + // Connects containerId to networkName, at endpoint unless it is null, with linkLocalIp there too unless it is null. + private void connect(String containerId, String networkName, ContainerNetwork endpoint, String linkLocalIp) { + ContainerNetwork at = linkLocalIp == null ? endpoint + : (endpoint != null ? endpoint : new ContainerNetwork()) + .withIpamConfig(new LinkLocalIpam(List.of(linkLocalIp))); + ConnectToNetworkCmd connect = dockerClient.connectToNetworkCmd() + .withContainerId(containerId) + .withNetworkId(networkName); + if (at != null) { + connect.withContainerNetwork(at); + } + connect.exec(); + } + /** * The last {@code lines} lines the container {@code containerId} wrote, standard output and error together, or as * much of them as Docker gave within {@code timeout}; empty when it gave none. For the message of a container that diff --git a/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java b/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java index 64f5abee77..ae65403233 100644 --- a/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java +++ b/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java @@ -471,6 +471,11 @@ public class EmulatorLifecycle { return true; } EmulatorConfig.EksServiceConfig eks = config.services().eks(); - return eks != null && eks.enabled() && !eks.mock() && eks.imds(); + if (eks != null && eks.enabled() && !eks.mock() && eks.imds()) { + return true; + } + // An EMR cluster's containers in the docker runner mode read their nodes' metadata through it. + EmulatorConfig.EmrServiceConfig emr = config.services().emr(); + return emr != null && emr.enabled() && "docker".equalsIgnoreCase(emr.runnerMode()); } } diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2MetadataServer.java b/src/main/java/io/floci/aws/services/ec2/Ec2MetadataServer.java index 020212366c..83a2b8fbb5 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2MetadataServer.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2MetadataServer.java @@ -69,6 +69,8 @@ public class Ec2MetadataServer { private final Map containerIpToInstance = new ConcurrentHashMap<>(); /** Cluster nodes whose instance-profile identity their registrar synthesizes rather than IAM holding it. */ private final Set synthesizedProfiles = ConcurrentHashMap.newKeySet(); + /** The addresses of the relays that name each caller in X-Forwarded-For, which is read from them alone. */ + private final Set forwarders = ConcurrentHashMap.newKeySet(); private volatile HttpServer httpServer; private final InstanceConnectKeys instanceConnect; @@ -97,6 +99,23 @@ public class Ec2MetadataServer { return Optional.ofNullable(instanceConnect); } + /** + * Trusts the relay at {@code address}, which holds 169.254.169.254 for containers that cannot hold it themselves and + * names each caller's address in {@code X-Forwarded-For}: a request from it is answered for that caller. + */ + public void trustForwarder(String address) { + if (address != null && !address.isBlank()) { + forwarders.add(address); + } + } + + /** Stops trusting the relay at {@code address}, which has gone. */ + public void distrustForwarder(String address) { + if (address != null) { + forwarders.remove(address); + } + } + /** Called by Ec2ContainerManager after a container starts to register its IP. */ public void registerContainer(String containerIp, String instanceId, Instance instance) { if (containerIp != null && !containerIp.isBlank()) { @@ -235,6 +254,7 @@ public class Ec2MetadataServer { tokens.clear(); containerIpToInstance.clear(); synthesizedProfiles.clear(); + forwarders.clear(); if (httpServer != null) { httpServer.close(); httpServer = null; @@ -261,7 +281,7 @@ public class Ec2MetadataServer { } else { LOG.debugv("IMDS: token requested from {0}, which is not a registered EC2 container; " - + "metadata requests with this token will fail", ctx.request().remoteAddress().host()); + + "metadata requests with this token will fail", callerAddress(ctx)); } ctx.response() @@ -563,8 +583,14 @@ public class Ec2MetadataServer { // ── Instance resolution ─────────────────────────────────────────────────── private Instance resolveInstanceByIp(RoutingContext ctx) { - String remoteIp = ctx.request().remoteAddress().host(); - return containerIpToInstance.get(remoteIp); + return containerIpToInstance.get(callerAddress(ctx)); + } + + // The caller's address: the request's own, or the one a trusted relay names for its caller. + private String callerAddress(RoutingContext ctx) { + String remote = ctx.request().remoteAddress().host(); + String forwarded = forwarders.contains(remote) ? ctx.request().getHeader("X-Forwarded-For") : null; + return forwarded != null && !forwarded.isBlank() ? forwarded.trim() : remote; } /** @@ -586,8 +612,7 @@ public class Ec2MetadataServer { } private Instance resolveInstance(RoutingContext ctx) { - String remoteIp = ctx.request().remoteAddress().host(); - Instance inst = containerIpToInstance.get(remoteIp); + Instance inst = containerIpToInstance.get(callerAddress(ctx)); // IMDSv2: a presented token must be valid; an invalid or expired one gets 401 so the // caller fetches a new token. A token is not valid on another instance, so a caller whose @@ -614,7 +639,7 @@ public class Ec2MetadataServer { } if (inst == null) { - String message = unregisteredContainerMessage(remoteIp); + String message = unregisteredContainerMessage(callerAddress(ctx)); LOG.warnv("IMDS: {0}", message); ctx.response().setStatusCode(404) .putHeader("content-type", "text/plain") diff --git a/src/main/java/io/floci/aws/services/emr/BootstrapRunner.java b/src/main/java/io/floci/aws/services/emr/BootstrapRunner.java index ac8f8287f9..19bb2d1653 100644 --- a/src/main/java/io/floci/aws/services/emr/BootstrapRunner.java +++ b/src/main/java/io/floci/aws/services/emr/BootstrapRunner.java @@ -42,12 +42,28 @@ public interface BootstrapRunner { * (null for none), each action's in a folder of its own named by its number. */ record Bootstrap(String clusterId, String accountId, String region, String releaseLabel, String imageTemplate, - String dockerNetwork, String role, List actions, String logFolder) { + String dockerNetwork, String role, List actions, String logFolder, + String metadataNetwork, String metadataAddress) { + + Bootstrap(String clusterId, String accountId, String region, String releaseLabel, String imageTemplate, + String dockerNetwork, String role, List actions, String logFolder) { + this(clusterId, accountId, region, releaseLabel, imageTemplate, dockerNetwork, role, actions, logFolder, + null, null); + } /** This bootstrap, run in {@code image}. */ Bootstrap inImage(String image) { return new Bootstrap(clusterId, accountId, region, releaseLabel, image, dockerNetwork, role, actions, - logFolder); + logFolder, metadataNetwork, metadataAddress); + } + + /** + * This bootstrap, its container on {@code network}, its cluster's own, at {@code address}, a link-local one, + * where its cluster's instance metadata relay answers it as the primary node, and on its steps' network too. + */ + Bootstrap onMetadata(String network, String address) { + return new Bootstrap(clusterId, accountId, region, releaseLabel, imageTemplate, dockerNetwork, role, + actions, logFolder, network, address); } } diff --git a/src/main/java/io/floci/aws/services/emr/ClusterStorage.java b/src/main/java/io/floci/aws/services/emr/ClusterStorage.java index 971cc59a06..6ce82d6c29 100644 --- a/src/main/java/io/floci/aws/services/emr/ClusterStorage.java +++ b/src/main/java/io/floci/aws/services/emr/ClusterStorage.java @@ -1,11 +1,13 @@ package io.floci.aws.services.emr; +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.Set; import java.util.function.BooleanSupplier; +import java.util.function.Function; import java.util.function.Supplier; /** @@ -16,6 +18,9 @@ import java.util.function.Supplier; */ public interface ClusterStorage { + /** The name {@link #identify} knows a cluster's primary node by: the first instance of its group numbered 0. */ + String PRIMARY_NODE = "0-1"; + /** The volumes holding {@code clusterId}'s storage, whether or not they are there yet. */ SparkJobRunner.Storage volumes(String clusterId); @@ -29,6 +34,44 @@ public interface ClusterStorage { */ boolean ownNetwork(String dockerNetwork); + /** + * Whether a cluster whose steps run on {@code dockerNetwork} has an instance metadata relay on a network of its + * own, which {@link #metadataNetwork} makes. + */ + default boolean metadataServed(String dockerNetwork) { + return false; + } + + /** + * Cluster {@code clusterId}'s network, its own, made when missing, with its instance metadata relay running there in + * {@code relayImage}, which the cluster's containers join to read their nodes' metadata at 169.254.169.254; null + * where its steps share a namespace or have no network, or no relay serves the metadata. + */ + default String metadataNetwork(String clusterId, String accountId, String region, String relayImage, + String dockerNetwork) { + return null; + } + + /** + * A link-local address on cluster {@code clusterId}'s network, which {@link #metadataNetwork} made, for a container + * that is {@code instance}, whose metadata its relay answers until the address is released; null where none is. + */ + default String metadataAddress(String clusterId, Instance instance) { + return null; + } + + /** The container given {@code address} has gone, and its metadata with it. */ + default void releaseMetadataAddress(String address) { + } + + /** + * How cluster {@code clusterId}'s nodes are known as EC2 instances, by node name: {@link #PRIMARY_NODE} its primary + * node, {@code -} each core or task node, as {@link Node#id} has it; each node's container started + * from then on is given its metadata. + */ + default void identify(String clusterId, Function nodes) { + } + /** * Starts {@code clusterId}'s HDFS, a NameNode and a DataNode keeping their data in a volume of their own, and, * unless {@code hiveMetastore} is null, Hive's metastore service, and unless {@code yarn} is null, YARN, in a diff --git a/src/main/java/io/floci/aws/services/emr/EmrBootstrapRunner.java b/src/main/java/io/floci/aws/services/emr/EmrBootstrapRunner.java index ccc883c880..4ca4d79e23 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrBootstrapRunner.java +++ b/src/main/java/io/floci/aws/services/emr/EmrBootstrapRunner.java @@ -115,16 +115,25 @@ public class EmrBootstrapRunner implements BootstrapRunner, ContainerTeardown { bootstrap.clusterId() + "-bootstrap"); String image = EmrServerlessSparkRunner.image(bootstrap.imageTemplate(), bootstrap.releaseLabel()); Map labels = labels(bootstrap); - ContainerSpec spec = containerBuilder.newContainer(image) + ContainerBuilder.Builder container = containerBuilder.newContainer(image) .withName(ContainerStorageHelper.dockerName(config, SERVICE + "-" + bootstrap.clusterId() + "-bootstrap")) .withUser("root") .withEntrypoint(List.of("sleep", "infinity")) - .withDockerNetwork(Optional.ofNullable(bootstrap.dockerNetwork())) .withHostDockerInternalOnLinux() .withEmbeddedDns() - .withLabels(labels) - .build(); + .withLabels(labels); + if (bootstrap.metadataNetwork() != null) { + // On its cluster's network, where the relay answers its address as the primary node's metadata, and on + // its steps' too, where it reaches Floci. + container.withDockerNetwork(Optional.of(bootstrap.metadataNetwork())) + .withLinkLocalIp(bootstrap.metadataAddress()) + .withJoinedNetwork(containerBuilder.resolveDockerNetwork( + Optional.ofNullable(bootstrap.dockerNetwork())).orElse(null)); + } else { + container.withDockerNetwork(Optional.ofNullable(bootstrap.dockerNetwork())); + } + ContainerSpec spec = container.build(); String containerId = lifecycleManager.createAndStart(spec).containerId(); launch.started(containerId); // In before the first action, for the actions' JVMs to find it. Not through the spec: the container is diff --git a/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java b/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java index 7dcd784422..ba1f21005f 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java +++ b/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java @@ -18,6 +18,7 @@ import io.floci.aws.core.common.docker.ContainerLiveness; 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; @@ -49,6 +50,7 @@ import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicLong; import java.util.function.BooleanSupplier; +import java.util.function.Function; import java.util.function.LongSupplier; import java.util.function.Supplier; import java.util.stream.Collectors; @@ -388,6 +390,12 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { private final LongSupplier nanoTime; // The subnet of each cluster's own network, once read (see clusterSubnet). private final Map subnets = new ConcurrentHashMap<>(); + // The clusters' instance metadata relays; none in a test that has no use for them. + private final EmrMetadataRelays relays; + // How each cluster's nodes are known as EC2 instances, by node name (see ClusterStorage.identify). + private final Map> identities = new ConcurrentHashMap<>(); + // The link-local address each node's container this process started was given, by container name. + private final Map nodeAddresses = new ConcurrentHashMap<>(); // How many teardowns, by a reset or a shutdown, have run: a step waiting for its cluster's HDFS through one stops. private final AtomicLong teardowns = new AtomicLong(); @@ -395,11 +403,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { public EmrClusterStorage(ContainerLifecycleManager lifecycleManager, ContainerBuilder containerBuilder, LaunchedContainerAwsEnv awsEnv, LambdaExecutionRoleCredentials roleCredentials, CurrentContainerNetworkResolver currentContainer, EmulatorConfig config, - S3Service s3Service) { + S3Service s3Service, EmrMetadataRelays relays) { this(lifecycleManager, containerBuilder, awsEnv, roleCredentials, currentContainer, config, s3Service, HDFS_START_TIMEOUT, System::nanoTime, Executors.newCachedThreadPool(Thread.ofPlatform().daemon().name("emr-decommission-", 0).factory()), - DECOMMISSION_POLL); + DECOMMISSION_POLL, relays); } EmrClusterStorage(ContainerLifecycleManager lifecycleManager, ContainerBuilder containerBuilder, @@ -415,6 +423,16 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { CurrentContainerNetworkResolver currentContainer, EmulatorConfig config, S3Service s3Service, Duration hdfsStartTimeout, LongSupplier nanoTime, Executor decommissions, Duration decommissionPoll) { + this(lifecycleManager, containerBuilder, awsEnv, roleCredentials, currentContainer, config, s3Service, + hdfsStartTimeout, nanoTime, decommissions, decommissionPoll, null); + } + + EmrClusterStorage(ContainerLifecycleManager lifecycleManager, ContainerBuilder containerBuilder, + LaunchedContainerAwsEnv awsEnv, LambdaExecutionRoleCredentials roleCredentials, + CurrentContainerNetworkResolver currentContainer, EmulatorConfig config, S3Service s3Service, + Duration hdfsStartTimeout, LongSupplier nanoTime, Executor decommissions, + Duration decommissionPoll, EmrMetadataRelays relays) { + this.relays = relays; this.decommissions = decommissions; this.decommissionPoll = decommissionPoll; this.lifecycleManager = lifecycleManager; @@ -553,6 +571,80 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { } } + @Override + public boolean metadataServed(String dockerNetwork) { + String network = network(dockerNetwork); + return relays != null && network != null && !NO_NETWORK.equals(network) && !sharesNamespace(network); + } + + @Override + public String metadataNetwork(String clusterId, String accountId, String region, String relayImage, + String dockerNetwork) { + if (!metadataServed(dockerNetwork)) { + return null; + } + String name = hdfsName(clusterId); + lifecycleManager.ensureNetwork(name, labels(clusterId, accountId, region, HDFS_COMPONENT)); + relays.start(clusterId, accountId, region, name, relayImage, metadataTarget(name)); + return name; + } + + @Override + public String metadataAddress(String clusterId, Instance instance) { + return relays != null ? relays.give(clusterId, instance) : null; + } + + @Override + public void identify(String clusterId, Function nodes) { + identities.put(clusterId, nodes); + } + + // The address the container of a cluster's node is given on its cluster's network, where its relay answers it as + // that node, the one it had before released; null where no relay serves the cluster or the node is not known. + private String nodeAddress(String clusterId, String containerName, String node) { + releaseNodeAddress(containerName); + Function known = identities.get(clusterId); + Instance instance = served(clusterId) && known != null ? known.apply(node) : null; + if (instance == null) { + return null; + } + String address = relays.give(clusterId, instance); + nodeAddresses.put(containerName, address); + return address; + } + + private void releaseNodeAddress(String containerName) { + String address = nodeAddresses.remove(containerName); + if (address != null && relays != null) { + relays.release(address); + } + } + + // Whether a node's container found running can serve its metadata: on a network a relay serves, one this process + // did not give an address, an earlier Floci's, has one this process does not know, which it could give another + // container, so it starts again. One in a namespace the steps share, which no relay serves, has none to know. + private boolean metadataKnown(String clusterId, String containerName) { + return !served(clusterId) || !identities.containsKey(clusterId) || nodeAddresses.containsKey(containerName); + } + + // Whether a relay serves cluster clusterId's network. + private boolean served(String clusterId) { + return relays != null && relays.serves(clusterId); + } + + @Override + public void releaseMetadataAddress(String address) { + if (relays != null) { + relays.release(address); + } + } + + // Where the metadata relay on a cluster's network reaches Floci: as FLOCI_ALIAS, Floci's container joining the + // network, as for the metastore, else Floci on the host at the host's address. + private String metadataTarget(String network) { + return attachFloci(network) ? FLOCI_ALIAS : URI.create(awsEnv.flociEndpoint(false)).getHost(); + } + @Override public boolean ownNetwork(String dockerNetwork) { String network = network(dockerNetwork); @@ -598,6 +690,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { && inStepsNamespace(name, shared ? network : name, shared || hiveMetastore != null || clusterSubnet(clusterId) == null ? null : network, imageId) + && metadataKnown(clusterId, name) && (shared || hiveMetastore == null || metastoreCurrent(name)); // Known before it starts, so a teardown while it starts removes it. running.add(name); @@ -675,7 +768,8 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { if (container == null || !"running".equals(container.getState()) || !request.imageId().equals(container.getImageId()) || !joins(container.getNetworkSettings() != null ? container.getNetworkSettings().getNetworks() - : null, clusterSubnet(clusterId) != null ? request.joinedNetwork() : null)) { + : null, clusterSubnet(clusterId) != null ? request.joinedNetwork() : null) + || !metadataKnown(clusterId, name)) { startNode(request, node.host(), node.core(), name, teardown); } else { runningNodes.add(name); @@ -758,6 +852,10 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { if (subnet != null) { spec.withJoinedNetwork(request.joinedNetwork()).withEmbeddedDns().withEnv(SUBNET_VARIABLE, subnet); } + String address = nodeAddress(clusterId, name, name.substring(name.lastIndexOf("-node-") + "-node-".length())); + if (address != null) { + spec.withLinkLocalIp(address); + } if (core) { spec.withEnv(NODE_CORE_VARIABLE, "1"); } @@ -998,6 +1096,8 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { LOG.warnv(e, "Could not remove the EMR node container {0}: {1}", name, e.getMessage()); return false; } + // Its address goes only now, so no other container is given it while this one is there. + releaseNodeAddress(name); runningNodes.remove(name); archivedLogs.remove(name); return !withVolume || lifecycleManager.removeVolume(name); @@ -1163,6 +1263,10 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { if (subnet != null) { spec.withJoinedNetwork(network).withEmbeddedDns().withEnv(SUBNET_VARIABLE, subnet); } + String address = nodeAddress(clusterId, name, PRIMARY_NODE); + if (address != null) { + spec.withLinkLocalIp(address); + } } if (yarn != null) { spec.withEnv(YARN_MEMORY_VARIABLE, String.valueOf(yarn.memoryMb())) @@ -1395,13 +1499,18 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { nodesGone = false; } boolean containerGone = removeKnown(hdfsName(clusterId)); + // Its relay goes, trusted no more, and every address given on its network with it. + boolean relayGone = relays == null || relays.stop(clusterId); + identities.remove(clusterId); + String nodes = ContainerStorageHelper.dockerName(config, SERVICE + "-" + clusterId + "-node-"); + nodeAddresses.keySet().removeIf(name -> name.equals(hdfsName(clusterId)) || name.startsWith(nodes)); SparkJobRunner.Storage storage = volumes(clusterId); // Each is tried, so one Docker refused does not keep the others. boolean networkGone = lifecycleManager.removeNetwork(hdfsName(clusterId)); boolean homeGone = lifecycleManager.removeVolume(storage.home()); boolean mntGone = lifecycleManager.removeVolume(storage.mnt()); return lifecycleManager.removeVolume(hdfsName(clusterId)) && mntGone && homeGone && networkGone - && containerGone && nodesGone; + && containerGone && nodesGone && relayGone; } /** @@ -1434,6 +1543,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { LOG.warnv(e, "Could not remove the HDFS container {0}: {1}", name, e.getMessage()); return false; } + releaseNodeAddress(name); releaseSession(name); if (!detachFloci(name)) { return false; @@ -1486,6 +1596,21 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { } catch (RuntimeException e) { LOG.warnv(e, "Could not remove the HDFS of EMR clusters that have ended: {0}", e.getMessage()); } + // The instance metadata relays an earlier process left, whose networks they would keep: the next bootstrap or step + // of a cluster still up starts another. + try { + for (Container container : lifecycleManager.getDockerClient().listContainersCmd().withShowAll(true) + .withLabelFilter(Map.of(ContainerStorageHelper.COMPONENT_LABEL, EmrMetadataRelays.COMPONENT, + ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config))) + .exec()) { + Map labels = container.getLabels() != null ? container.getLabels() : Map.of(); + if (EmrMetadataRelays.COMPONENT.equals(labels.get(ContainerStorageHelper.COMPONENT_LABEL))) { + lifecycleManager.stopAndRemove(container.getId(), null, 0); + } + } + } catch (RuntimeException e) { + LOG.warnv(e, "Could not remove the instance metadata relays an earlier Floci left: {0}", e.getMessage()); + } try { for (Network network : lifecycleManager.getDockerClient().listNetworksCmd() .withFilter("label", List.of(ContainerStorageHelper.COMPONENT_LABEL + "=" + HDFS_COMPONENT, diff --git a/src/main/java/io/floci/aws/services/emr/EmrHandler.java b/src/main/java/io/floci/aws/services/emr/EmrHandler.java index 3ccbd8684b..32f9e8ef7b 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrHandler.java +++ b/src/main/java/io/floci/aws/services/emr/EmrHandler.java @@ -5,7 +5,6 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; -import io.floci.aws.core.common.AwsEndpoints; import io.floci.aws.core.common.AwsErrorResponse; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.AwsJson11Controller; @@ -161,7 +160,7 @@ public class EmrHandler { cluster.setKeepJobFlowAliveWhenNoSteps(instances.path("KeepJobFlowAliveWhenNoSteps").asBoolean(false)); cluster.setTerminationProtected(instances.path("TerminationProtected").asBoolean(false)); cluster.setUnhealthyNodeReplacement(instances.path("UnhealthyNodeReplacement").asBoolean(false)); - cluster.setEc2Attributes(buildEc2Attributes(instances)); + cluster.setEc2Attributes(buildEc2Attributes(instances, region)); cluster.setInstanceGroups(parseInstanceGroups(instances.path("InstanceGroups"))); cluster.setInstanceFleets(parseInstanceFleets(instances.path("InstanceFleets"))); cluster.setSteps(parseSteps(request.path("Steps"), text(request, "StepExecutionRoleArn"))); @@ -939,7 +938,7 @@ public class EmrHandler { ObjectNode node = objectMapper.createObjectNode(); node.put("Id", "ci-" + index + cluster.getId()); node.put("Ec2InstanceId", EmrService.ec2InstanceId(index)); - node.put("PublicDnsName", AwsEndpoints.ec2PublicDns("203.0.113." + index, cluster.getRegion())); + node.put("PublicDnsName", EmrService.publicDnsName(index, cluster.getRegion())); node.put("PrivateDnsName", AwsRegions.ec2PrivateIpDnsName(privateIp, cluster.getRegion())); node.put("PrivateIpAddress", privateIp); if (set.groupId() != null) { @@ -1086,14 +1085,22 @@ public class EmrHandler { return fleet; } - private String buildEc2Attributes(JsonNode instances) { + // The cluster's EC2 attributes, its availability zone among them: the one Placement names, the first of its + // AvailabilityZones, else the Region's first, as its instances' metadata gives it too. + private String buildEc2Attributes(JsonNode instances, String region) { ObjectNode ec2 = objectMapper.createObjectNode(); + JsonNode placement = instances.path("Placement"); + String zone = placement.path("AvailabilityZone").asText(""); + if (zone.isEmpty()) { + zone = placement.path("AvailabilityZones").path(0).asText(""); + } + ec2.put("Ec2AvailabilityZone", zone.isEmpty() ? region + "a" : zone); copyText(instances, "Ec2KeyName", ec2, "Ec2KeyName"); copyText(instances, "Ec2SubnetId", ec2, "Ec2SubnetId"); copyText(instances, "EmrManagedMasterSecurityGroup", ec2, "EmrManagedMasterSecurityGroup"); copyText(instances, "EmrManagedSlaveSecurityGroup", ec2, "EmrManagedSlaveSecurityGroup"); copyText(instances, "ServiceAccessSecurityGroup", ec2, "ServiceAccessSecurityGroup"); - return ec2.isEmpty() ? null : ec2.toString(); + return ec2.toString(); } private void copyText(JsonNode src, String srcField, ObjectNode dst, String dstField) { diff --git a/src/main/java/io/floci/aws/services/emr/EmrMetadataRelays.java b/src/main/java/io/floci/aws/services/emr/EmrMetadataRelays.java new file mode 100644 index 0000000000..df42cc2c0b --- /dev/null +++ b/src/main/java/io/floci/aws/services/emr/EmrMetadataRelays.java @@ -0,0 +1,269 @@ +package io.floci.aws.services.emr; + +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.ContainerTeardown; +import io.floci.aws.core.common.docker.ContainerBuilder; +import io.floci.aws.core.common.docker.ContainerExec; +import io.floci.aws.core.common.docker.ContainerLifecycleManager; +import io.floci.aws.core.common.docker.ContainerStorageHelper; +import io.floci.aws.services.ec2.Ec2MetadataServer; +import io.floci.aws.services.ec2.model.Instance; +import jakarta.enterprise.context.ApplicationScoped; +import org.jboss.logging.Logger; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** + * Instance metadata for a cluster's containers in the {@code docker} runner mode, at 169.254.169.254 as on the EC2 + * instances an EMR cluster runs on. A relay container on the cluster's own Docker network holds that address as a + * link-local one, as ECS's credentials proxy holds its own, and forwards each request to Floci's EC2 metadata server, + * naming its caller in {@code X-Forwarded-For} by the link-local address each of the cluster's containers is given + * there, so the server answers it as the instance that container is: the cluster's primary node for its bootstrap + * actions and its steps, a core or task node for that node's container. Only the cluster's own containers are on that + * network, and the server reads the header from the relays it trusts alone. + */ +@ApplicationScoped +public class EmrMetadataRelays implements ContainerTeardown { + + private static final Logger LOG = Logger.getLogger(EmrMetadataRelays.class); + /** The address of the instance metadata service, which a relay holds on its cluster's network. */ + static final String ADDRESS = "169.254.169.254"; + private static final String SERVICE = "emr"; + /** The component label of a cluster's relay container. */ + static final String COMPONENT = "emr-metadata"; + // How long a relay may take to listen once its container has started, a look every 100 ms. + private static final int READY_LOOKS = 100; + // The relay: an HTTP server on 169.254.169.254:80 that sends each request on to the metadata server ($1:$2) with + // the caller's address in X-Forwarded-For, in place of any the caller sent, and gives its answer back, an answer to + // HEAD with the length the server gave, as it has no body to count. + static final String RELAY_SCRIPT = String.join("\n", + "import http.client, http.server, socketserver, sys", + "TARGET = (sys.argv[1], int(sys.argv[2]))", + "DROPPED = ('host', 'x-forwarded-for', 'connection', 'content-length', 'transfer-encoding')", + "class Relay(http.server.BaseHTTPRequestHandler):", + " protocol_version = 'HTTP/1.1'", + " def relay(self):", + " length = int(self.headers.get('Content-Length') or 0)", + " body = self.rfile.read(length) if length else None", + " headers = {k: v for k, v in self.headers.items() if k.lower() not in DROPPED}", + " headers['X-Forwarded-For'] = self.client_address[0]", + " connection = http.client.HTTPConnection(*TARGET, timeout=30)", + " try:", + " connection.request(self.command, self.path, body=body, headers=headers)", + " answer = connection.getresponse()", + " data = answer.read()", + " except OSError:", + " self.send_error(502)", + " return", + " finally:", + " connection.close()", + " self.send_response(answer.status)", + " for k, v in answer.getheaders():", + " if k.lower() not in DROPPED:", + " self.send_header(k, v)", + " length = answer.getheader('Content-Length') if self.command == 'HEAD' else None", + " self.send_header('Content-Length', length if length is not None else str(len(data)))", + " self.end_headers()", + " if self.command != 'HEAD':", + " self.wfile.write(data)", + " do_GET = do_PUT = do_HEAD = do_POST = relay", + " def log_message(self, *args):", + " pass", + "class Server(socketserver.ThreadingMixIn, http.server.HTTPServer):", + " daemon_threads = True", + " allow_reuse_address = True", + "Server(('" + ADDRESS + "', 80), Relay).serve_forever()"); + // Ready once a connection to 169.254.169.254:80 is taken. + private static final String READY_PROBE = "import socket; socket.create_connection(('" + ADDRESS + "', 80), 1)"; + + private final ContainerBuilder containerBuilder; + private final ContainerLifecycleManager lifecycleManager; + private final Ec2MetadataServer metadataServer; + private final EmulatorConfig config; + // Each cluster's relay, by cluster id. + private final Map relays = new HashMap<>(); + // Each link-local address given, by address: whose it is. + private final Map given = new HashMap<>(); + // The clusters whose relay Docker kept, trusted no more, which the next stop removes. + private final Set left = new LinkedHashSet<>(); + + public EmrMetadataRelays(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager, + Ec2MetadataServer metadataServer, EmulatorConfig config) { + this.containerBuilder = containerBuilder; + this.lifecycleManager = lifecycleManager; + this.metadataServer = metadataServer; + this.config = config; + } + + /** + * Starts the relay of cluster {@code clusterId} on {@code network}, its own, which exists, in {@code image}, which + * has Python 3, unless it runs, sending requests to Floci's metadata server at {@code targetHost} as the network + * reaches Floci; the server trusts it from then on. + */ + public synchronized void start(String clusterId, String accountId, String region, String network, String image, + String targetHost) { + Relay known = relays.get(clusterId); + if (known != null && lifecycleManager.isContainerRunning(known.containerId())) { + return; + } + if (known != null) { + // One that has stopped is trusted no more before it goes, so whatever Docker gives its address is not. + relays.remove(clusterId); + metadataServer.distrustForwarder(known.address()); + } + if (!removeRelay(clusterId)) { + throw new IllegalStateException("Docker kept the instance metadata relay of EMR cluster " + clusterId); + } + String name = ContainerStorageHelper.dockerName(config, name(clusterId)); + Map labels = new LinkedHashMap<>(ContainerStorageHelper.resourceIdentityLabels(SERVICE, + clusterId, accountId, region)); + labels.put(ContainerStorageHelper.COMPONENT_LABEL, COMPONENT); + labels.put(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)); + String containerId = lifecycleManager.createAndStart(containerBuilder.newContainer(image) + .withName(name) + .withUser("root") + .withEntrypoint(List.of("python3", "-c", RELAY_SCRIPT, targetHost, + String.valueOf(config.services().ec2().imdsPort()))) + .withDockerNetwork(Optional.of(network)) + .withLinkLocalIp(ADDRESS) + .withHostDockerInternalOnLinux() + .withLogRotation() + .withLabels(labels) + .build()).containerId(); + try { + awaitListening(containerId); + String address = lifecycleManager.resolveContainerNetworkIp(containerId, network); + metadataServer.trustForwarder(address); + relays.put(clusterId, new Relay(containerId, address)); + LOG.infov("Started the instance metadata relay of EMR cluster {0} at {1} on {2}", clusterId, ADDRESS, + network); + } catch (RuntimeException e) { + removeRelay(clusterId); + throw e; + } + } + + /** Whether a relay this Floci started serves cluster {@code clusterId}'s network. */ + public synchronized boolean serves(String clusterId) { + return relays.containsKey(clusterId); + } + + /** + * A link-local address on cluster {@code clusterId}'s network for a container that is {@code instance}, which the + * metadata server answers for as that instance until {@link #release}. + */ + public synchronized String give(String clusterId, Instance instance) { + String address = free(); + given.put(address, new Given(clusterId, instance)); + metadataServer.reconcileClusterNodeAddresses(Set.copyOf(addressesOf(instance)), instance); + return address; + } + + /** The container given {@code address} has gone: the server answers for it no more. */ + public synchronized void release(String address) { + Given gone = given.remove(address); + if (gone == null) { + return; + } + List left = addressesOf(gone.instance()); + if (left.isEmpty()) { + metadataServer.unregisterInstance(gone.instance()); + } else { + metadataServer.reconcileClusterNodeAddresses(Set.copyOf(left), gone.instance()); + } + } + + /** + * Cluster {@code clusterId} has ended: its relay, trusted no more, goes, and every address given on its network. + * Whether the relay has gone: one Docker keeps is removed by the next stop. + */ + public synchronized boolean stop(String clusterId) { + Relay relay = relays.remove(clusterId); + if (relay != null) { + metadataServer.distrustForwarder(relay.address()); + } + List addresses = given.entrySet().stream() + .filter(entry -> entry.getValue().clusterId().equals(clusterId)).map(Map.Entry::getKey).toList(); + addresses.forEach(this::release); + return removeRelay(clusterId); + } + + /** Removes every relay this Floci started, so a reset or a shutdown orphans none. */ + @Override + public synchronized void stopManagedContainers() { + Set clusters = new LinkedHashSet<>(relays.keySet()); + clusters.addAll(left); + clusters.forEach(this::stop); + for (String address : List.copyOf(given.keySet())) { + release(address); + } + } + + // Removes cluster clusterId's relay container, by its name; one Docker keeps is left for the next stop. Whether it + // has gone. + private boolean removeRelay(String clusterId) { + try { + lifecycleManager.removeIfExistsStrict(ContainerStorageHelper.dockerName(config, name(clusterId))); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not remove the instance metadata relay of EMR cluster {0}: {1}", clusterId, + e.getMessage()); + left.add(clusterId); + return false; + } + left.remove(clusterId); + return true; + } + + private void awaitListening(String containerId) { + for (int look = 0; look < READY_LOOKS; look++) { + ContainerExec.Result probed = ContainerExec.run(lifecycleManager.getDockerClient(), containerId, + new String[] {"python3", "-c", READY_PROBE}, 5); + if (probed.exitCode() == 0) { + return; + } + if (!lifecycleManager.isContainerRunning(containerId)) { + break; + } + try { + Thread.sleep(100); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; + } + } + throw new IllegalStateException("The instance metadata relay " + containerId + " did not listen on " + ADDRESS); + } + + // The first link-local address not given, skipping the relay's own; the whole /16 is the networks' own. + private String free() { + for (int third = 0; third < 256; third++) { + for (int fourth = 1; fourth <= 254; fourth++) { + String candidate = "169.254." + third + "." + fourth; + if (!ADDRESS.equals(candidate) && !given.containsKey(candidate)) { + return candidate; + } + } + } + throw new IllegalStateException("No link-local address is left for an EMR cluster's container"); + } + + // The addresses given to containers that are instance. + private List addressesOf(Instance instance) { + return given.entrySet().stream().filter(entry -> entry.getValue().instance() == instance) + .map(Map.Entry::getKey).toList(); + } + + static String name(String clusterId) { + return "emr-" + clusterId + "-metadata"; + } + + private record Relay(String containerId, String address) {} + + private record Given(String clusterId, Instance instance) {} +} diff --git a/src/main/java/io/floci/aws/services/emr/EmrService.java b/src/main/java/io/floci/aws/services/emr/EmrService.java index 9685031dfc..da1b047d65 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrService.java @@ -6,6 +6,8 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.AwsEndpoints; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.AwsRegions; import io.floci.aws.core.common.ContainerTeardown; @@ -19,6 +21,9 @@ import io.floci.aws.core.common.StoredResourceArns; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.ec2.model.Instance; +import io.floci.aws.services.ec2.model.InstanceState; +import io.floci.aws.services.ec2.model.Placement; import io.floci.aws.services.emr.model.EmrBlockPublicAccess; import io.floci.aws.services.emr.model.EmrCluster; import io.floci.aws.services.emr.model.EmrErrorDetail; @@ -1570,6 +1575,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear if ((hive != null || application != null || command != null) && clusterStorage != null) { storage = clusterStorage.volumes(cluster.getId()); cluster.setStorageCreated(true); + String known = cluster.getId(); + clusterStorage.identify(known, node -> nodeIdentity(known, accountId, region, node)); } // The image a cluster's bootstrap left, which holds what its release's does; else a cluster with Hive's or // YARN's, which the step's thread makes, or the release's. @@ -1620,7 +1627,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear teardowns.get()); executing.add(stepKey(accountId, step.getId())); String containerLogs = yarn ? EmrSparkSteps.containerLogFolder(cluster) : null; - stepExecutor.execute(() -> runStep(job, launch, releaseImage, hdfs, containerLogs)); + Instance primary = nodeInstance(cluster, accountId, 0, 1); + stepExecutor.execute(() -> runStep(job, launch, releaseImage, hdfs, containerLogs, primary)); } @Override @@ -1633,7 +1641,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear // cluster with Hive's or YARN's image is made first, when it is not there yet, so a failure to make it fails the // step. private void runStep(SparkJobRunner.Job job, StepLaunch launch, Supplier releaseImage, - BiFunction hdfs, String containerLogs) { + BiFunction hdfs, String containerLogs, + Instance primary) { String failure; if (job == null) { failure = EmrSparkSteps.NOT_RUN; @@ -1641,14 +1650,20 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear SparkJobRunner.Outcome outcome; StepProgress progress = new StepProgress(launch); String image = null; + String address = null; try { image = releaseImage != null && !progress.cancelled() ? releaseImage.get() : null; SparkJobRunner.Job running = image != null ? job.inImage(image) : job; // The cluster's storage is there, its HDFS running, before its first step's container mounts it. A step - // a cancel, its cluster's end or a reset has passed does not start, so it makes none. + // a cancel, its cluster's end or a reset has passed does not start, so it makes none. Its container + // reads the primary node's instance metadata, as a step on EMR's primary node does. if (job.storage() != null && !progress.cancelled()) { clusterStorage.create(launch.clusterId(), launch.accountId(), launch.region()); - running = running.onStorage(hdfs.apply(running.imageTemplate(), progress::cancelled)); + MetadataPlace place = metadataPlace(launch.clusterId(), launch.accountId(), launch.region(), + running.imageTemplate(), running.releaseLabel(), primary); + address = place != null ? place.address() : null; + SparkJobRunner.Storage storage = hdfs.apply(running.imageTemplate(), progress::cancelled); + running = running.onStorage(address != null ? storage.withMetadataAddress(address) : storage); } outcome = sparkRunner.run(running, progress); } catch (ClusterStorage.Stopped e) { @@ -1665,10 +1680,14 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear outcome = SparkJobRunner.Outcome.couldNotStart(e.getMessage()); } } finally { - // Its containers have come and gone, or never came, so a newer image of its kind may remove this one. + // Its containers have come and gone, or never came, so a newer image of its kind may remove this one, + // and its address on the cluster's network may go to another. if (image != null) { releaseImages.released(image); } + if (address != null) { + clusterStorage.releaseMetadataAddress(address); + } } // A reset since the step started has swept the storage and wiped its cluster, so nothing would remove // volumes made, or mounted, after its sweep: they go now, the step's container being gone. @@ -1730,7 +1749,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear teardowns.get()); Supplier releaseImage = releaseImage(cluster); bootstrapping.add(clusterKey(accountId, cluster.getId())); - stepExecutor.execute(() -> runBootstrap(bootstrap, launch, releaseImage)); + Instance primary = nodeInstance(cluster, accountId, 0, 1); + stepExecutor.execute(() -> runBootstrap(bootstrap, launch, releaseImage, primary)); } @Override @@ -1911,19 +1931,57 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear return actions; } + /** + * A link-local address on the cluster's network, where its instance metadata relay, started first in the image the + * container runs, answers a container given it as {@code instance}; null where the cluster's containers have no + * such network. A relay that cannot start is thrown, so what would read it fails, as no EC2 instance runs without + * its metadata. + */ + private MetadataPlace metadataPlace(String clusterId, String accountId, String region, String imageTemplate, + String releaseLabel, Instance instance) { + if (clusterStorage == null || instance == null) { + return null; + } + try { + String network = clusterStorage.metadataNetwork(clusterId, accountId, region, + EmrServerlessSparkRunner.image(imageTemplate, releaseLabel), dockerNetwork); + String address = network == null ? null : clusterStorage.metadataAddress(clusterId, instance); + return address == null ? null : new MetadataPlace(network, address); + } catch (RuntimeException e) { + throw new IllegalStateException("The instance metadata of EMR cluster " + clusterId + " could not start: " + + e.getMessage(), e); + } + } + + /** Where a container reads its node's instance metadata: its link-local address on its cluster's network. */ + private record MetadataPlace(String network, String address) {} + // A cluster's bootstrap thread: its actions run to their end, which then ends its BOOTSTRAPPING. They run in // a cluster with Hive's image, which is made first when it is not there yet, unless the cluster ended, or a reset // removed it, before the thread ran; a failure to make it ends the cluster as one to run the bootstrap does. private void runBootstrap(BootstrapRunner.Bootstrap bootstrap, BootstrapLaunch launch, - Supplier releaseImage) { + Supplier releaseImage, Instance primary) { // A teardown since the bootstrap was handed off stops it as it does a step, before it runs or as it goes. BooleanSupplier cancelled = () -> teardowns.get() != launch.teardownsBefore() || !RequestScopes.callAs(launch.accountId(), launch.region(), () -> stillBootstrapping(launch)); BootstrapRunner.Outcome outcome; String image = null; + String address = null; + boolean metadataMade = false; try { image = releaseImage != null && !cancelled.getAsBoolean() ? releaseImage.get() : null; - outcome = bootstrapRunner.run(image != null ? bootstrap.inImage(image) : bootstrap, cancelled); + BootstrapRunner.Bootstrap running = image != null ? bootstrap.inImage(image) : bootstrap; + // The actions run as on the primary node, whose instance metadata they read. + MetadataPlace place = null; + if (!cancelled.getAsBoolean()) { + metadataMade = clusterStorage != null && primary != null + && clusterStorage.metadataServed(dockerNetwork); + place = metadataPlace(running.clusterId(), running.accountId(), running.region(), + running.imageTemplate(), running.releaseLabel(), primary); + } + address = place != null ? place.address() : null; + outcome = bootstrapRunner.run(place != null ? running.onMetadata(place.network(), place.address()) + : running, cancelled); } catch (RuntimeException e) { LOG.warnv(e, "The bootstrap actions of EMR cluster {0} could not run", launch.clusterId()); outcome = BootstrapRunner.Outcome.couldNotRun(e.getMessage()); @@ -1933,14 +1991,19 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear if (image != null) { releaseImages.released(image); } + if (address != null) { + clusterStorage.releaseMetadataAddress(address); + } } BootstrapRunner.Outcome ended = outcome; + boolean storageMade = metadataMade; // One that ended, however, after a teardown began ends as one Floci stopped, which starts no step: the // service's lock orders the two. AtomicBoolean tornDownSince = new AtomicBoolean(); RequestScopes.runAs(launch.accountId(), launch.region(), () -> run(() -> { tornDownSince.set(teardowns.get() != launch.teardownsBefore()); - bootstrapEnded(bootstrap, launch, tornDownSince.get() ? BootstrapRunner.Outcome.halted() : ended); + bootstrapEnded(bootstrap, launch, tornDownSince.get() ? BootstrapRunner.Outcome.halted() : ended, + storageMade); })); // An image it committed as the teardown began goes, as no cluster starts from it. if (tornDownSince.get() && ended.image() != null) { @@ -1962,10 +2025,18 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear * wipes it, and a restart ends it. */ private void bootstrapEnded(BootstrapRunner.Bootstrap bootstrap, BootstrapLaunch launch, - BootstrapRunner.Outcome outcome) { + BootstrapRunner.Outcome outcome, boolean storageMade) { Optional current = launch.launchedIn() == generation ? findCluster(launch.clusterId()) : Optional.empty(); Optional found = current.filter(EmrService::bootstrapsInContainer); + if (storageMade && current.isPresent() && !current.get().isStorageCreated()) { + // The network and the instance metadata relay its bootstrap had are the cluster's storage, which goes as + // the cluster ends, though no step of it runs, and now on one that ended meanwhile. + EmrCluster made = current.get(); + made.setStorageCreated(true); + clusterStore.put(made.getId(), made); + releaseStorage(made); + } if (outcome.stopped() && found.isPresent()) { return; } @@ -2037,6 +2108,11 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear return "i-" + String.format("%017d", index); } + /** The public DNS name ListInstances gives a cluster's instance {@code index}, counted from 1, in a Region. */ + static String publicDnsName(long index, String region) { + return AwsEndpoints.ec2PublicDns("203.0.113." + index, region); + } + /** * The private IPv4 address of the instance {@code ordinal}, counted from 1, of a cluster's instance group numbered * {@code group}: an instance keeps it while its cluster's other groups resize, as an EC2 instance does. @@ -2075,6 +2151,78 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear throw new IllegalArgumentException("The instance group or fleet is not one of the cluster's"); } + /** + * The EC2 instance that a cluster's instance {@code ordinal}, counted from 1, of its group or fleet numbered + * {@code group} is, as ListInstances gives it and its instance metadata answers: its id, the cluster's account as + * its owner, its instance type, private address and name, public name, the cluster's availability zone, and the + * cluster's EC2 instance profile ({@code JobFlowRole}). + */ + Instance nodeInstance(EmrCluster cluster, String accountId, int group, long ordinal) { + List listed = EmrHandler.listedInstances(cluster, false); + EmrHandler.ListedInstances primary = listed.stream().filter(set -> set.number() == 0).findFirst().orElse(null); + long next = primary == null ? 1 : 1 + primary.count(); + long index = ordinal; + String instanceType = null; + for (EmrHandler.ListedInstances set : listed) { + long first = set == primary ? 1 : next; + if (set != primary) { + next += set.count(); + } + if (set.number() == group) { + index = first + ordinal - 1; + instanceType = set.instanceType(); + break; + } + } + Instance instance = new Instance(); + instance.setInstanceId(ec2InstanceId(index)); + instance.setOwnerId(accountId); + instance.setInstanceType(instanceType); + instance.setImageId(cluster.getCustomAmiId()); + String address = privateIpAddress(group, ordinal); + instance.setPrivateIpAddress(address); + instance.setPrivateDnsName(AwsRegions.ec2PrivateIpDnsName(address, cluster.getRegion())); + instance.setPublicDnsName(publicDnsName(index, cluster.getRegion())); + instance.setPlacement(new Placement(availabilityZone(cluster))); + instance.setRegion(cluster.getRegion()); + instance.setState(InstanceState.running()); + String profile = cluster.getJobFlowRole(); + if (profile != null && !profile.isBlank()) { + instance.setIamInstanceProfileArn(AwsArnUtils.looksLikeArn(profile) ? profile + : AwsArnUtils.Arn.global(regionResolver.partitionForRegion(cluster.getRegion()), "iam", accountId, + "instance-profile/" + profile).toString()); + // As IAM shapes a profile's id, which the metadata reports where IAM holds no such profile. + instance.setIamInstanceProfileId("AIPA" + instance.getInstanceId().substring(2)); + } + return instance; + } + + // The EC2 instance a cluster's node, named as ClusterStorage.identify has it, is as the cluster stands now; null for + // a cluster that is gone. + private Instance nodeIdentity(String clusterId, String accountId, String region, String node) { + int dash = node.indexOf('-'); + int group = Integer.parseInt(node.substring(0, dash)); + long ordinal = Long.parseLong(node.substring(dash + 1)); + return RequestScopes.callAs(accountId, region, () -> call(() -> clusterStore.get(clusterId) + .map(cluster -> nodeInstance(cluster, accountId, group, ordinal)).orElse(null))); + } + + /** + * The availability zone a cluster's instances are in: the one DescribeCluster's {@code Ec2InstanceAttributes} gives, + * else its Region's first. + */ + static String availabilityZone(EmrCluster cluster) { + String recorded = null; + if (cluster.getEc2Attributes() != null) { + try { + recorded = SNAPSHOT_MAPPER.readTree(cluster.getEc2Attributes()).path("Ec2AvailabilityZone").asText(null); + } catch (JsonProcessingException ignored) { + // RunJobFlow stored them as an object; one an earlier Floci stored without a zone gets the Region's. + } + } + return recorded != null && !recorded.isBlank() ? recorded : cluster.getRegion() + "a"; + } + // The primary instance's: the first of the MASTER group or fleet, which ListInstances numbers before the others. static String masterInstanceId(EmrCluster cluster) { return ec2InstanceId(1); diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java index 9af16a66b1..0130e23611 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java @@ -551,10 +551,13 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo launch.started(containerId); // A cluster's HDFS is on a network of its own, which only its steps join; on YARN the executors there reach // the driver at the name its container has on it. + // With an address there, the cluster's instance metadata relay answers it as the cluster's primary node. if (onYarn) { - lifecycleManager.ensureConnected(containerId, job.storage().hdfsNetwork(), driverHost(job)); + lifecycleManager.ensureConnected(containerId, job.storage().hdfsNetwork(), driverHost(job), + job.storage().metadataAddress()); } else if (job.storage() != null && job.storage().hdfsNetwork() != null) { - lifecycleManager.connectToNetwork(containerId, job.storage().hdfsNetwork()); + lifecycleManager.connectToNetwork(containerId, job.storage().hdfsNetwork(), + job.storage().metadataAddress()); } // A stop, a reset or a shutdown while the image was pulled, the trust store copied or the archives put // in is read now, before the driver starts; one before an archive or while it streams in puts in no diff --git a/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java b/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java index cd5f4727fd..b10fa55fde 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java +++ b/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java @@ -176,7 +176,8 @@ public interface SparkJobRunner { * nodes hold it, else 0. */ record Storage(String home, String mnt, String hdfsHost, String hdfsAddress, String hdfsNetwork, - String hiveMetastore, String resourceManager, String flociEndpoint, int replication) { + String hiveMetastore, String resourceManager, String flociEndpoint, int replication, + String metadataAddress) { /** * The component label of an EMR cluster's HDFS container, which carries its service's labels as a driver @@ -189,19 +190,19 @@ public interface SparkJobRunner { /** A cluster's volumes, before its HDFS runs. */ public Storage(String home, String mnt) { - this(home, mnt, null, null, null, null, null, null, 0); + this(home, mnt, null, null, null, null, null, null, 0, null); } /** This storage, its HDFS's NameNode on {@code host}, at {@code address} on {@code network}. */ public Storage withHdfs(String host, String address, String network) { return new Storage(home, mnt, host, address, network, hiveMetastore, resourceManager, flociEndpoint, - replication); + replication, metadataAddress); } /** This storage, its Hive metastore service at {@code uri}. */ public Storage withHiveMetastore(String uri) { return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, uri, resourceManager, flociEndpoint, - replication); + replication, metadataAddress); } /** @@ -210,13 +211,22 @@ public interface SparkJobRunner { */ public Storage withYarn(String host, String flociEndpoint) { return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, hiveMetastore, host, flociEndpoint, - replication); + replication, metadataAddress); } /** This storage, its HDFS keeping {@code copies} copies of a block on its core nodes. */ public Storage withReplication(int copies) { return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, hiveMetastore, resourceManager, - flociEndpoint, copies); + flociEndpoint, copies, metadataAddress); + } + + /** + * This storage, the step's container given {@code address}, a link-local one, on the HDFS's network, where its + * cluster's instance metadata relay answers it as the cluster's primary node. + */ + public Storage withMetadataAddress(String address) { + return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, hiveMetastore, resourceManager, + flociEndpoint, replication, address); } } diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2MetadataForwarderTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2MetadataForwarderTest.java new file mode 100644 index 0000000000..d27525e0ae --- /dev/null +++ b/src/test/java/io/floci/aws/services/ec2/Ec2MetadataForwarderTest.java @@ -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 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 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 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 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 refused = get("/latest/meta-data/instance-id", CALLER, null); + + assertEquals(404, refused.statusCode()); + } + + private HttpResponse 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()); + } +} diff --git a/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java b/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java index 7e74dc06bd..48817327d2 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java @@ -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 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> 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 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)); diff --git a/src/test/java/io/floci/aws/services/emr/EmrIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrIntegrationTest.java index 4bf1475d4a..6fc0fd988a 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrIntegrationTest.java @@ -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); + } + } } diff --git a/src/test/java/io/floci/aws/services/emr/EmrMetadataRelaysTest.java b/src/test/java/io/floci/aws/services/emr/EmrMetadataRelaysTest.java new file mode 100644 index 0000000000..cb68bca430 --- /dev/null +++ b/src/test/java/io/floci/aws/services/emr/EmrMetadataRelaysTest.java @@ -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 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 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 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 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; + } +} diff --git a/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java b/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java index ee7dd5a2df..9fc20896d3 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java @@ -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); diff --git a/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java b/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java index 43e87263d9..0decb4bd1c 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java @@ -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 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> relays = new ArrayList<>(); + final List given = new ArrayList<>(); + final List released = new ArrayList<>(); + // How each cluster's nodes are known as EC2 instances. + final Map> 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 nodes) { + identities.put(clusterId, nodes); + } @Override public SparkJobRunner.Storage volumes(String clusterId) { diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java index a4ed62768b..db3129c3d8 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java @@ -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 arguments) -> arguments.contains("spark.hadoop.fs.s3a.endpoint=http://floci-on-cluster:4566")