diff --git a/docs/services/emr.md b/docs/services/emr.md index 823709526e..cbdd68f329 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -222,9 +222,17 @@ holding the driver and its executors, or a command or a script. The cluster itse settings, as EMR's primary node does, so a `hive-site` setting of `hive.metastore.warehouse.dir`, say, holds for the service as for the Hive steps. A primary node with the service that an earlier Floci left running starts again, on the data its volume keeps, as its session went with that Floci. The container is on a Docker network of the cluster's own, also - `emr--hdfs`, which the cluster's steps join besides their own, so the steps of other clusters, another - account's included, cannot reach its files or tables; each cluster whose HDFS runs takes one network from the - Docker daemon's address pools. When Floci runs in a container, that container joins the network of each cluster + `emr--hdfs`, which the cluster's steps join besides their own, where the cluster's nodes and steps reach + it by the primary node's name; each cluster whose HDFS runs takes one network from the Docker daemon's address pools. + Each of the cluster's nodes, this one and its core and task nodes (see **YARN**), is on the steps' network too, the + one Floci's other containers are on, from before it starts, with Floci's DNS, as a cluster's nodes reach what is in + their VPC: a cluster-mode driver or an executor reaches an MSK cluster's brokers or an RDS instance by the endpoints + Floci gives, and a virtual-hosted bucket name under Floci's host name, as Iceberg's `S3FileIO` uses by default, + resolves to Floci. The nodes' HDFS and YARN listen on their address on the cluster's network alone, so a container on + the steps' network, another cluster's included, reaches neither. Hive 3's metastore has no setting for the address it + listens on, so on a cluster with Hive or HCatalog the primary node, which runs it, stays on the cluster's network + alone, and the executors YARN runs there, on such a cluster with no core node, reach Floci at its address on the + cluster's network. Where Docker does not say the subnet of the cluster's network, its nodes stay on it alone. A node an earlier Floci started on the cluster's network alone starts again, on its data. When Floci runs in a container, that container joins the network of each cluster with Hive too, as `floci`, which is how the metastore reaches Floci's S3, and leaves it when the HDFS container goes. The cluster's first step starts it, and waits for it: a step whose cluster's HDFS is not ready within two minutes fails ("The step could not start: The HDFS of EMR cluster ... did not start within 120 seconds"). If its @@ -274,10 +282,11 @@ holding the driver and its executors, or a command or a script. The cluster itse offers `yarn-node-memory-mb` and `yarn-node-vcores`, 4096 MB and 4 by default, and an executor is 1 GB and one core and a driver 2 GB and one core, which the cluster's `spark-defaults` and a step's own options replace. A container larger than the NodeManager offers is refused by YARN, and its step fails. Dynamic allocation is on, as it is on - EMR, through Spark's shuffle tracking: the images have no external shuffle service. Executors reach Floci's S3 at - Floci's address on the cluster's network, which Floci's container joins as for the metastore (see **Storage**), over - HTTP, which Floci serves beside HTTPS with TLS on, so no certificate is involved, with the step's AWS credentials, - and find the driver at its container's name on that network. + EMR, through Spark's shuffle tracking: the images have no external shuffle service. Executors reach Floci's S3 as the + steps do, their node being on the steps' network (see **Storage**), or, where the steps have no network of Floci's, + at Floci's address on the cluster's network, which Floci's container joins as for the metastore, over HTTP, which + Floci serves beside HTTPS with TLS on, so no certificate is involved, with the step's AWS credentials, and find the + driver at its container's name on the cluster's network. Each core and task node is a container of its own on that network, `emr--node--`, with its data in a volume of its own: "Core nodes run the Data Node daemon", "a core node runs YARN NodeManager daemons, Hadoop MapReduce tasks, and Spark executors", and "Task nodes don't run the Data Node daemon". Its name on the network is the diff --git a/src/main/java/io/floci/aws/core/common/docker/ContainerBuilder.java b/src/main/java/io/floci/aws/core/common/docker/ContainerBuilder.java index 20ae72ef1b..03dc2d75b3 100644 --- a/src/main/java/io/floci/aws/core/common/docker/ContainerBuilder.java +++ b/src/main/java/io/floci/aws/core/common/docker/ContainerBuilder.java @@ -230,6 +230,7 @@ public class ContainerBuilder { private Long memorySwappiness; private boolean javaTrustStore; private String dnsName; + private final List joinedNetworks = new ArrayList<>(); Builder(String image, EmulatorConfig config, DockerHostResolver dockerHostResolver, EmbeddedDnsServer embeddedDnsServer, @@ -444,6 +445,17 @@ public class ContainerBuilder { return this; } + /** + * Joins the container to {@code network} too, a user-defined network, before it starts, with no alias of its + * own there, so it reaches the containers on that network from its first moment. + */ + public Builder withJoinedNetwork(String network) { + if (network != null && !network.isBlank() && !joinedNetworks.contains(network)) { + joinedNetworks.add(network); + } + return this; + } + /** * Sets the Docker network from a service-specific Optional, falling back to * the global services.dockerNetwork() if not present. @@ -861,7 +873,8 @@ public class ContainerBuilder { new LinuxOptions(List.copyOf(capAdd), List.copyOf(capDrop), List.copyOf(devices), shmSizeBytes, Map.copyOf(tmpfs), memorySwapBytes, memorySwappiness), javaTrustStore, - dnsName + dnsName, + List.copyOf(joinedNetworks) ); } } 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 78947d3461..71a518e621 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 @@ -250,6 +250,15 @@ public class ContainerLifecycleManager { "Failed to attach pre-start network configuration for container " + containerId, e); } } + for (String network : spec.joinedNetworks()) { + try { + dockerClient.connectToNetworkCmd().withContainerId(containerId).withNetworkId(network).exec(); + } catch (RuntimeException e) { + removeFailedContainer(containerId, e, removeAnonymousVolumes); + throw new IllegalStateException("Could not connect container " + containerId + " to Docker network " + + network + ": " + e.getMessage(), e); + } + } return containerId; } diff --git a/src/main/java/io/floci/aws/core/common/docker/ContainerSpec.java b/src/main/java/io/floci/aws/core/common/docker/ContainerSpec.java index 05473905cd..6c445c1b4c 100644 --- a/src/main/java/io/floci/aws/core/common/docker/ContainerSpec.java +++ b/src/main/java/io/floci/aws/core/common/docker/ContainerSpec.java @@ -53,6 +53,8 @@ import java.util.regex.Pattern; * store goes in beside the bundle, and {@code JAVA_TOOL_OPTIONS} points at it * @param dnsName The container's host name, and its alias on the user-defined network it joins at creation, so other * containers there reach it by that name (null = Docker's own) + * @param joinedNetworks Further user-defined networks the container joins before it starts, with no alias of its own + * there (empty = none) */ public record ContainerSpec( String image, @@ -86,7 +88,8 @@ public record ContainerSpec( boolean init, LinuxOptions linuxOptions, boolean javaTrustStore, - String dnsName + String dnsName, + List joinedNetworks ) { private static final Pattern LINK_LOCAL_IPV4 = Pattern.compile("^169\\.254\\.(\\d{1,3})\\.(\\d{1,3})$"); private static final Set NETWORKS_WITHOUT_ENDPOINT_IPAM = Set.of("bridge", "default", "host", "none"); @@ -96,6 +99,7 @@ public record ContainerSpec( if (linuxOptions == null) { linuxOptions = LinuxOptions.NONE; } + joinedNetworks = joinedNetworks == null ? List.of() : List.copyOf(joinedNetworks); if (linkLocalIps != null && !linkLocalIps.isEmpty()) { requireUserDefinedNetwork(networkMode); linkLocalIps.forEach(ContainerSpec::requireLinkLocalIpv4); @@ -110,7 +114,52 @@ public record ContainerSpec( this(image, null, List.of(), null, null, null, Map.of(), List.of(), List.of(), null, List.of(), List.of(), List.of(), List.of(), Map.of(), null, false, null, List.of(), null, null, List.of(), List.of(), null, null, false, List.of(), Map.of(), false, LinuxOptions.NONE, - false, null); + false, null, List.of()); + } + + /** + * Backward-compatible constructor that joins the container to no network but its own, so callers that predate + * {@code joinedNetworks} keep their existing behaviour. + */ + public ContainerSpec( + String image, + String name, + List env, + List cmd, + List entrypoint, + Long memoryBytes, + Map portBindings, + List loopbackPortBindings, + List exposedPorts, + String networkMode, + List mounts, + List binds, + List volumesFrom, + List extraHosts, + Map labels, + LogConfig logConfig, + boolean privileged, + String cgroupnsMode, + List dnsServers, + String workingDir, + String user, + List groupAdd, + List deviceRequests, + Long nanoCpus, + Integer cpuShares, + boolean readonlyRootfs, + List linkLocalIps, + Map portBindingHostIps, + boolean init, + LinuxOptions linuxOptions, + boolean javaTrustStore, + String dnsName + ) { + this(image, name, env, cmd, entrypoint, memoryBytes, portBindings, loopbackPortBindings, + exposedPorts, networkMode, mounts, binds, volumesFrom, extraHosts, labels, logConfig, + privileged, cgroupnsMode, dnsServers, workingDir, user, groupAdd, deviceRequests, + nanoCpus, cpuShares, readonlyRootfs, linkLocalIps, portBindingHostIps, init, linuxOptions, + javaTrustStore, dnsName, List.of()); } /** 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 6f588fc049..7dcd784422 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java +++ b/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java @@ -4,6 +4,7 @@ import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.command.InspectVolumeResponse; import com.github.dockerjava.api.command.ListVolumesResponse; import com.github.dockerjava.api.model.Container; +import com.github.dockerjava.api.model.ContainerNetwork; import com.github.dockerjava.api.model.HostConfig; import com.github.dockerjava.api.model.Network; import io.floci.aws.config.EmulatorConfig; @@ -65,7 +66,14 @@ import java.util.zip.GZIPOutputStream; * metastore service, as EMR's primary node does, with its database in that third volume, reaching S3 with a session * for the cluster's instance profile's role, which goes with the container. Where it has core nodes, "Core nodes run * the Data Node daemon" and "a core node runs YARN NodeManager daemons", and "Task nodes don't run the Data Node - * daemon", each is a container of its own on the cluster's network, with its data in a volume of its own. + * daemon", each is a container of its own on the cluster's network, with its data in a volume of its own. Each node is + * on the network the cluster's steps run on too, the one Floci's other containers are on, MSK's brokers and RDS's + * databases among them, from before it starts, with Floci's DNS, so a cluster-mode driver or an executor on it reaches + * them by the endpoints Floci gives, as a cluster's nodes reach what is in their VPC, and a virtual-hosted bucket name + * under Floci's host name resolves. Their HDFS and YARN listen on their address on the cluster's network alone (see + * BIND_SETUP), so that network's other containers reach neither; Hive 3's metastore has no setting for the address it + * listens on, so the primary node of a cluster with Hive or HCatalog, which runs it, stays off that network, and so does + * every node where Docker does not say the subnet of the cluster's network. */ @ApplicationScoped public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { @@ -80,10 +88,16 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { private static final String CONTAINER_NETWORK_PREFIX = "container:"; private static final String NO_NETWORK = "none"; private static final String LOOPBACK = "127.0.0.1"; + // The address a node's daemons listen on, which its start writes here for what asks them later (see BIND_SETUP). + private static final String BIND_FILE = "/tmp/floci-hdfs-bind"; + private static final String BIND = "$(cat " + BIND_FILE + ")"; + // The subnet of the cluster's own network, set where its node joins the steps' network too, whose containers then do + // not reach the node's daemons, which listen on its address on the cluster's network alone. + private static final String SUBNET_VARIABLE = "FLOCI_HDFS_SUBNET"; // The NameNode's JMX on its web port, which says when the DataNode has joined and safe mode has ended without // starting a JVM of hdfs's own each time it is asked; each look is given five seconds, so one the NameNode does not // answer while it starts is asked again. - private static final String NAMENODE_JMX = "http://127.0.0.1:9870/jmx?qry=Hadoop:service=NameNode,name="; + private static final String NAMENODE_JMX = "http://" + BIND + ":9870/jmx?qry=Hadoop:service=NameNode,name="; // The metastore service's --hiveconf settings, Floci's S3 among them; set only on a cluster with Hive or // HCatalog. private static final String HIVE_METASTORE_VARIABLE = "FLOCI_HIVE_METASTORE"; @@ -116,8 +130,8 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { private static final String DFS_EXCLUDE = HDFS_CONF + "/dfs.exclude"; private static final String YARN_EXCLUDE = HDFS_CONF + "/yarn.exclude"; // The ResourceManager's cluster metrics on its web port, which say when the NodeManager has registered. - private static final String RESOURCE_MANAGER_METRICS = "http://127.0.0.1:8088/ws/v1/cluster/metrics"; - private static final String RESOURCE_MANAGER_NODES = "http://127.0.0.1:8088/ws/v1/cluster/nodes?states="; + private static final String RESOURCE_MANAGER_METRICS = "http://" + BIND + ":8088/ws/v1/cluster/metrics"; + private static final String RESOURCE_MANAGER_NODES = "http://" + BIND + ":8088/ws/v1/cluster/nodes?states="; // Where a NodeManager keeps its containers' logs, on the node's volume, as //. private static final String YARN_LOGS = "/mnt/yarn/logs"; private static final int LOG_LISTING_SECONDS = 30; @@ -241,7 +255,26 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // NodeManager has registered. A daemon that exits, before or after, the metastore among them, ends the container, // its readiness gone, so the next step starts it again on its data. With HADOOP_FOLDER_VARIABLE set, every daemon // runs from the Hadoop in that folder. + // Where a node's daemons listen: FLOCI_HDFS_BIND, or, with SUBNET_VARIABLE set, the node's own address in that subnet, + // its cluster's network, alone, so another network it joins does not reach its HDFS or its YARN; written to + // BIND_FILE. Hive 3's metastore has no setting for the address it listens on, so it takes every one. + private static final String BIND_SETUP = String.join("\n", + "if [ -n \"${" + SUBNET_VARIABLE + ":-}\" ]; then", + " int() { local IFS=.; set -- $1; echo $(( ($1 << 24) + ($2 << 16) + ($3 << 8) + $4 )); }", + " net=${" + SUBNET_VARIABLE + "%/*} bits=${" + SUBNET_VARIABLE + "#*/}", + " mask=$(( (0xFFFFFFFF << (32 - bits)) & 0xFFFFFFFF ))", + " for a in $(hostname -I); do", + " case \"$a\" in *:*) continue ;; esac", + " [ $(( $(int \"$a\") & mask )) -ne $(( $(int \"$net\") & mask )) ] || FLOCI_HDFS_BIND=$a", + " done", + " if [ \"$FLOCI_HDFS_BIND\" = 0.0.0.0 ]; then", + " echo \"Floci: no address of this node is in $" + SUBNET_VARIABLE + "\" >&2; exit 1", + " fi", + " export FLOCI_HDFS_BIND", + "fi", + "echo \"$FLOCI_HDFS_BIND\" > " + BIND_FILE + " || exit"); private static final String HDFS_SCRIPT = String.join("\n", + BIND_SETUP, "address=$FLOCI_HDFS_BIND; [ \"$address\" != 0.0.0.0 ] || address=$(hostname -i | awk '{print $1}')", "echo \"$address $FLOCI_HDFS_HOST\" >> /etc/hosts || exit", NODE_SETUP, @@ -304,6 +337,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // by its name on the cluster's network and register under the node's own. It is ready once the ResourceManager, and // on a core node the NameNode, knows it. A daemon that exits ends the container, as on the primary node. private static final String NODE_SCRIPT = String.join("\n", + BIND_SETUP, NODE_SETUP, "exec setpriv --reuid=hadoop --regid=hadoop --clear-groups bash -c '" + "n=1; if [ -n \"$" + NODE_CORE_VARIABLE + "\" ]; then hdfs datanode & n=2; fi; " @@ -352,6 +386,8 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { private final S3Service s3Service; private final Duration hdfsStartTimeout; private final LongSupplier nanoTime; + // The subnet of each cluster's own network, once read (see clusterSubnet). + private final Map subnets = 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(); @@ -546,7 +582,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // Read here, so a resize before this took the lock counts, and one after it waits and finds these nodes. Yarn yarn = yarnNow != null ? yarnNow.get() : null; NodeRequest nodeRequest = yarn == null ? null - : new NodeRequest(clusterId, accountId, region, host, imageId, yarn); + : new NodeRequest(clusterId, accountId, region, host, imageId, yarn, shared ? null : network); String containerId = null; List nodes = List.of(); // One found running whose daemon has just exited stops before it is ready, and is started again, once. @@ -559,7 +595,9 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { + " runs"); } boolean found = liveness == ContainerLiveness.RUNNING && attempt == 0 - && inStepsNamespace(name, shared ? network : name, imageId) + && inStepsNamespace(name, shared ? network : name, + shared || hiveMetastore != null || clusterSubnet(clusterId) == null ? null : network, + imageId) && (shared || hiveMetastore == null || metastoreCurrent(name)); // Known before it starts, so a teardown while it starts removes it. running.add(name); @@ -590,8 +628,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { if (yarn == null) { return storage; } - // Its executors reach Floci's S3 from the node, at Floci's address on the cluster's network. - storage = storage.withYarn(host, flociEndpointOn(name)); + // Its executors reach Floci's S3 from the node as the steps do, the node being on their network too, else + // at Floci's address on the cluster's network. + boolean everyWorkerJoined = network != null && clusterSubnet(clusterId) != null + && (hiveMetastore == null || !yarn.primaryWorks()); + storage = storage.withYarn(host, everyWorkerJoined ? awsEnv.flociEndpoint() : flociEndpointOn(name)); return yarn.nodes().stream().anyMatch(Node::core) ? storage.withReplication(yarn.replication()) : storage; } } @@ -632,7 +673,9 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { changed |= leaving.remove(name) != null; Container container = present.get(name); if (container == null || !"running".equals(container.getState()) - || !request.imageId().equals(container.getImageId())) { + || !request.imageId().equals(container.getImageId()) + || !joins(container.getNetworkSettings() != null ? container.getNetworkSettings().getNetworks() + : null, clusterSubnet(clusterId) != null ? request.joinedNetwork() : null)) { startNode(request, node.host(), node.core(), name, teardown); } else { runningNodes.add(name); @@ -711,6 +754,10 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // Its executors reach Floci, Floci on the host by its address, Floci's own certificate trusted. .withHostDockerInternalOnLinux() .withJavaTrustStore(); + String subnet = request.joinedNetwork() != null ? clusterSubnet(clusterId) : null; + if (subnet != null) { + spec.withJoinedNetwork(request.joinedNetwork()).withEmbeddedDns().withEnv(SUBNET_VARIABLE, subnet); + } if (core) { spec.withEnv(NODE_CORE_VARIABLE, "1"); } @@ -910,13 +957,13 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { startNode(request, node.host(), true, name, teardown); return false; } - return node.hdfsDone() && onPrimary(request.clusterId(), "curl -sf -m 5 '" + RESOURCE_MANAGER_NODES - + "DECOMMISSIONED' | grep -q '\"nodeHostName\":\"" + node.host() + "\"'"); + return node.hdfsDone() && onPrimary(request.clusterId(), "curl -sf -m 5 \"" + RESOURCE_MANAGER_NODES + + "DECOMMISSIONED\" | grep -q '\"nodeHostName\":\"" + node.host() + "\"'"); } // Whether HDFS has moved a core node's blocks to the nodes that stay. private boolean hdfsDecommissioned(String clusterId, Draining node) { - return onPrimary(clusterId, "curl -sf -m 5 '" + NAMENODE_JMX + "NameNodeInfo' | grep -Eq '" + node.host() + return onPrimary(clusterId, "curl -sf -m 5 \"" + NAMENODE_JMX + "NameNodeInfo\" | grep -Eq '" + node.host() + ":9866[^}]*Decommissioned'"); } @@ -957,10 +1004,10 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { } private record NodeRequest(String clusterId, String accountId, String region, String host, String imageId, - Yarn yarn) { + Yarn yarn, String joinedNetwork) { NodeRequest resizedTo(Yarn resized) { - return new NodeRequest(clusterId, accountId, region, host, imageId, resized); + return new NodeRequest(clusterId, accountId, region, host, imageId, resized, joinedNetwork); } } @@ -1001,12 +1048,20 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // cluster's own network, the host's, or the same container's, and of the image they run in; one a process with // another docker-network left, or one of another image, an earlier Floci's in the Hive image, goes, and starts // again on its data. - private boolean inStepsNamespace(String name, String stepsNetwork, String imageId) { + private boolean inStepsNamespace(String name, String stepsNetwork, String joinedNetwork, String imageId) { InspectContainerResponse container = lifecycleManager.getDockerClient().inspectContainerCmd(name).exec(); HostConfig hostConfig = container.getHostConfig(); String networkMode = hostConfig != null ? hostConfig.getNetworkMode() : null; return Objects.equals(namespaceOf(networkMode), namespaceOf(stepsNetwork)) - && imageId.equals(container.getImageId()); + && imageId.equals(container.getImageId()) + && joins(container.getNetworkSettings() != null ? container.getNetworkSettings().getNetworks() : null, + joinedNetwork); + } + + // Whether a node's container is on the network its cluster's steps run on too, as one an earlier Floci started on + // its cluster's network alone is not; true where it need not be. + private static boolean joins(Map networks, String joinedNetwork) { + return joinedNetwork == null || networks != null && networks.containsKey(joinedNetwork); } // The namespace a network mode puts a container in, the same for a container's name and its id: the network, @@ -1053,10 +1108,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // A cluster's HDFS container, started anew on the HDFS data its volume holds, which goes with the cluster's other // two, with its metastore service when asked; one a restart, a stop or a daemon's exit left goes first. It runs on - // a Docker network of the cluster's own, which only the cluster's steps join, as its HDFS and its metastore serve - // its files and tables to any client that reaches them: the steps of other clusters, of other accounts too, do - // not. In a namespace the steps share it listens on the loopback alone, and the metastore does not run, as Hive 3's - // has no setting for the address it listens on: it would serve every interface, the host's own for one. + // a Docker network of the cluster's own, where its nodes and steps reach it by its name, and joins the steps' + // network too, as the other nodes do, its HDFS on its address on the cluster's network alone, unless it runs the + // metastore, which listens on every one (see the class's comment). In a namespace the steps share it listens on the + // loopback alone, and the metastore does not run, + // as Hive 3's has no setting for the address it listens on: it would serve every interface, the host's own for one. private String start(String clusterId, String accountId, String region, String host, String imageId, String dockerNetwork, HiveMetastore hiveMetastore, Yarn yarn) { String network = network(dockerNetwork); @@ -1102,6 +1158,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { if (!shared) { // Its core and task nodes reach it by its name on the network, which a new address does not change. spec.withDnsName(host); + // With its metastore, which Hive 3 lets listen on every address alone, it stays off the steps' network. + String subnet = network != null && hiveMetastore == null ? clusterSubnet(clusterId) : null; + if (subnet != null) { + spec.withJoinedNetwork(network).withEmbeddedDns().withEnv(SUBNET_VARIABLE, subnet); + } } if (yarn != null) { spec.withEnv(YARN_MEMORY_VARIABLE, String.valueOf(yarn.memoryMb())) @@ -1145,6 +1206,34 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { return containerId; } + // The subnet of a cluster's own network, which exists, as Docker says it: where it is known, the cluster's nodes join + // the steps' network too, their HDFS and YARN listening on their address in that subnet alone (see BIND_SETUP), so + // the steps' network's containers, other clusters' among them, reach neither; where it is not, they stay on their + // cluster's network alone, as is logged. Kept once read, for the network keeps it. + private String clusterSubnet(String clusterId) { + String known = subnets.get(clusterId); + if (known != null) { + return known; + } + String network = hdfsName(clusterId); + String subnet = null; + try { + Network inspected = lifecycleManager.getDockerClient().inspectNetworkCmd().withNetworkId(network).exec(); + if (inspected != null && inspected.getIpam() != null && inspected.getIpam().getConfig() != null + && !inspected.getIpam().getConfig().isEmpty()) { + subnet = inspected.getIpam().getConfig().getFirst().getSubnet(); + } + } catch (RuntimeException e) { + LOG.debugv(e, "Could not read the subnet of Docker network {0}: {1}", network, e.getMessage()); + } + if (subnet == null || !subnet.contains(".")) { + LOG.warnv("The nodes of EMR cluster {0} stay on its network alone, as its subnet is not known", clusterId); + return null; + } + subnets.put(clusterId, subnet); + return subnet; + } + // Where the metastore service, on the cluster's network, which Docker keeps apart from Floci's, reaches Floci's // S3: Floci on the host at the host's address, as the steps reach it; Floci in a container of its own as // FLOCI_ALIAS, its container joining the cluster's network, as it joins the networks of EC2 VPCs. @@ -1287,6 +1376,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // Its HDFS goes first, as its container holds the volume of its data and its network, and its lock with it, so // the clusters that have ended leave none behind. starting.remove(clusterId); + subnets.remove(clusterId); nodeRequests.remove(clusterId); draining.remove(clusterId); departed.remove(clusterId); diff --git a/src/test/java/io/floci/aws/core/common/docker/ContainerLifecycleManagerNetworkTest.java b/src/test/java/io/floci/aws/core/common/docker/ContainerLifecycleManagerNetworkTest.java index dc15e82998..340bfff4b2 100644 --- a/src/test/java/io/floci/aws/core/common/docker/ContainerLifecycleManagerNetworkTest.java +++ b/src/test/java/io/floci/aws/core/common/docker/ContainerLifecycleManagerNetworkTest.java @@ -229,6 +229,32 @@ class ContainerLifecycleManagerNetworkTest { order.verify(connectCmd).exec(); } + @Test + void createJoinsTheContainerToItsFurtherNetworksBeforeItStarts() { + manager().create(specJoining("steps-network")); + + InOrder order = inOrder(createCmd, connectCmd); + order.verify(createCmd).exec(); + order.verify(connectCmd).withContainerId("container-id"); + order.verify(connectCmd).withNetworkId("steps-network"); + order.verify(connectCmd).exec(); + verify(connectCmd, never()).withContainerNetwork(any()); + verify(disconnectCmd, never()).exec(); + } + + @Test + void createRemovesTheContainerWhenItCannotJoinAFurtherNetwork() { + RemoveContainerCmd removeCmd = mock(RemoveContainerCmd.class, RETURNS_SELF); + lenient().when(dockerClient.removeContainerCmd("container-id")).thenReturn(removeCmd); + doThrow(new IllegalStateException("network gone")).when(connectCmd).exec(); + + IllegalStateException failure = assertThrows(IllegalStateException.class, + () -> manager().create(specJoining("steps-network"))); + + assertTrue(failure.getMessage().contains("steps-network"), failure.getMessage()); + verify(dockerClient).removeContainerCmd("container-id"); + } + @Test void createLeavesNetworkAloneWithoutLinkLocalIps() { manager().create(new ContainerSpec("busybox:stable")); @@ -598,4 +624,13 @@ class ContainerLifecycleManagerNetworkTest { false, null, List.of(), null, null, List.of(), List.of(), null, null, false, List.of(LINK_LOCAL_IP), Map.of(), false); } + + // A container on test-network that joins network too. + private static ContainerSpec specJoining(String network) { + return new ContainerSpec( + "busybox:stable", null, List.of(), null, null, null, Map.of(), List.of(), + List.of(), "test-network", List.of(), List.of(), List.of(), List.of(), Map.of(), null, + false, null, List.of(), null, null, List.of(), List.of(), null, null, false, + List.of(), Map.of(), false, LinuxOptions.NONE, false, null, List.of(network)); + } } 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 99f9e96cf9..7e74dc06bd 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java @@ -5,6 +5,7 @@ import com.github.dockerjava.api.command.CopyArchiveFromContainerCmd; import com.github.dockerjava.api.command.ExecCreateCmd; import com.github.dockerjava.api.command.InspectContainerCmd; import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.command.InspectNetworkCmd; import com.github.dockerjava.api.command.InspectVolumeResponse; import com.github.dockerjava.api.command.ListContainersCmd; import com.github.dockerjava.api.command.ListNetworksCmd; @@ -15,8 +16,11 @@ import com.github.dockerjava.api.exception.DockerException; import com.github.dockerjava.api.exception.NotFoundException; import com.github.dockerjava.api.model.Container; import com.github.dockerjava.api.model.ContainerHostConfig; +import com.github.dockerjava.api.model.ContainerNetwork; +import com.github.dockerjava.api.model.ContainerNetworkSettings; import com.github.dockerjava.api.model.HostConfig; import com.github.dockerjava.api.model.Network; +import com.github.dockerjava.api.model.NetworkSettings; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.config.EmulatorConfig.EcsServiceConfig.ImagePullBehavior; import io.floci.aws.core.common.ContainerTeardown; @@ -31,6 +35,7 @@ import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv; import io.floci.aws.services.emrserverless.EmrServerlessSparkRunner; import io.floci.aws.services.emrserverless.SparkJobRunner; import io.floci.aws.services.iam.model.SessionCreds; +import io.floci.aws.services.lambda.launcher.BootstrapProcess; import io.floci.aws.services.lambda.launcher.ImageCacheService; import io.floci.aws.services.lambda.launcher.LambdaExecutionRoleCredentials; import io.floci.aws.services.s3.S3Service; @@ -38,12 +43,16 @@ import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; import java.time.Duration; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -133,6 +142,8 @@ class EmrClusterStorageTest { when(lifecycle.resolveImageForLaunch(IMAGE, ImagePullBehavior.PREFER_CACHED, null)) .thenReturn(new ImageCacheService.LaunchImage(IMAGE, null)); when(spec.build()).thenReturn(new ContainerSpec(IMAGE)); + // The cluster's network's subnet, which lets its nodes join the steps' network too. + clusterSubnet("172.20.0.0/16"); // No other cluster's HDFS runs. ListContainersCmd running = mock(ListContainersCmd.class, RETURNS_SELF); when(docker.listContainersCmd()).thenReturn(running); @@ -159,6 +170,10 @@ class EmrClusterStorageTest { verify(spec).withDnsName(CORE_HOST); verify(spec).withDnsName(TASK_HOST); verify(spec).withDnsName(HOST); + // Each on the steps' network too, from before it starts, with Floci's DNS, so what runs on it reaches the + // containers Floci starts there by the endpoints Floci gives. + verify(spec, times(3)).withJoinedNetwork("floci-network"); + verify(spec, times(3)).withEmbeddedDns(); verify(spec).withEnv("FLOCI_NODE_HOST", CORE_HOST); verify(spec).withEnv("FLOCI_NODE_HOST", TASK_HOST); // Only a core node holds a DataNode, and with one the primary node holds neither. @@ -248,6 +263,134 @@ class EmrClusterStorageTest { verify(lifecycle, never()).removeVolume(coreName); } + @Test + void nodesOnTheStepsNetworkListenOnTheirClustersNetworkAlone() { + nodesStart(coreName, taskName); + clusterSubnet("172.20.0.0/16"); + + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES, + NOT_STOPPED); + + // The primary and each node: their HDFS and YARN on the cluster's network alone, out of the steps' network's + // reach, while what runs on them reaches that network. + verify(spec, times(3)).withEnv("FLOCI_HDFS_SUBNET", "172.20.0.0/16"); + } + + @Test + void nodesWhoseNetworksSubnetDockerDoesNotSayStayOnItAlone() { + nodesStart(coreName, taskName); + clusterSubnet(null); + + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES, + NOT_STOPPED); + + // Their daemons could not be kept to the cluster's network, so they do not join another. + verify(spec, never()).withJoinedNetwork(any()); + verify(spec, never()).withEnv(eq("FLOCI_HDFS_SUBNET"), anyString()); + } + + @Test + void aClusterWithHivesPrimaryNodeStaysOffTheStepsNetworkAsItsMetastoreListensEverywhere() { + nodesStart(coreName, taskName); + when(awsEnv.flociEndpoint()).thenReturn("http://floci:4566"); + when(awsEnv.flociEndpoint(false)).thenReturn("http://host.docker.internal:4566"); + + SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, + "floci-network", METASTORE, () -> TWO_NODES, NOT_STOPPED); + + // Its core and task nodes join, the primary does not; the executors run on the core and task nodes alone, so + // they reach Floci as the steps do. + verify(spec, times(2)).withJoinedNetwork("floci-network"); + assertEquals("http://floci:4566", started.flociEndpoint()); + } + + @Test + void aClusterWithHiveAndNoCoreNodeHasItsExecutorsReachFlociOnItsOwnNetwork() { + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-7", Map.of())); + when(lifecycle.probeContainer("c-7")).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.resolveContainerNetworkIp("c-7", hdfsName)).thenReturn("172.18.0.8"); + ContainerExecStubs.completeEveryExec(docker, "c-7", 0L, "", ""); + when(awsEnv.flociEndpoint(false)).thenReturn("http://host.docker.internal:4566"); + + SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, + "floci-network", METASTORE, () -> new ClusterStorage.Yarn(4096, 4), NOT_STOPPED); + + // The executors run on the primary node, which stays off the steps' network. + verify(spec, never()).withJoinedNetwork(any()); + assertEquals("http://host.docker.internal:4566", started.flociEndpoint()); + } + + @Test + void aNodeListensOnItsAddressInItsClustersSubnet(@TempDir Path folder) throws Exception { + nodesStart(coreName, taskName); + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES, + NOT_STOPPED); + ArgumentCaptor> entrypoints = ArgumentCaptor.captor(); + verify(spec, times(3)).withEntrypoint(entrypoints.capture()); + String script = entrypoints.getAllValues().getFirst().get(2); + int start = script.indexOf("if [ -n \"${FLOCI_HDFS_SUBNET:-}\" ]; then"); + assertTrue(start >= 0, script); + String end = "> /tmp/floci-hdfs-bind || exit"; + Path bind = folder.resolve("bind"); + String setup = script.substring(start, script.indexOf(end, start) + end.length()) + .replace("/tmp/floci-hdfs-bind", bind.toString()); + // A node on the cluster's network and the steps' one, as hostname -I lists its addresses. + String addresses = "hostname() { echo '172.30.0.5 172.20.3.7 fd00::7'; }\n"; + + assertEquals(0, BootstrapProcess.run(shell(addresses + setup, "172.20.0.0/16")).exit()); + assertEquals("172.20.3.7", Files.readString(bind).strip()); + + BootstrapProcess.Result outside = BootstrapProcess.run(shell(addresses + setup, "10.9.0.0/16")); + assertEquals(1, outside.exit()); + assertTrue(outside.output().contains("no address of this node is in 10.9.0.0/16"), outside.output()); + + assertEquals(0, BootstrapProcess.run(shell(addresses + setup, null)).exit()); + assertEquals("0.0.0.0", Files.readString(bind).strip()); + } + + // bash running script with FLOCI_HDFS_BIND at 0.0.0.0, and FLOCI_HDFS_SUBNET at subnet unless it is null. + private static ProcessBuilder shell(String script, String subnet) { + ProcessBuilder shell = new ProcessBuilder("bash", "-c", script); + shell.environment().put("FLOCI_HDFS_BIND", "0.0.0.0"); + if (subnet != null) { + shell.environment().put("FLOCI_HDFS_SUBNET", subnet); + } else { + shell.environment().remove("FLOCI_HDFS_SUBNET"); + } + return shell; + } + + // Docker says the cluster's network's subnet is subnet. + private void clusterSubnet(String subnet) { + InspectNetworkCmd inspect = mock(InspectNetworkCmd.class, RETURNS_SELF); + when(docker.inspectNetworkCmd()).thenReturn(inspect); + Network network = mock(Network.class, RETURNS_DEEP_STUBS); + Network.Ipam.Config config = mock(Network.Ipam.Config.class); + when(config.getSubnet()).thenReturn(subnet); + when(network.getIpam().getConfig()).thenReturn(List.of(config)); + when(inspect.exec()).thenReturn(network); + } + + @Test + void aNodeOnItsClustersNetworkAloneStartsAgainOnItsData() { + nodesStart(coreName, taskName); + // An earlier Floci's, which it started on its cluster's network alone. + Container alone = node(coreName, "running", IMAGE, CORE_HOST, true); + ContainerNetworkSettings networks = mock(ContainerNetworkSettings.class); + when(networks.getNetworks()).thenReturn(Map.of(hdfsName, new ContainerNetwork())); + when(alone.getNetworkSettings()).thenReturn(networks); + runningNodes(alone, node(taskName, "running", IMAGE, TASK_HOST, false)); + + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES, + NOT_STOPPED); + + verify(lifecycle).removeIfExistsStrict(coreName); + verify(spec).withName(coreName); + verify(spec, never()).withName(taskName); + verify(lifecycle, never()).removeVolume(coreName); + } + @Test void aNodeThatStopsBeforeItIsReadyStartsAgainOnceThenFailsTheStep() { nodesStart(coreName); @@ -338,7 +481,7 @@ class EmrClusterStorageTest { assertTrue(told.contains("hdfs dfsadmin -refreshNodes || { rm -f /tmp/floci-hdfs-conf/dfs.exclude; exit 1; }"), told); String asked = commands.get(2).get(2); - assertTrue(asked.contains("cluster/nodes?states=DECOMMISSIONED' | grep -q '\"nodeHostName\":\"" + TASK_HOST), asked); + assertTrue(asked.contains("cluster/nodes?states=DECOMMISSIONED\" | grep -q '\"nodeHostName\":\"" + TASK_HOST), asked); assertFalse(asked.contains("Decommissioned"), asked); verify(docker).copyArchiveFromContainerCmd(taskName, "/mnt/yarn/logs/" + taskLog); verify(lifecycle).removeIfExistsStrict(taskName); @@ -375,9 +518,9 @@ class EmrClusterStorageTest { assertTrue(yarnTold.contains("printf '" + CORE_HOST + "\\n' > /tmp/floci-hdfs-conf/yarn.exclude.new"), yarnTold); String yarnAsked = commands.get(6).get(2); - assertTrue(yarnAsked.contains("DECOMMISSIONED' | grep -q '\"nodeHostName\":\"" + CORE_HOST), yarnAsked); + assertTrue(yarnAsked.contains("DECOMMISSIONED\" | grep -q '\"nodeHostName\":\"" + CORE_HOST), yarnAsked); assertEquals(2, commands.stream().filter(command -> command.get(2).contains("Decommissioned'")).count()); - assertEquals(1, commands.stream().filter(command -> command.get(2).contains("DECOMMISSIONED'")).count()); + assertEquals(1, commands.stream().filter(command -> command.get(2).contains("DECOMMISSIONED\"")).count()); String gone = commands.get(7).get(2); assertTrue(gone.contains(excluded), gone); String dead = commands.get(commands.size() - 1).get(2); @@ -827,8 +970,12 @@ class EmrClusterStorageTest { verify(spec).withLabels(argThat(labels -> "emr-hdfs".equals(labels.get(ContainerStorageHelper.COMPONENT_LABEL)) && "j-1".equals(labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL)))); // Its host name leads to the container's own address, where the DataNode registers, unless it listens on one - // address only, which its name then leads to. - verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).startsWith(String.join("\n", + // address only, which its name then leads to: its address on the cluster's network where it joins another (see + // aNodeListensOnItsAddressInItsClustersSubnet), which is found first. + verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).startsWith( + "if [ -n \"${FLOCI_HDFS_SUBNET:-}\" ]; then\n") + && entrypoint.get(2).contains(String.join("\n", + "echo \"$FLOCI_HDFS_BIND\" > /tmp/floci-hdfs-bind || exit", "address=$FLOCI_HDFS_BIND; [ \"$address\" != 0.0.0.0 ] || address=$(hostname -i | awk '{print $1}')", "echo \"$address $FLOCI_HDFS_HOST\" >> /etc/hosts || exit\n")))); // Every one of its daemons' listeners is on that address. @@ -851,7 +998,7 @@ class EmrClusterStorageTest { + " hdfs namenode & n=1; if [ -z \"$FLOCI_NODE_WORKERS\" ] || [ -d /mnt/datanode/current ];" + " then hdfs datanode & n=2; fi; dirs=\"/tmp /user/hadoop\";") && entrypoint.get(2).contains(String.join(" ", - "until curl -sf -m 5 \"http://127.0.0.1:9870/jmx?qry=Hadoop:service=NameNode,name=NameNodeInfo\"", + "until curl -sf -m 5 \"http://$(cat /tmp/floci-hdfs-bind):9870/jmx?qry=Hadoop:service=NameNode,name=NameNodeInfo\"", "| grep -q \"\\\"ClusterId\\\" : \\\"$cid\\\"\"; do", "[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done;")))); // The image is there before the start's deadline. @@ -859,10 +1006,10 @@ class EmrClusterStorageTest { // Ready once the DataNode has joined and the NameNode has left safe mode, as its JMX says; a daemon that // exits ends it. verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(String.join(" ", - "until curl -sf -m 5 \"http://127.0.0.1:9870/jmx?qry=Hadoop:service=NameNode,name=FSNamesystemState\"", + "until curl -sf -m 5 \"http://$(cat /tmp/floci-hdfs-bind):9870/jmx?qry=Hadoop:service=NameNode,name=FSNamesystemState\"", "| grep -q \"\\\"NumLiveDataNodes\\\" : [1-9]\"; do", "[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done;", - "until curl -sf -m 5 \"http://127.0.0.1:9870/jmx?qry=Hadoop:service=NameNode,name=NameNodeInfo\"", + "until curl -sf -m 5 \"http://$(cat /tmp/floci-hdfs-bind):9870/jmx?qry=Hadoop:service=NameNode,name=NameNodeInfo\"", "| grep -q \"\\\"Safemode\\\" : \\\"\\\"\"; do", "[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done;", "hdfs dfs -mkdir -p $dirs || exit 1;")) @@ -940,21 +1087,22 @@ class EmrClusterStorageTest { when(lifecycle.probeContainer("c-7")).thenReturn(ContainerLiveness.RUNNING); when(lifecycle.resolveContainerNetworkIp("c-7", hdfsName)).thenReturn("172.18.0.8"); ContainerExecStubs.completeEveryExec(docker, "c-7", 0L, "", ""); - // Floci on the host, reached at the host's address. - when(awsEnv.flociEndpoint(false)).thenReturn("http://host.docker.internal:4566"); + when(awsEnv.flociEndpoint()).thenReturn("http://floci:4566"); SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> new ClusterStorage.Yarn(4096, 4), NOT_STOPPED); - // The steps' Spark submits to the ResourceManager on the primary node, its executors reaching Floci there. + // The steps' Spark submits to the ResourceManager on the primary node, its executors reaching Floci there as + // the steps do, the node being on their network, with Floci's DNS. assertEquals(HOST, started.resourceManager()); - assertEquals("http://host.docker.internal:4566", started.flociEndpoint()); + assertEquals("http://floci:4566", started.flociEndpoint()); verify(spec).withEnv("FLOCI_YARN_MEMORY_MB", "4096"); verify(spec).withEnv("FLOCI_YARN_VCORES", "4"); verify(spec, never()).withEnv(eq("FLOCI_HADOOP_FOLDER"), any()); verify(spec).withHostDockerInternalOnLinux(); verify(spec).withJavaTrustStore(); - verify(spec, never()).withEmbeddedDns(); + verify(spec).withEmbeddedDns(); + verify(spec).withJoinedNetwork("floci-network"); // Its configuration names the primary node, listens where HDFS does and offers what it was given. verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(String.join(" ", "\"yarn.resourcemanager.hostname$FLOCI_HDFS_HOST\"", @@ -973,9 +1121,9 @@ class EmrClusterStorageTest { // and the node gone if either daemon exits while starting. verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains( "yarn nodemanager & n=$((n + 1)); fi; fi; " - + "until curl -sf -m 5 \"http://127.0.0.1:9870/jmx?qry=Hadoop:service=NameNode,name=NameNodeInfo\"") + + "until curl -sf -m 5 \"http://$(cat /tmp/floci-hdfs-bind):9870/jmx?qry=Hadoop:service=NameNode,name=NameNodeInfo\"") && entrypoint.get(2).contains("if [ -n \"$FLOCI_YARN_MEMORY_MB\" ]; then " - + "until curl -sf -m 5 http://127.0.0.1:8088/ws/v1/cluster/metrics" + + "until curl -sf -m 5 http://$(cat /tmp/floci-hdfs-bind):8088/ws/v1/cluster/metrics" + " | grep -q \"\\\"activeNodes\\\":[1-9]\"; do " + "[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done; fi;" + " touch /tmp/floci-hdfs-ready"))); @@ -1052,6 +1200,44 @@ class EmrClusterStorageTest { verify(lifecycle).createAndStart(any()); } + @Test + void aPrimaryNodeFoundRunningOffItsStepsNetworkStartsAgain() { + // An earlier Floci's, on its cluster's network alone. + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING); + runningOn(hdfsName, hdfsName); + NetworkSettings alone = mock(NetworkSettings.class); + when(alone.getNetworks()).thenReturn(Map.of(hdfsName, new ContainerNetwork())); + when(docker.inspectContainerCmd(hdfsName).exec().getNetworkSettings()).thenReturn(alone); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-9", Map.of())); + when(lifecycle.probeContainer("c-9")).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.resolveContainerNetworkIp("c-9", hdfsName)).thenReturn("172.18.0.10"); + ContainerExecStubs.completeEveryExec(docker, "c-9", 0L, "", ""); + + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, null, NOT_STOPPED); + + verify(lifecycle).removeIfExistsStrict(hdfsName); + verify(spec).withJoinedNetwork("floci-network"); + } + + @Test + void aClusterWhoseStepsHaveNoNetworkOfFlocisReachesFlociAtItsAddressOnTheClustersNetwork() { + when(containerBuilder.resolveDockerNetwork(Optional.empty())).thenReturn(Optional.empty()); + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-7", Map.of())); + when(lifecycle.probeContainer("c-7")).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.resolveContainerNetworkIp("c-7", hdfsName)).thenReturn("172.18.0.8"); + ContainerExecStubs.completeEveryExec(docker, "c-7", 0L, "", ""); + // Floci on the host, reached at the host's address. + when(awsEnv.flociEndpoint(false)).thenReturn("http://host.docker.internal:4566"); + + SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, null, null, + () -> new ClusterStorage.Yarn(4096, 4), NOT_STOPPED); + + assertEquals("http://host.docker.internal:4566", started.flociEndpoint()); + verify(spec, never()).withJoinedNetwork(any()); + verify(spec, never()).withEmbeddedDns(); + } + @Test void aNodesContainerLogsGoToTheirS3FolderGzippedOnceEachAndNeverALaunchScript() throws IOException { String container = "application_1_0001/container_1_0001_01_000001/"; @@ -1190,7 +1376,8 @@ class EmrClusterStorageTest { verify(spec).withEnv(List.of("AWS_ACCESS_KEY_ID=ASIAMETASTORE")); verify(spec).withHostDockerInternalOnLinux(); verify(spec).withJavaTrustStore(); - // Floci's resolver would answer with an address on Floci's network, which the cluster's does not reach. + // Off the steps' network, as its metastore would listen there too. + verify(spec, never()).withJoinedNetwork(any()); verify(spec, never()).withEmbeddedDns(); verify(lifecycle, never()).ensureConnected(anyString(), anyString(), anyString()); // Floci's S3 through S3A, as for the cluster's steps. @@ -1209,7 +1396,7 @@ class EmrClusterStorageTest { + "-$(sha256sum \"$jar\" | cut -d\" \" -f1).jar || exit 1; until (exec 3<>/dev/tcp"))); // Started with the NameNode, as it needs no HDFS to start, and waited for once the HDFS is ready. verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).indexOf("hive --service metastore") - < entrypoint.get(2).indexOf("until curl -sf -m 5 \"http://127.0.0.1:9870/jmx"))); + < entrypoint.get(2).indexOf("until curl -sf -m 5 \"http://$(cat /tmp/floci-hdfs-bind):9870/jmx"))); // With the Hive image's Hadoop configuration, as Hive steps run; in a folder Derby can write its log in; its // database on the primary node's own volume, its warehouse in the HDFS, ready only once it listens, and the // node gone if it exits while starting. @@ -2239,6 +2426,10 @@ class EmrClusterStorageTest { when(container.getImageId()).thenReturn(image); when(container.getLabels()).thenReturn(Map.of("io.floci.emr.node-host", host, "io.floci.emr.node-core", String.valueOf(core))); + // On its cluster's network and on the one its steps run on. + ContainerNetworkSettings networks = mock(ContainerNetworkSettings.class); + when(networks.getNetworks()).thenReturn(Map.of("floci-network", new ContainerNetwork())); + when(container.getNetworkSettings()).thenReturn(networks); return container; } @@ -2296,6 +2487,10 @@ class EmrClusterStorageTest { when(inspect.exec()).thenReturn(response); when(response.getHostConfig()).thenReturn(HostConfig.newHostConfig().withNetworkMode(networkMode)); when(response.getImageId()).thenReturn(IMAGE); + NetworkSettings networks = mock(NetworkSettings.class); + when(networks.getNetworks()).thenReturn(Map.of(networkMode, new ContainerNetwork(), "floci-network", + new ContainerNetwork())); + when(response.getNetworkSettings()).thenReturn(networks); } // Docker inspects the container nameOrId as the one of id.