feat(emr): run a cluster's core and task nodes in containers of their own (#8066)

A docker cluster's YARN and HDFS ran on its primary node alone, however
many instances the cluster named. On EMR "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".

- Each core and task node is a container of its own on the cluster's
  network, with its data in a volume of its own, its name there the
  private DNS name ListInstances gives it. The primary node keeps a
  DataNode and a NodeManager only on a cluster created with no core
  node, which keeps them as core nodes are added, and a primary node
  whose volume holds a DataNode's data runs it in any case, so the
  blocks on it stay in reach.
- ListInstances gives each group's instances addresses of their own, so
  an instance keeps its address while another group resizes.
- How many follows the instance groups' counts or the instance fleets'
  target capacities, at most yarn-max-worker-nodes, core nodes first. A
  fleet's unit of capacity is one node. With 0 a cluster runs on its
  primary node alone.
- HDFS keeps what EMR's does: one copy of a block below four core nodes,
  two below ten, three otherwise, or the hdfs-site classification's
  dfs.replication. Steps' Spark, Hive and hadoop clients write that many.
- A resize reaches the nodes of a cluster a step has started them on, on
  another thread: a new node takes work once it has registered, and one
  no longer wanted is decommissioned, HDFS and YARN telling when it may
  go, within EMR's default hour, each node its own, then goes with its
  data. Core nodes stop at the copies HDFS keeps.
- A core node's NodeManager is decommissioned only once HDFS has moved
  its blocks, as a decommissioned NodeManager exits, which ends the
  node's container, its DataNode with it. A core node that has gone
  stays among HDFS's excluded nodes until the NameNode has it dead, 40s
  after it stopped, so the copies it held never count again.
- A core node that stops before HDFS has moved its blocks starts again
  on its data, and one a shutdown cut off while it was decommissioned
  starts again with the cluster's next step, from its volume, which
  carries its name, to be decommissioned then. A task node's volume a
  shutdown left goes.
- A decommissioning round that fails, a refresh of HDFS's or YARN's
  lists among them, is tried again on the next; a node Docker will not
  remove yet stays to be removed then, and one whose start a teardown
  passed goes. A cluster's end removes the volumes of nodes that have no
  container, and finishes even when Docker cannot list its nodes.
- The node list is read inside the cluster's lock, so a step queued
  before a resize starts the nodes asked for by then.
- Container logs come from every node, a decommissioned one's first.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-12 13:59:34 -04:00
1 parent ef5e1cf010
commit 7ebed877a8
21 files changed
+2148 -111

No files matched your search

@@ -2138,6 +2138,16 @@ public interface EmulatorConfig {
@WithDefault("4")
int yarnNodeVcores();
/**
* The most core and task nodes a {@code docker} cluster runs as containers of their own, core nodes first; each
* costs 300 to 800 MB while idle. With 0 the primary node holds its DataNode and NodeManager, as a cluster of one
* node does.
*
* Env var: FLOCI_SERVICES_EMR_YARN_MAX_WORKER_NODES
*/
@WithDefault("4")
int yarnMaxWorkerNodes();
/**
* When true, Floci removes, in the {@code docker} runner mode, every EMR step driver and bootstrap
* container a previous run of <em>this same</em> Floci left on the daemon (matched by the
@@ -201,6 +201,7 @@ public class ContainerBuilder {
private Long memorySwapBytes;
private Long memorySwappiness;
private boolean javaTrustStore;
private String dnsName;
Builder(String image, EmulatorConfig config, DockerHostResolver dockerHostResolver,
EmbeddedDnsServer embeddedDnsServer,
@@ -406,6 +407,15 @@ public class ContainerBuilder {
return this;
}
/**
* Gives the container {@code name} as its host name and as its alias on the user-defined network it joins at
* creation, so the other containers there reach it by that name.
*/
public Builder withDnsName(String name) {
this.dnsName = name;
return this;
}
/**
* Sets the Docker network from a service-specific Optional, falling back to
* the global services.dockerNetwork() if not present.
@@ -822,7 +832,8 @@ public class ContainerBuilder {
init,
new LinuxOptions(List.copyOf(capAdd), List.copyOf(capDrop), List.copyOf(devices),
shmSizeBytes, Map.copyOf(tmpfs), memorySwapBytes, memorySwappiness),
javaTrustStore
javaTrustStore,
dnsName
);
}
}
@@ -294,6 +294,9 @@ public class ContainerLifecycleManager {
if (spec.user() != null && !spec.user().isBlank()) {
createCmd.withUser(spec.user());
}
if (spec.dnsName() != null) {
createCmd.withHostName(spec.dnsName()).withAliases(spec.dnsName());
}
if (env != null && !env.isEmpty()) {
createCmd.withEnv(env);
}
@@ -51,6 +51,8 @@ import java.util.regex.Pattern;
* ({@link LinuxOptions#NONE} = daemon defaults)
* @param javaTrustStore Whether, with TLS on, the container's JVMs trust Floci's CA: the CA bundle's Java trust
* 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)
*/
public record ContainerSpec(
String image,
@@ -83,7 +85,8 @@ public record ContainerSpec(
Map<Integer, String> portBindingHostIps,
boolean init,
LinuxOptions linuxOptions,
boolean javaTrustStore
boolean javaTrustStore,
String dnsName
) {
private static final Pattern LINK_LOCAL_IPV4 = Pattern.compile("^169\\.254\\.(\\d{1,3})\\.(\\d{1,3})$");
private static final Set<String> NETWORKS_WITHOUT_ENDPOINT_IPAM = Set.of("bridge", "default", "host", "none");
@@ -107,7 +110,51 @@ 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);
false, null);
}
/**
* Backward-compatible constructor that leaves the container's name on its network to Docker, so callers that
* predate {@code dnsName} keep their existing behaviour.
*/
public ContainerSpec(
String image,
String name,
List<String> env,
List<String> cmd,
List<String> entrypoint,
Long memoryBytes,
Map<Integer, Integer> portBindings,
List<Integer> loopbackPortBindings,
List<Integer> exposedPorts,
String networkMode,
List<Mount> mounts,
List<Bind> binds,
List<VolumesFrom> volumesFrom,
List<String> extraHosts,
Map<String, String> labels,
LogConfig logConfig,
boolean privileged,
String cgroupnsMode,
List<String> dnsServers,
String workingDir,
String user,
List<String> groupAdd,
List<DeviceRequest> deviceRequests,
Long nanoCpus,
Integer cpuShares,
boolean readonlyRootfs,
List<String> linkLocalIps,
Map<Integer, String> portBindingHostIps,
boolean init,
LinuxOptions linuxOptions,
boolean javaTrustStore
) {
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, null);
}
/**
@@ -149,7 +196,8 @@ public record ContainerSpec(
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, false);
nanoCpus, cpuShares, readonlyRootfs, linkLocalIps, portBindingHostIps, init, linuxOptions, false,
null);
}
/**
@@ -2,9 +2,11 @@ package io.floci.aws.services.emr;
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.Supplier;
/**
* A cluster's storage in the EMR {@code docker} runner mode: the disks of its primary node, which every one of
@@ -34,14 +36,24 @@ public interface ClusterStorage {
* unless it is running, and returns the cluster's storage with them: its primary node's {@code host} name, which a
* step's container resolves to the address given, on the network given, the metastore's URI, and YARN's
* ResourceManager with the address Floci has on that network, the metastore and YARN only on a network of the
* cluster's own. A failure to start them is thrown, and {@link Stopped} once {@code stopped} says the step is past
* starting, or a teardown has stopped the HDFS.
* cluster's own. Its core and task nodes, {@code yarn}'s, run in containers of their own on that network, and
* {@code yarn} is read as they start, so a resize since the step was queued counts. A failure to start them is
* thrown, and {@link Stopped} once {@code stopped} says the step is past starting, or a teardown
* has stopped the HDFS.
*/
SparkJobRunner.Storage hdfs(String clusterId, String accountId, String region, String host, String image,
String dockerNetwork, HiveMetastore hiveMetastore, Yarn yarn, BooleanSupplier stopped);
String dockerNetwork, HiveMetastore hiveMetastore, Supplier<Yarn> yarn,
BooleanSupplier stopped);
/**
* Puts the logs of the YARN applications on {@code clusterId}'s primary node in {@code logFolder}, an S3 folder
* Brings {@code clusterId}'s core and task nodes to what {@code yarn} says at that moment, when a step has started
* them: a node that is new starts, and one that is no longer wanted is decommissioned and then goes, while the rest
* carry on. Clusters no step has started yet get theirs when one does.
*/
void resize(String clusterId, Supplier<Yarn> yarn);
/**
* Puts the logs of the YARN applications on {@code clusterId}'s nodes in {@code logFolder}, an S3 folder
* ending in a slash, each container's files gzipped in {@code <application>/<container>/}, those already there
* and unchanged left as they are. Logs that cannot be read or written leave the step as it ended, and are only
* logged.
@@ -57,20 +69,44 @@ public interface ClusterStorage {
}
/**
* YARN on a cluster's primary node: a ResourceManager, and a NodeManager offering its containers
* {@code memoryMb} of memory and {@code vcores} virtual cores, which run its steps' Spark executors, and the folder
* of the node's image holding the Hadoop its daemons run from, or null for the image's own.
* YARN on a cluster: a ResourceManager on its primary node, and a NodeManager on each of its {@code nodes}, and on
* the primary node too when it {@code primaryWorks}, each offering its containers {@code memoryMb} of memory and
* {@code vcores} virtual cores, which run its steps' Spark executors; the folder of the nodes' image holding the
* Hadoop their daemons run from, or null for the image's own; the copies of a block its HDFS keeps; and the S3
* folder its applications' logs go in, or null. A primary node that works runs a DataNode as well.
*/
record Yarn(int memoryMb, int vcores, String hadoopFolder) {
record Yarn(int memoryMb, int vcores, String hadoopFolder, List<Node> nodes, int replication, String logFolder,
boolean primaryWorks) {
Yarn(int memoryMb, int vcores) {
this(memoryMb, vcores, null);
this(memoryMb, vcores, null, List.of(), 1, null, true);
}
/** This YARN with its daemons run from the Hadoop in {@code folder}. */
Yarn withHadoopFolder(String folder) {
return new Yarn(memoryMb, vcores, folder);
return new Yarn(memoryMb, vcores, folder, nodes, replication, logFolder, primaryWorks);
}
/**
* This YARN on these nodes, its HDFS keeping {@code copies} of a block, its logs going to {@code folder}, its
* primary node working when none of them is a core node.
*/
Yarn onNodes(List<Node> workers, int copies, String folder) {
return new Yarn(memoryMb, vcores, hadoopFolder, List.copyOf(workers), copies, folder,
workers.stream().noneMatch(Node::core));
}
/** This YARN with its primary node running a DataNode and a NodeManager, or not. */
Yarn withPrimaryWorking(boolean works) {
return new Yarn(memoryMb, vcores, hadoopFolder, nodes, replication, logFolder, works);
}
}
/**
* A core or task node of a cluster: {@code id} tells its container from its cluster's others, {@code host} is its
* private DNS name, and a {@code core} node holds a DataNode beside its NodeManager.
*/
record Node(String id, String host, boolean core) {
}
/**
@@ -36,6 +36,7 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -43,9 +44,12 @@ import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
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.LongSupplier;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.zip.GZIPOutputStream;
@@ -59,7 +63,9 @@ import java.util.zip.GZIPOutputStream;
* primary node's, with their data in a third volume, so that the first container to mount the {@code /mnt} one is a
* step's, which fills it from the step's image. On a cluster with Hive or HCatalog the same container runs Hive's
* 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.
* 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.
*/
@ApplicationScoped
public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
@@ -95,8 +101,23 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
private static final String YARN_VCORES_VARIABLE = "FLOCI_YARN_VCORES";
// The folder of the image holding the Hadoop the node's daemons run from; set only when that is not the image's own.
private static final String HADOOP_FOLDER_VARIABLE = "FLOCI_HADOOP_FOLDER";
// A core or task node's container: its host name, and whether it holds a DataNode, as a resize must know them again
// after Floci restarts.
private static final String NODE_COMPONENT = SparkJobRunner.Storage.NODE_COMPONENT;
private static final String NODE_HOST_LABEL = "io.floci.emr.node-host";
private static final String NODE_CORE_LABEL = "io.floci.emr.node-core";
private static final String NODE_HOST_VARIABLE = "FLOCI_NODE_HOST";
private static final String NODE_CORE_VARIABLE = "FLOCI_NODE_CORE";
// Set on a primary node whose cluster was created with core nodes, which hold its DataNodes and NodeManagers in its
// place.
private static final String NODE_WORKERS_VARIABLE = "FLOCI_NODE_WORKERS";
private static final String REPLICATION_VARIABLE = "FLOCI_HDFS_REPLICATION";
// The nodes being decommissioned, one host name to a line, as HDFS and YARN read them on the primary node.
private static final String DFS_EXCLUDE = HDFS_CONF + "/dfs.exclude";
private static final String YARN_EXCLUDE = HDFS_CONF + "/yarn.exclude";
// The ResourceManager's 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=";
// The java.base packages Hadoop 3.4's YARN daemons reach into, which Java 17 opens only when told, through
// JDK_JAVA_OPTIONS, which Java 9 on reads and Java 8, on which a release may run and which refuses the options
// themselves, ignores.
@@ -115,44 +136,50 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
// gives up.
private static final Duration HDFS_START_TIMEOUT = Duration.ofSeconds(120);
private static final Duration HDFS_POLL_INTERVAL = Duration.ofMillis(500);
// How long a node being decommissioned may take before it goes anyway: EMR's default for a graceful one, "3600s
// (one hour)", and a minute more for the ResourceManager's own timeout to pass first.
private static final Duration GRACEFUL_DECOMMISSION = Duration.ofHours(1);
private static final Duration DECOMMISSION_MARGIN = Duration.ofMinutes(1);
private static final Duration DECOMMISSION_POLL = Duration.ofSeconds(3);
// A core node that has gone stays in HDFS's exclude list until the NameNode has it dead: taken out while the
// NameNode still has it live, it is back in service, the copies of its blocks count again, and the NameNode drops
// one copy of each block now held twice, which may be the remaining node's. The NameNode has a node dead after twice
// its heartbeat recheck interval and ten heartbeats, 2 x 5s + 10 x 3s with NODE_SETUP's setting; this has a margin.
private static final Duration DEAD_NODE_WAIT = Duration.ofSeconds(60);
private static final int NODE_COMMAND_SECONDS = 120;
// How much of a node's output is logged when it does not become ready, and how long reading it may take.
private static final int NODE_LOG_LINES = 40;
private static final Duration NODE_LOG_READ = Duration.ofSeconds(5);
// The primary node's HDFS, started as root: its daemons log their warnings and errors to the container's output,
// which docker logs shows; its host name, FLOCI_HDFS_HOST, leads to this container's address, where the DataNode
// registers, so steps reach both by it; /mnt, its data's volume, becomes the image's user's, which runs a NameNode
// and a DataNode with their data in it, the NameNode formatted the first time, with one copy of each block and
// without permissions, listening on FLOCI_HDFS_BIND: every address of the container, on the cluster's own network,
// or, in a namespace the steps share, the host's or a container's, only its loopback, which its name leads to, so
// no other interface serves files anyone could change; in a container's, the hosts file the name goes in is the
// one the namespace's containers share, the steps' too. Once the NameNode on its port is this container's own,
// its ClusterId the one its format gave it, rather than another cluster's in that namespace, the DataNode has
// joined and the NameNode has left safe mode, which on a restart waits for the blocks the volume holds, the
// folders EMR's HDFS has for steps, /tmp and the hadoop user's home, are made. With HIVE_METASTORE_VARIABLE set,
// Hive's metastore service starts too, with the Hive image's Hadoop configuration, which the node's image keeps at
// HIVE_HADOOP_CONF, as Hive steps run, its settings after it: "Hive records metastore information in a MySQL database on the primary node's file system", kept as a Derby
// database in /mnt, which only the service opens, so any number of steps share it, its log in /tmp, and its
// warehouse in the HDFS, Hive's exec jar in HIVE_JARS; the cluster's core-site and hive-site, last, replace any of
// them, as on EMR's primary node. With YARN_MEMORY_VARIABLE set, YARN starts last, as "the primary node runs the
// YARN ResourceManager service": a ResourceManager and, as on a cluster of one node, a NodeManager, which offers
// that much memory and YARN_VCORES_VARIABLE's cores to the containers it runs the steps' Spark executors in, its
// local and log folders in /mnt, Java 17 opening to both the packages they reach into, and the node is ready once
// the NodeManager has registered. HDFS_READY then says the node is ready. 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.
private static final String HDFS_SCRIPT = String.join("\n",
"address=$FLOCI_HDFS_BIND; [ \"$address\" != 0.0.0.0 ] || address=$(hostname -i | awk '{print $1}')",
"echo \"$address $FLOCI_HDFS_HOST\" >> /etc/hosts || exit",
// Every daemon of a node, and each command run on it, uses the Hadoop in HADOOP_FOLDER_VARIABLE when that is set.
private static final String HADOOP_FOLDER_SETUP = String.join("\n",
"if [ -n \"$" + HADOOP_FOLDER_VARIABLE + "\" ]; then",
" h=$" + HADOOP_FOLDER_VARIABLE,
" export HADOOP_HOME=$h/hadoop HADOOP_COMMON_HOME=$h/hadoop HADOOP_LIBEXEC_DIR=$h/hadoop/libexec"
+ " HADOOP_HDFS_HOME=$h/hadoop-hdfs HADOOP_MAPRED_HOME=$h/hadoop-mapreduce"
+ " HADOOP_YARN_HOME=$h/hadoop-yarn PATH=$h/hadoop-hdfs/bin:$h/hadoop-yarn/bin:$h/hadoop/bin:$PATH",
"fi");
// What every node of a cluster writes before its daemons start: the Hadoop configuration, its name among the
// nodes in HDFS's when it is given one, and the empty files listing the nodes being decommissioned.
private static final String NODE_SETUP = String.join("\n",
"chown hadoop:hadoop /mnt || exit",
EmrServerlessSparkRunner.HIVE_ONE_SDK,
"mkdir -p " + HDFS_CONF + " || exit",
"printf '%s\\n' '<configuration>'"
+ " \"<property><name>fs.defaultFS</name><value>hdfs://$FLOCI_HDFS_HOST:8020</value></property>\""
+ " '</configuration>' > " + HDFS_CONF + "/core-site.xml",
"datanode_name=; [ -z \"$" + NODE_HOST_VARIABLE + "\" ] || datanode_name=\"<property>"
+ "<name>dfs.datanode.hostname</name><value>$" + NODE_HOST_VARIABLE + "</value></property>\"",
": > " + DFS_EXCLUDE + " || exit",
": > " + YARN_EXCLUDE + " || exit",
"printf '%s\\n' '<configuration>'"
+ " '<property><name>dfs.namenode.name.dir</name><value>file:///mnt/namenode</value></property>'"
+ " '<property><name>dfs.datanode.data.dir</name><value>file:///mnt/datanode</value></property>'"
+ " '<property><name>dfs.replication</name><value>1</value></property>'"
+ " \"<property><name>dfs.replication</name><value>${" + REPLICATION_VARIABLE
+ ":-1}</value></property>\""
+ " '<property><name>dfs.hosts.exclude</name><value>" + DFS_EXCLUDE + "</value></property>'"
+ " '<property><name>dfs.namenode.decommission.interval</name><value>3</value></property>'"
+ " '<property><name>dfs.namenode.heartbeat.recheck-interval</name><value>5000</value></property>'"
+ " \"$datanode_name\""
+ " '<property><name>dfs.permissions.enabled</name><value>false</value></property>'"
+ " \"<property><name>dfs.namenode.rpc-bind-host</name><value>$FLOCI_HDFS_BIND</value></property>\""
+ " \"<property><name>dfs.namenode.http-address</name>"
@@ -178,7 +205,9 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
"yarn.nodemanager.local-dirs", "/mnt/yarn/local",
"yarn.nodemanager.log-dirs", "/mnt/yarn/logs",
"yarn.nodemanager.disk-health-checker.max-disk-utilization-per-disk-percentage", "100",
"yarn.nodemanager.aux-services", "mapreduce_shuffle"))
"yarn.nodemanager.aux-services", "mapreduce_shuffle",
"yarn.resourcemanager.nodes.exclude-path", YARN_EXCLUDE,
"yarn.resourcemanager.decommissioning-nodes-watcher.poll-interval-secs", "3"))
+ " '</configuration>' > " + HDFS_CONF + "/yarn-site.xml || exit",
" printf '%s\\n' '<configuration>'" + yarnProperties(List.of(
"yarn.scheduler.capacity.root.queues", "default",
@@ -191,21 +220,46 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
+ " 'log4j.appender.console.layout=org.apache.log4j.PatternLayout'"
+ " 'log4j.appender.console.layout.ConversionPattern=%d %p %c: %m%n'"
+ " > " + HDFS_CONF + "/log4j.properties",
"if [ -n \"$" + HADOOP_FOLDER_VARIABLE + "\" ]; then",
" h=$" + HADOOP_FOLDER_VARIABLE,
" export HADOOP_HOME=$h/hadoop HADOOP_COMMON_HOME=$h/hadoop HADOOP_LIBEXEC_DIR=$h/hadoop/libexec"
+ " HADOOP_HDFS_HOME=$h/hadoop-hdfs HADOOP_MAPRED_HOME=$h/hadoop-mapreduce"
+ " HADOOP_YARN_HOME=$h/hadoop-yarn PATH=$h/hadoop-hdfs/bin:$h/hadoop-yarn/bin:$h/hadoop/bin:$PATH",
"fi",
HADOOP_FOLDER_SETUP);
// The primary node's HDFS, started as root: its daemons log their warnings and errors to the container's output,
// which docker logs shows; its host name, FLOCI_HDFS_HOST, leads to this container's address, where the DataNode
// registers, so steps reach both by it; /mnt, its data's volume, becomes the image's user's, which runs a NameNode
// and a DataNode with their data in it, the NameNode formatted the first time, with one copy of each block and
// without permissions, listening on FLOCI_HDFS_BIND: every address of the container, on the cluster's own network,
// or, in a namespace the steps share, the host's or a container's, only its loopback, which its name leads to, so
// no other interface serves files anyone could change; in a container's, the hosts file the name goes in is the
// one the namespace's containers share, the steps' too. Once the NameNode on its port is this container's own,
// its ClusterId the one its format gave it, rather than another cluster's in that namespace, the DataNode has
// joined and the NameNode has left safe mode, which on a restart waits for the blocks the volume holds, the
// folders EMR's HDFS has for steps, /tmp and the hadoop user's home, are made. With HIVE_METASTORE_VARIABLE set,
// Hive's metastore service starts too, with the Hive image's Hadoop configuration, which the node's image keeps at
// HIVE_HADOOP_CONF, as Hive steps run, its settings after it: "Hive records metastore information in a MySQL database on the primary node's file system", kept as a Derby
// database in /mnt, which only the service opens, so any number of steps share it, its log in /tmp, and its
// warehouse in the HDFS, Hive's exec jar in HIVE_JARS; the cluster's core-site and hive-site, last, replace any of
// them, as on EMR's primary node. With YARN_MEMORY_VARIABLE set, YARN starts last, as "the primary node runs the
// YARN ResourceManager service": a ResourceManager and, as on a cluster of one node, a NodeManager, which offers
// that much memory and YARN_VCORES_VARIABLE's cores to the containers it runs the steps' Spark executors in, its
// local and log folders in /mnt, Java 17 opening to both the packages they reach into, and the node is ready once
// the NodeManager has registered. Where the cluster's core nodes hold them (NODE_WORKERS_VARIABLE), the node runs no
// DataNode or NodeManager, but a DataNode on a volume that holds one's data, so the blocks it kept stay in reach.
// HDFS_READY then says the node is ready. 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.
private static final String HDFS_SCRIPT = String.join("\n",
"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,
"exec setpriv --reuid=hadoop --regid=hadoop --clear-groups bash -c '"
+ "[ -d /mnt/namenode/current ] || hdfs namenode -format -nonInteractive || exit; "
+ "cid=$(sed -n \"s/^clusterID=//p\" /mnt/namenode/current/VERSION); "
+ "hdfs namenode & hdfs datanode & n=2; "
+ "hdfs namenode & n=1; "
+ "if [ -z \"$" + NODE_WORKERS_VARIABLE + "\" ] || [ -d /mnt/datanode/current ]; then "
+ "hdfs datanode & n=2; fi; "
+ "until curl -sf -m 5 \"" + NAMENODE_JMX + "NameNodeInfo\""
+ " | grep -q \"\\\"ClusterId\\\" : \\\"$cid\\\"\"; do "
+ "[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done; "
+ "until curl -sf -m 5 \"" + NAMENODE_JMX + "FSNamesystemState\""
+ " | grep -q \"\\\"NumLiveDataNodes\\\" : 1,\"; do "
+ " | grep -q \"\\\"NumLiveDataNodes\\\" : [1-9]\"; do "
+ "[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done; "
+ "until curl -sf -m 5 \"" + NAMENODE_JMX + "NameNodeInfo\""
+ " | grep -q \"\\\"Safemode\\\" : \\\"\\\"\"; do "
@@ -233,9 +287,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
+ "[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done; "
+ "fi; "
+ "if [ -n \"$" + YARN_MEMORY_VARIABLE + "\" ]; then "
+ "JDK_JAVA_OPTIONS=\"" + yarnOpens() + "\" yarn resourcemanager & "
+ "JDK_JAVA_OPTIONS=\"" + yarnOpens() + "\" yarn nodemanager & n=$((n + 2)); "
+ "until curl -sf -m 5 " + RESOURCE_MANAGER_METRICS + " | grep -q \"\\\"activeNodes\\\":1,\"; do "
+ "JDK_JAVA_OPTIONS=\"" + yarnOpens() + "\" yarn resourcemanager & n=$((n + 1)); "
+ "if [ -z \"$" + NODE_WORKERS_VARIABLE + "\" ]; then "
+ "JDK_JAVA_OPTIONS=\"" + yarnOpens() + "\" yarn nodemanager & n=$((n + 1)); fi; "
+ "until curl -sf -m 5 " + RESOURCE_MANAGER_METRICS
+ " | grep -q \"\\\"activeNodes\\\":[1-9]\"; do "
+ "[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done; "
+ "fi; "
+ "touch " + HDFS_READY + "; "
@@ -243,6 +299,25 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
+ "while [ \"$(jobs -rp | wc -l)\" = $n ]; do sleep 1; done; rm -f " + HDFS_READY
+ "; kill $(jobs -rp) 2>/dev/null; exit 1'");
// A core or task node, started as root: a NodeManager and, on a core node, a DataNode, which reach the primary node
// 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",
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; "
+ "JDK_JAVA_OPTIONS=\"" + yarnOpens() + "\" yarn nodemanager & "
+ "until curl -sf -m 5 \"http://$FLOCI_HDFS_HOST:8088/ws/v1/cluster/nodes?states=RUNNING\""
+ " | grep -q \"\\\"nodeHostName\\\":\\\"$" + NODE_HOST_VARIABLE + "\\\"\"; do "
+ "[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done; "
+ "if [ -n \"$" + NODE_CORE_VARIABLE + "\" ]; then "
+ "until curl -sf -m 5 \"http://$FLOCI_HDFS_HOST:9870/jmx?qry=Hadoop:service=NameNode,"
+ "name=NameNodeInfo\" | grep -q \"$" + NODE_HOST_VARIABLE + ":9866\"; do "
+ "[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done; fi; "
+ "touch " + HDFS_READY + "; "
+ "while [ \"$(jobs -rp | wc -l)\" = $n ]; do sleep 1; done; rm -f " + HDFS_READY
+ "; kill $(jobs -rp) 2>/dev/null; exit 1'");
// One start at a time in a namespace the steps share, whatever the cluster, as it holds one HDFS.
private final Object sharedNamespaceStarts = new Object();
// One start at a time for each cluster's HDFS; a step coming while it starts waits, then finds it running.
@@ -254,6 +329,19 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
private final Map<String, Map<String, Long>> archivedLogs = new ConcurrentHashMap<>();
// The HDFS containers this process has started or found running, by name, which a reset or a shutdown removes.
private final Set<String> running = ConcurrentHashMap.newKeySet();
// The core and task nodes' containers this process has started or found, by name.
private final Set<String> runningNodes = ConcurrentHashMap.newKeySet();
// What each cluster's last step started its nodes from, which a resize starts new ones from.
private final Map<String, NodeRequest> nodeRequests = new ConcurrentHashMap<>();
// For each cluster, the nodes being decommissioned, by container name.
private final Map<String, Map<String, Draining>> draining = new ConcurrentHashMap<>();
// For each cluster, the core nodes that have gone and are still in HDFS's exclude list, by host name, with the
// nanoTime they went at.
private final Map<String, Map<String, Long>> departed = new ConcurrentHashMap<>();
// The clusters a thread is decommissioning nodes of.
private final Set<String> decommissioning = ConcurrentHashMap.newKeySet();
private final Executor decommissions;
private final Duration decommissionPoll;
private final ContainerLifecycleManager lifecycleManager;
private final ContainerBuilder containerBuilder;
private final LaunchedContainerAwsEnv awsEnv;
@@ -272,13 +360,26 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
CurrentContainerNetworkResolver currentContainer, EmulatorConfig config,
S3Service s3Service) {
this(lifecycleManager, containerBuilder, awsEnv, roleCredentials, currentContainer, config, s3Service,
HDFS_START_TIMEOUT, System::nanoTime);
HDFS_START_TIMEOUT, System::nanoTime,
Executors.newCachedThreadPool(Thread.ofPlatform().daemon().name("emr-decommission-", 0).factory()),
DECOMMISSION_POLL);
}
EmrClusterStorage(ContainerLifecycleManager lifecycleManager, ContainerBuilder containerBuilder,
LaunchedContainerAwsEnv awsEnv, LambdaExecutionRoleCredentials roleCredentials,
CurrentContainerNetworkResolver currentContainer, EmulatorConfig config, S3Service s3Service,
Duration hdfsStartTimeout, LongSupplier nanoTime) {
this(lifecycleManager, containerBuilder, awsEnv, roleCredentials, currentContainer, config, s3Service,
hdfsStartTimeout, nanoTime, Runnable::run, Duration.ZERO);
}
EmrClusterStorage(ContainerLifecycleManager lifecycleManager, ContainerBuilder containerBuilder,
LaunchedContainerAwsEnv awsEnv, LambdaExecutionRoleCredentials roleCredentials,
CurrentContainerNetworkResolver currentContainer, EmulatorConfig config, S3Service s3Service,
Duration hdfsStartTimeout, LongSupplier nanoTime, Executor decommissions,
Duration decommissionPoll) {
this.decommissions = decommissions;
this.decommissionPoll = decommissionPoll;
this.lifecycleManager = lifecycleManager;
this.containerBuilder = containerBuilder;
this.awsEnv = awsEnv;
@@ -307,12 +408,30 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
@Override
public void archiveContainerLogs(String clusterId, String accountId, String region, String logFolder) {
String name = hdfsName(clusterId);
archiveNodeLogs(clusterId, hdfsName(clusterId), accountId, region, logFolder);
Collection<String> nodes;
try {
nodes = nodeContainers(clusterId).keySet();
} catch (RuntimeException e) {
LOG.warnv(e, "Could not find the nodes of EMR cluster {0} to write their container logs to {1}: {2}",
clusterId, logFolder, e.getMessage());
return;
}
for (String node : nodes) {
archiveNodeLogs(clusterId, node, accountId, region, logFolder);
}
}
private void archiveNodeLogs(String clusterId, String name, String accountId, String region, String logFolder) {
Map<String, Long> archived = archivedLogs.computeIfAbsent(name, node -> new ConcurrentHashMap<>());
// One step's end at a time for a node, so of two reading a log that is still growing the later is written last.
synchronized (archived) {
try {
S3Uri folder = S3Uri.parseAnyScheme(logFolder);
if (lifecycleManager.probeContainer(name) == ContainerLiveness.NOT_RUNNING) {
archiveStoppedNodeLogs(name, archived, accountId, region, folder);
return;
}
for (String log : changedLogs(name, archived)) {
archiveLog(name, log, archived, accountId, region, folder);
}
@@ -325,9 +444,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
// The node's container logs whose size is not the one already in S3, as <application>/<container>/<file>, but the
// launch scripts: only those are read from Docker, so a step's end does not bring every earlier application's again.
// A primary node whose core nodes run the NodeManagers has no such folder, and so none.
private List<String> changedLogs(String name, Map<String, Long> archived) {
ContainerExec.Result listed = ContainerExec.run(lifecycleManager.getDockerClient(), name,
new String[]{"find", YARN_LOGS, "-mindepth", "3", "-maxdepth", "3", "-type", "f", "-printf", "%s %P\\n"},
new String[]{"bash", "-c", "[ ! -d " + YARN_LOGS + " ] || exec find " + YARN_LOGS
+ " -mindepth 3 -maxdepth 3 -type f -printf '%s %P\\n'"},
LOG_LISTING_SECONDS);
if (listed.exitCode() != 0) {
throw new IllegalStateException("Could not list them: " + listed.stderr());
@@ -343,6 +464,28 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
return changed;
}
// A stopped node answers no command, a decommissioned one among them, whose NodeManager exits once it is, which ends
// its container, but Docker still copies its files: the whole folder, as this is the last look at a node that goes.
private void archiveStoppedNodeLogs(String name, Map<String, Long> archived, String accountId, String region,
S3Uri folder) throws IOException {
try (InputStream archive = lifecycleManager.getDockerClient().copyArchiveFromContainerCmd(name, YARN_LOGS)
.exec(); TarArchiveInputStream entries = new TarArchiveInputStream(archive)) {
TarArchiveEntry entry;
while ((entry = entries.getNextEntry()) != null) {
// logs/<application>/<container>/<file>, as Docker archives the folder.
String[] path = entry.getName().split("/");
if (!entry.isFile() || path.length != 4 || CONTAINER_LAUNCH_SCRIPT.equals(path[3])) {
continue;
}
String log = path[1] + "/" + path[2] + "/" + path[3];
if (!Objects.equals(archived.get(log), entry.getSize())) {
putContainerLog(entries, accountId, region, folder.bucket(), folder.key() + log + ".gz");
archived.put(log, entry.getSize());
}
}
}
}
private void archiveLog(String name, String log, Map<String, Long> archived, String accountId, String region,
S3Uri folder) throws IOException {
try (InputStream archive = lifecycleManager.getDockerClient()
@@ -381,7 +524,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
@Override
public SparkJobRunner.Storage hdfs(String clusterId, String accountId, String region, String host, String image,
String dockerNetwork, HiveMetastore hiveMetastore, Yarn yarn,
String dockerNetwork, HiveMetastore hiveMetastore, Supplier<Yarn> yarnNow,
BooleanSupplier stopped) {
String name = hdfsName(clusterId);
String network = network(dockerNetwork);
@@ -399,7 +542,12 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
boolean shared = sharesNamespace(network);
long deadline = nanoTime.getAsLong() + hdfsStartTimeout.toNanos();
synchronized (starting.computeIfAbsent(clusterId, id -> new Object())) {
// 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);
String containerId = null;
List<String> nodes = List.of();
// One found running whose daemon has just exited stops before it is ready, and is started again, once.
for (int attempt = 0; containerId == null; attempt++) {
stopIfStopped(clusterId, teardown, stopped);
@@ -416,6 +564,8 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
running.add(name);
String candidate = found ? name
: start(clusterId, accountId, region, host, imageId, dockerNetwork, hiveMetastore, yarn);
// Before it is awaited, as its readiness needs a DataNode of theirs.
nodes = nodeRequest != null ? reconcileNodes(nodeRequest, teardown) : List.of();
if (awaitReady(clusterId, candidate, deadline, teardown, stopped)) {
containerId = candidate;
} else if (!found) {
@@ -428,12 +578,401 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
if (shared) {
return volumes(clusterId).withHdfs(host, LOOPBACK, null);
}
if (nodeRequest != null) {
awaitNodes(nodeRequest, nodes, deadline, teardown, stopped);
nodeRequests.put(clusterId, nodeRequest);
}
SparkJobRunner.Storage storage = volumes(clusterId).withHdfs(host, address(clusterId, containerId), name);
if (hiveMetastore != null) {
storage = storage.withHiveMetastore("thrift://" + host + ":" + HIVE_METASTORE_PORT);
}
if (yarn == null) {
return storage;
}
// Its executors reach Floci's S3 from the node, at Floci's address on the cluster's network.
return yarn != null ? storage.withYarn(host, flociEndpointOn(name)) : storage;
storage = storage.withYarn(host, flociEndpointOn(name));
return yarn.nodes().stream().anyMatch(Node::core) ? storage.withReplication(yarn.replication()) : storage;
}
}
@Override
public void resize(String clusterId, Supplier<Yarn> yarn) {
long teardown = teardowns.get();
try {
synchronized (starting.computeIfAbsent(clusterId, id -> new Object())) {
NodeRequest known = nodeRequests.get(clusterId);
if (known == null) {
return;
}
// Read here too, so of two resizes the one that takes the lock last applies what the cluster says now.
NodeRequest request = known.resizedTo(yarn.get());
nodeRequests.put(clusterId, request);
reconcileNodes(request, teardown);
}
} catch (RuntimeException e) {
LOG.warnv(e, "Could not resize the nodes of EMR cluster {0}: {1}", clusterId, e.getMessage());
}
}
// A cluster's core and task nodes: one wanted and not running in the image starts, on the data its volume keeps, one
// no longer wanted is decommissioned on a thread of its own, and one being decommissioned that is wanted again
// carries on. A core node found only as its volume, as a shutdown leaves one it cut off while it was decommissioned,
// starts again on its data to be decommissioned, so HDFS moves its blocks; a task node's volume goes, as it holds
// none. The names of those wanted.
private List<String> reconcileNodes(NodeRequest request, long teardown) {
String clusterId = request.clusterId();
Map<String, Container> present = nodeContainers(clusterId);
Map<String, Draining> leaving = draining.computeIfAbsent(clusterId, id -> new ConcurrentHashMap<>());
boolean changed = false;
List<String> wanted = new ArrayList<>();
for (Node node : request.yarn().nodes()) {
String name = nodeName(clusterId, node);
wanted.add(name);
changed |= leaving.remove(name) != null;
Container container = present.get(name);
if (container == null || !"running".equals(container.getState())
|| !request.imageId().equals(container.getImageId())) {
startNode(request, node.host(), node.core(), name, teardown);
} else {
runningNodes.add(name);
}
}
for (Map.Entry<String, Container> node : present.entrySet()) {
if (!wanted.contains(node.getKey()) && !leaving.containsKey(node.getKey())) {
leaving.put(node.getKey(), draining(node.getValue().getLabels()));
runningNodes.add(node.getKey());
changed = true;
}
}
for (Map.Entry<String, Map<String, String>> volume : nodeVolumes(clusterId).entrySet()) {
String name = volume.getKey();
if (wanted.contains(name) || present.containsKey(name) || leaving.containsKey(name)) {
continue;
}
Draining node = draining(volume.getValue());
if (node.core()) {
startNode(request, node.host(), true, name, teardown);
leaving.put(name, node);
changed = true;
} else {
lifecycleManager.removeVolume(name);
}
}
if (changed) {
syncExcludes(clusterId, leaving.values());
}
if (!leaving.isEmpty() && decommissioning.add(clusterId)) {
decommissions.execute(() -> decommission(request, teardown));
}
return wanted;
}
// A node being decommissioned, as its container's or its volume's labels say, with an hour and a minute to go in.
private Draining draining(Map<String, String> labels) {
Map<String, String> known = labels != null ? labels : Map.of();
return new Draining(known.get(NODE_HOST_LABEL), Boolean.parseBoolean(known.get(NODE_CORE_LABEL)),
nanoTime.getAsLong() + GRACEFUL_DECOMMISSION.plus(DECOMMISSION_MARGIN).toNanos());
}
// A node's container, started on the data its volume keeps; one whose start a teardown passed goes, as the teardown's
// sweep may have looked before it was there.
private void startNode(NodeRequest request, String host, boolean core, String name, long teardown) {
String clusterId = request.clusterId();
Yarn yarn = request.yarn();
// Known before it starts, so a teardown while it starts removes it.
runningNodes.add(name);
lifecycleManager.removeIfExistsStrict(name);
// Its volume says whose it is too, so a shutdown that removes its container leaves it findable.
Map<String, String> volumeLabels = labels(clusterId, request.accountId(), request.region(), COMPONENT);
volumeLabels.put(NODE_HOST_LABEL, host);
volumeLabels.put(NODE_CORE_LABEL, String.valueOf(core));
lifecycleManager.ensureVolume(name, volumeLabels);
Map<String, String> labels = labels(clusterId, request.accountId(), request.region(), NODE_COMPONENT);
labels.put(NODE_HOST_LABEL, host);
labels.put(NODE_CORE_LABEL, String.valueOf(core));
ContainerBuilder.Builder spec = containerBuilder.newContainer(request.imageId())
.withName(name)
.withUser("root")
.withEntrypoint(List.of("/bin/bash", "-c", NODE_SCRIPT))
.withEnv("FLOCI_HDFS_HOST", request.host())
.withEnv("FLOCI_HDFS_BIND", "0.0.0.0")
.withEnv(NODE_HOST_VARIABLE, host)
.withEnv(REPLICATION_VARIABLE, String.valueOf(yarn.replication()))
.withEnv(YARN_MEMORY_VARIABLE, String.valueOf(yarn.memoryMb()))
.withEnv(YARN_VCORES_VARIABLE, String.valueOf(yarn.vcores()))
.withEnv("HADOOP_CONF_DIR", HDFS_CONF)
.withEnv("HADOOP_LOG_DIR", "/tmp/floci-hdfs-logs")
.withNamedVolume(name, "/mnt")
.withDockerNetwork(Optional.of(hdfsName(clusterId)))
.withDnsName(host)
.withLogRotation()
.withLabels(labels)
// Its executors reach Floci, Floci on the host by its address, Floci's own certificate trusted.
.withHostDockerInternalOnLinux()
.withJavaTrustStore();
if (core) {
spec.withEnv(NODE_CORE_VARIABLE, "1");
}
if (yarn.hadoopFolder() != null) {
spec.withEnv(HADOOP_FOLDER_VARIABLE, yarn.hadoopFolder());
}
lifecycleManager.createAndStart(spec.build());
if (teardowns.get() != teardown) {
removeNode(name, false);
return;
}
LOG.infov("Started the {0} node {1} of EMR cluster {2}", core ? "core" : "task", host, clusterId);
}
// Each node ready by the deadline; one that stopped before it was is started again, once.
private void awaitNodes(NodeRequest request, List<String> nodes, long deadline, long teardown,
BooleanSupplier stopped) {
List<String> wanted = nodes;
for (int attempt = 0; ; attempt++) {
boolean ready = true;
for (String node : wanted) {
ready = ready && awaitReady(request.clusterId(), node, deadline, teardown, stopped);
}
if (ready) {
return;
}
stopIfStopped(request.clusterId(), teardown, stopped);
if (attempt > 0) {
throw new IllegalStateException("A node of EMR cluster " + request.clusterId()
+ " stopped before it was ready");
}
wanted = reconcileNodes(request, teardown);
}
}
// The containers of a cluster's core and task nodes, running or not, by name.
private Map<String, Container> nodeContainers(String clusterId) {
Map<String, Container> nodes = new LinkedHashMap<>();
List<Container> containers = lifecycleManager.getDockerClient().listContainersCmd().withShowAll(true)
.withLabelFilter(Map.of(ContainerStorageHelper.COMPONENT_LABEL, NODE_COMPONENT,
ContainerStorageHelper.RESOURCE_ID_LABEL, clusterId,
ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)))
.exec();
for (Container container : containers) {
nodes.put(container.getNames()[0].substring(1), container);
}
return nodes;
}
// The volumes of a cluster's core and task nodes, with their labels, by name, whether a container has them or not.
private Map<String, Map<String, String>> nodeVolumes(String clusterId) {
ListVolumesResponse response = lifecycleManager.getDockerClient().listVolumesCmd()
.withFilter("label", List.of(ContainerStorageHelper.COMPONENT_LABEL + "=" + COMPONENT,
ContainerStorageHelper.RESOURCE_ID_LABEL + "=" + clusterId,
ContainerStorageHelper.OWNER_LABEL + "=" + ContainerStorageHelper.ownerIdentity(config),
NODE_HOST_LABEL))
.exec();
Map<String, Map<String, String>> volumes = new LinkedHashMap<>();
if (response != null && response.getVolumes() != null) {
for (InspectVolumeResponse volume : response.getVolumes()) {
Map<String, String> labels = volume.getLabels() != null ? volume.getLabels() : Map.of();
if (clusterId.equals(labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL))
&& labels.containsKey(NODE_HOST_LABEL)) {
volumes.put(volume.getName(), labels);
}
}
}
return volumes;
}
// Writes the lists of the nodes being decommissioned on the primary node, when they changed, a primary node started
// again holding none, and has HDFS and YARN read them: "both YARN NodeManager and HDFS DataNode daemons must be
// decommissioned" on a core node, and only the first on a task node. A node leaves YARN's list once it has gone, as
// a node that comes back under its name is a new one, and HDFS's once the NameNode has it dead (DEAD_NODE_WAIT). A
// refresh that fails takes its list away, so the next round's differs and is read again.
private void syncExcludes(String clusterId, Collection<Draining> nodes) {
String yarnHosts = hostLines(nodes.stream().filter(Draining::hdfsDone).map(Draining::host).toList());
List<String> dfs = new ArrayList<>(nodes.stream().filter(Draining::core).map(Draining::host).toList());
dfs.addAll(departed.getOrDefault(clusterId, Map.of()).keySet());
String dfsHosts = hostLines(dfs);
String script = String.join("\n", HADOOP_FOLDER_SETUP,
"printf '" + yarnHosts + "' > " + YARN_EXCLUDE + ".new || exit 1",
"printf '" + dfsHosts + "' > " + DFS_EXCLUDE + ".new || exit 1",
"if ! cmp -s " + YARN_EXCLUDE + ".new " + YARN_EXCLUDE + "; then mv " + YARN_EXCLUDE + ".new "
+ YARN_EXCLUDE + " && yarn rmadmin -refreshNodes -g " + GRACEFUL_DECOMMISSION.toSeconds()
+ " -server || { rm -f " + YARN_EXCLUDE + "; exit 1; }; fi",
"if ! cmp -s " + DFS_EXCLUDE + ".new " + DFS_EXCLUDE + "; then mv " + DFS_EXCLUDE + ".new "
+ DFS_EXCLUDE + " && hdfs dfsadmin -refreshNodes || { rm -f " + DFS_EXCLUDE + "; exit 1; }; fi");
try {
ContainerExec.Result result = ContainerExec.run(lifecycleManager.getDockerClient(), hdfsName(clusterId),
new String[]{"bash", "-c", script}, NODE_COMMAND_SECONDS);
if (result.exitCode() != 0) {
LOG.warnv("Could not tell EMR cluster {0} which nodes to decommission, which the next round tries"
+ " again: {1}", clusterId, result.stderr());
}
} catch (RuntimeException e) {
LOG.warnv(e, "Could not tell EMR cluster {0} which nodes to decommission, which the next round tries"
+ " again: {1}", clusterId, e.getMessage());
}
}
private static String hostLines(List<String> hosts) {
return hosts.stream().map(host -> host + "\\n").collect(Collectors.joining());
}
// A thread's work: each node being decommissioned goes once HDFS and YARN have let it, or the time it was given is
// up, and its containers' logs with it. It ends once the last core node to go is dead to the NameNode, or with its
// cluster or a teardown. A round that fails, Docker or a command on the primary node failing, leaves every node as it
// is, and the next asks again.
private void decommission(NodeRequest request, long teardown) {
String clusterId = request.clusterId();
boolean ended = false;
boolean failing = false;
try {
while (true) {
try {
synchronized (starting.computeIfAbsent(clusterId, id -> new Object())) {
if (decommissionRound(request, teardown)) {
// Under the lock, so a resize from now on starts a thread of its own.
decommissioning.remove(clusterId);
ended = true;
return;
}
}
failing = false;
} catch (RuntimeException e) {
if (failing) {
LOG.debugv(e, "Could not decommission the nodes of EMR cluster {0} again: {1}", clusterId,
e.getMessage());
} else {
LOG.warnv(e, "Could not decommission the nodes of EMR cluster {0}, which the next round tries"
+ " again: {1}", clusterId, e.getMessage());
}
failing = true;
}
Thread.sleep(decommissionPoll.toMillis());
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
if (!ended) {
decommissioning.remove(clusterId);
}
}
}
// One round of a cluster's decommissioning, under its lock: true once there is nothing left to do.
private boolean decommissionRound(NodeRequest request, long teardown) {
String clusterId = request.clusterId();
Map<String, Draining> leaving = draining.get(clusterId);
if (leaving == null || teardowns.get() != teardown) {
return true;
}
Map<String, Long> gone = departed.computeIfAbsent(clusterId, id -> new ConcurrentHashMap<>());
long now = nanoTime.getAsLong();
gone.values().removeIf(at -> now - at >= DEAD_NODE_WAIT.toNanos());
syncExcludes(clusterId, leaving.values());
for (Map.Entry<String, Draining> node : List.copyOf(leaving.entrySet())) {
boolean late = now >= node.getValue().deadline();
if (late || decommissioned(request, node.getKey(), node.getValue(), teardown)) {
if (late) {
LOG.warnv("Node {0} of EMR cluster {1} was not decommissioned in time, and goes anyway",
node.getValue().host(), clusterId);
}
if (removeDecommissioned(request, node.getKey())) {
leaving.remove(node.getKey());
if (node.getValue().core()) {
gone.put(node.getValue().host(), nanoTime.getAsLong());
}
}
} else if (!node.getValue().hdfsDone() && hdfsDecommissioned(clusterId, node.getValue())) {
// YARN is told on the next round.
leaving.put(node.getKey(), node.getValue().hdfsDecommissioned());
}
}
if (leaving.isEmpty() && gone.isEmpty()) {
syncExcludes(clusterId, leaving.values());
return true;
}
return false;
}
// Whether YARN has finished with a node HDFS has finished with, or it has stopped with nothing left for HDFS to move.
// A core node that stopped before HDFS moved its blocks holds them still, so it starts again on its data, and one
// Docker cannot tell the state of is asked about again on the next round.
private boolean decommissioned(NodeRequest request, String name, Draining node, long teardown) {
ContainerLiveness liveness = lifecycleManager.probeContainer(name);
if (liveness == ContainerLiveness.UNKNOWN) {
return false;
}
if (liveness == ContainerLiveness.NOT_RUNNING) {
if (node.hdfsDone()) {
return true;
}
LOG.infov("The core node {0} of EMR cluster {1} stopped before HDFS moved its blocks, and starts again on"
+ " its data", node.host(), request.clusterId());
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() + "\"'");
}
// 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()
+ ":9866[^}]*Decommissioned'");
}
private boolean onPrimary(String clusterId, String command) {
return ContainerExec.run(lifecycleManager.getDockerClient(), hdfsName(clusterId),
new String[]{"bash", "-c", command}, NODE_COMMAND_SECONDS).exitCode() == 0;
}
// A node that has been decommissioned goes, with its data, as an EC2 instance's disks go with it, its containers'
// logs in S3 first, while its container is there. Whether it has gone: one Docker keeps, or keeps the data of, is
// tried again on the next round.
private boolean removeDecommissioned(NodeRequest request, String name) {
if (request.yarn().logFolder() != null && runningNodes.contains(name)) {
archiveNodeLogs(request.clusterId(), name, request.accountId(), request.region(),
request.yarn().logFolder());
}
if (!removeNode(name, true)) {
LOG.warnv("Docker kept node {0} of EMR cluster {1} or its data, which the next round removes",
name, request.clusterId());
return false;
}
LOG.infov("Node {0} of EMR cluster {1} was decommissioned", name, request.clusterId());
return true;
}
// Removes a node's container and, when asked, its volume; a removal Docker refuses leaves it known, so the next
// reset or shutdown tries again. Whether it has gone.
private boolean removeNode(String name, boolean withVolume) {
try {
lifecycleManager.removeIfExistsStrict(name);
} catch (RuntimeException e) {
LOG.warnv(e, "Could not remove the EMR node container {0}: {1}", name, e.getMessage());
return false;
}
runningNodes.remove(name);
archivedLogs.remove(name);
return !withVolume || lifecycleManager.removeVolume(name);
}
private record NodeRequest(String clusterId, String accountId, String region, String host, String imageId,
Yarn yarn) {
NodeRequest resizedTo(Yarn resized) {
return new NodeRequest(clusterId, accountId, region, host, imageId, resized);
}
}
// A node being decommissioned, which goes anyway at the nanoTime deadline, its own, so one a later resize adds has
// the whole time too. A core node goes to YARN's decommission only once HDFS has moved its blocks: a decommissioned
// NodeManager exits, which ends its container, the DataNode with it.
private record Draining(String host, boolean core, boolean hdfsDone, long deadline) {
Draining(String host, boolean core, long deadline) {
this(host, core, !core, deadline);
}
Draining hdfsDecommissioned() {
return new Draining(host, core, true, deadline);
}
}
@@ -560,9 +1099,17 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
.withDockerNetwork(Optional.of(shared ? network : name))
.withLogRotation()
.withLabels(labels(clusterId, accountId, region, HDFS_COMPONENT));
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);
}
if (yarn != null) {
spec.withEnv(YARN_MEMORY_VARIABLE, String.valueOf(yarn.memoryMb()))
.withEnv(YARN_VCORES_VARIABLE, String.valueOf(yarn.vcores()));
.withEnv(YARN_VCORES_VARIABLE, String.valueOf(yarn.vcores()))
.withEnv(REPLICATION_VARIABLE, String.valueOf(yarn.replication()));
if (!yarn.primaryWorks()) {
spec.withEnv(NODE_WORKERS_VARIABLE, "1");
}
if (yarn.hadoopFolder() != null) {
spec.withEnv(HADOOP_FOLDER_VARIABLE, yarn.hadoopFolder());
}
@@ -700,7 +1247,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
// What a node that did not become ready last wrote, in Floci's log, as the container goes with its cluster.
private void logNodeOutput(String clusterId, String containerId) {
LOG.warnv("The primary node of EMR cluster {0} did not become ready. It last wrote:\n{1}", clusterId,
LOG.warnv("A node of EMR cluster {0}, {1}, did not become ready. It last wrote:\n{2}", clusterId, containerId,
lifecycleManager.lastLogLines(containerId, NODE_LOG_LINES, NODE_LOG_READ));
}
@@ -717,6 +1264,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
}
}
// The name of a cluster's core or task node's container, and of the volume its data is in.
private String nodeName(String clusterId, Node node) {
return ContainerStorageHelper.dockerName(config, SERVICE + "-" + clusterId + "-node-" + node.id());
}
// The name of a cluster's HDFS container, of the volume its data is in, and of the Docker network it is on.
private String hdfsName(String clusterId) {
return ContainerStorageHelper.dockerName(config, SERVICE + "-" + clusterId + "-hdfs");
@@ -735,6 +1287,23 @@ 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);
nodeRequests.remove(clusterId);
draining.remove(clusterId);
departed.remove(clusterId);
boolean nodesGone = true;
try {
for (String node : nodeContainers(clusterId).keySet()) {
nodesGone &= removeNode(node, true);
}
// A node's data whose container a shutdown removed, which no list of containers finds.
for (String volume : nodeVolumes(clusterId).keySet()) {
nodesGone &= lifecycleManager.removeVolume(volume);
}
} catch (RuntimeException e) {
// The rest is removed all the same, and the cluster's storage is asked for again.
LOG.warnv(e, "Could not find the nodes of EMR cluster {0} to remove: {1}", clusterId, e.getMessage());
nodesGone = false;
}
boolean containerGone = removeKnown(hdfsName(clusterId));
SparkJobRunner.Storage storage = volumes(clusterId);
// Each is tried, so one Docker refused does not keep the others.
@@ -742,7 +1311,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
boolean homeGone = lifecycleManager.removeVolume(storage.home());
boolean mntGone = lifecycleManager.removeVolume(storage.mnt());
return lifecycleManager.removeVolume(hdfsName(clusterId)) && mntGone && homeGone && networkGone
&& containerGone;
&& containerGone && nodesGone;
}
/**
@@ -754,6 +1323,12 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
@Override
public void stopManagedContainers() {
teardowns.incrementAndGet();
nodeRequests.clear();
draining.clear();
departed.clear();
for (String name : List.copyOf(runningNodes)) {
removeNode(name, false);
}
for (String name : List.copyOf(running)) {
removeKnown(name);
}
@@ -786,6 +1361,21 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
@Override
public void removeAllBut(Set<String> kept) {
// Each sweep on its own, so Docker refusing one list does not keep the others from going.
try {
for (Container container : lifecycleManager.getDockerClient().listContainersCmd().withShowAll(true)
.withLabelFilter(Map.of(ContainerStorageHelper.COMPONENT_LABEL, NODE_COMPONENT,
ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)))
.exec()) {
Map<String, String> labels = container.getLabels() != null ? container.getLabels() : Map.of();
String name = container.getNames()[0].substring(1);
runningNodes.add(name);
if (!kept.contains(labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL))) {
removeNode(name, false);
}
}
} catch (RuntimeException e) {
LOG.warnv(e, "Could not remove the nodes of EMR clusters that have ended: {0}", e.getMessage());
}
try {
for (Container container : lifecycleManager.getDockerClient().listContainersCmd().withShowAll(true)
.withLabelFilter(Map.of(ContainerStorageHelper.COMPONENT_LABEL, HDFS_COMPONENT,
@@ -332,8 +332,10 @@ public class EmrHandler {
for (EmrInstanceGroup group : cluster.getInstanceGroups()) {
int count = listedInstanceCount(group, terminated);
int first = group == primary ? 1 : next;
int number = EmrService.groupNumber(cluster.getInstanceGroups(), group);
for (int i = 0; i < count; i++) {
arr.add(syntheticInstanceNode(cluster, group, first + i, terminated));
arr.add(syntheticInstanceNode(cluster, group, first + i, EmrService.privateIpAddress(number, i + 1),
terminated));
}
if (group != primary) {
next += count;
@@ -752,13 +754,12 @@ public class EmrHandler {
return node;
}
private ObjectNode syntheticInstanceNode(EmrCluster cluster, EmrInstanceGroup group, int index,
private ObjectNode syntheticInstanceNode(EmrCluster cluster, EmrInstanceGroup group, int index, String privateIp,
boolean terminated) {
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()));
String privateIp = EmrService.privateIpAddress(index);
node.put("PrivateDnsName", AwsRegions.ec2PrivateIpDnsName(privateIp, cluster.getRegion()));
node.put("PrivateIpAddress", privateIp);
node.put("InstanceGroupId", group.getId());
@@ -132,6 +132,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
private final String dockerNetwork;
// What the NodeManager of a cluster that runs YARN offers its containers.
private final ClusterStorage.Yarn nodeManager;
private final int maxWorkerNodes;
// The steps a thread is running, by account and id; a RUNNING container step not here was left by a restart.
private final Set<String> executing = new HashSet<>();
// Likewise the clusters a thread is bootstrapping.
@@ -253,6 +254,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
this.dockerNetwork = config.services().emr().dockerNetwork().orElse(null);
this.nodeManager = new ClusterStorage.Yarn(config.services().emr().yarnNodeMemoryMb(),
config.services().emr().yarnNodeVcores());
this.maxWorkerNodes = config.services().emr().yarnMaxWorkerNodes();
this.lifecycle = new EmrClusterLifecycle(config.services().emr().clusterStartupDelaySeconds(),
config.services().emr().stepDurationSeconds(),
config.services().emr().clusterTerminationDelaySeconds(), eventPublisher,
@@ -389,6 +391,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
f.setProvisionedSpotCapacity(f.getTargetSpotCapacity());
f.setState("RUNNING");
}
cluster.setProvisionedCoreNodes(coreNodes(cluster));
cluster.getSteps().forEach(step -> step.setId("s-" + randomId(13)));
lifecycle.start(cluster, now(), region);
store(cluster);
@@ -575,6 +578,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
ids.add(group.getId());
}
clusterStore.put(clusterId, cluster);
resizeNodes(cluster);
return ids;
});
}
@@ -630,6 +634,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
}
}
touched.forEach(clusterStore::put);
touched.values().forEach(this::resizeNodes);
});
}
@@ -669,6 +674,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
fleet.setState("RUNNING");
cluster.getInstanceFleets().add(fleet);
clusterStore.put(clusterId, cluster);
resizeNodes(cluster);
return fleet.getId();
});
}
@@ -712,6 +718,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
fleet.setProvisionedOnDemandCapacity(onDemand);
fleet.setProvisionedSpotCapacity(spot);
clusterStore.put(clusterId, cluster);
resizeNodes(cluster);
});
}
@@ -1516,8 +1523,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
String clusterId = cluster.getId();
String hdfsHost = masterPrivateDnsName(cluster);
String hdfsImage = hdfsImage(cluster.getReleaseLabel());
ClusterStorage.Yarn nodeYarn = yarn
? nodeManager.withHadoopFolder(EmrReleaseImages.hadoopFolder(cluster.getReleaseLabel())) : null;
Supplier<ClusterStorage.Yarn> nodeYarn = yarn ? currentYarn(cluster, accountId, region) : null;
ClusterStorage.HiveMetastore hiveMetastore = EmrSparkSteps.installsHive(cluster.getReleaseLabel(),
cluster.getApplications(), SNAPSHOT_MAPPER)
? new ClusterStorage.HiveMetastore(instanceProfileRole(cluster, accountId),
@@ -1692,6 +1698,118 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
return () -> releaseImages.image(release, spark, hive, withHive);
}
/**
* The YARN a cluster runs: the service's capacity on each node, its core and task nodes, its HDFS's copies. Its
* primary node holds a DataNode and a NodeManager unless the cluster was created with core nodes that run, so one
* created without keeps both as core nodes are added, the blocks it holds staying in reach.
*/
private ClusterStorage.Yarn yarnOf(EmrCluster cluster) {
List<ClusterStorage.Node> nodes = workerNodes(cluster);
long coreNodes = nodes.stream().filter(ClusterStorage.Node::core).count();
return nodeManager.withHadoopFolder(EmrReleaseImages.hadoopFolder(cluster.getReleaseLabel()))
.onNodes(nodes, (int) Math.max(1, Math.min(replication(cluster), coreNodes)),
EmrSparkSteps.containerLogFolder(cluster))
.withPrimaryWorking(cluster.getProvisionedCoreNodes() == 0 || coreNodes == 0);
}
// What a cluster asks of YARN when it is read, which may be later than now; what it asks now, if it has gone by then.
private Supplier<ClusterStorage.Yarn> currentYarn(EmrCluster cluster, String accountId, String region) {
String clusterId = cluster.getId();
ClusterStorage.Yarn asked = yarnOf(cluster);
return () -> RequestScopes.callAs(accountId, region,
() -> call(() -> clusterStore.get(clusterId).map(this::yarnOf).orElse(asked)));
}
// A resize reaches the nodes of a cluster a step has started them on, on another thread, as they take a while;
// on any other cluster the first step starts those it asks for then.
private void resizeNodes(EmrCluster cluster) {
if (cluster.isStorageCreated() && runsYarn(cluster)) {
Supplier<ClusterStorage.Yarn> yarn = currentYarn(cluster, regionResolver.getAccountId(), regionOf(cluster));
String clusterId = cluster.getId();
stepExecutor.execute(() -> clusterStorage.resize(clusterId, yarn));
}
}
// A cluster's core and task nodes as containers: "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". No more than the setting allows, core
// nodes first, as they hold HDFS, and no fewer core nodes than HDFS keeps copies, as "Amazon EMR will not allow
// clusters to scale core nodes below dfs.replication". A fleet's unit of capacity is one node.
private List<ClusterStorage.Node> workerNodes(EmrCluster cluster) {
int floor = Math.min(cluster.getProvisionedCoreNodes(), replication(cluster));
List<ClusterStorage.Node> core = new ArrayList<>();
List<ClusterStorage.Node> task = new ArrayList<>();
for (EmrInstanceGroup group : cluster.getInstanceGroups()) {
boolean isCore = "CORE".equals(group.getInstanceGroupType());
if (isCore || "TASK".equals(group.getInstanceGroupType())) {
int count = group.getRequestedInstanceCount();
addNodes(cluster, groupNumber(cluster.getInstanceGroups(), group), isCore ? Math.max(count, floor) : count,
isCore, isCore ? core : task);
}
}
EmrInstanceFleet primaryFleet = cluster.getInstanceFleets().stream()
.filter(fleet -> "MASTER".equals(fleet.getInstanceFleetType())).findFirst().orElse(null);
int number = 1;
for (EmrInstanceFleet fleet : cluster.getInstanceFleets()) {
if (fleet == primaryFleet) {
continue;
}
boolean isCore = "CORE".equals(fleet.getInstanceFleetType());
int count = fleet.getTargetOnDemandCapacity() + fleet.getTargetSpotCapacity();
addNodes(cluster, number++, isCore ? Math.max(count, floor) : count, isCore, isCore ? core : task);
}
List<ClusterStorage.Node> nodes = new ArrayList<>(core);
nodes.addAll(task);
if (nodes.size() > maxWorkerNodes) {
LOG.infov("EMR cluster {0} asks for {1} core and task nodes, and runs the first {2}, as yarn-max-worker-nodes"
+ " says", cluster.getId(), nodes.size(), maxWorkerNodes);
return List.copyOf(nodes.subList(0, maxWorkerNodes));
}
return nodes;
}
private static void addNodes(EmrCluster cluster, int group, int count, boolean core,
List<ClusterStorage.Node> nodes) {
for (int ordinal = 1; ordinal <= count; ordinal++) {
nodes.add(new ClusterStorage.Node(group + "-" + ordinal,
AwsRegions.ec2PrivateIpDnsName(privateIpAddress(group, ordinal), cluster.getRegion()), core));
}
}
// "Amazon EMR sets this value based on the number of core nodes the cluster is provisioned with": 1 "for clusters
// that are provisioned with less than four core nodes", 2 "for clusters that are provisioned with less than ten
// core nodes", 3 "for all other clusters". "To overwrite the default value, use the hdfs-site classification."
private int replication(EmrCluster cluster) {
String configured = EmrSparkSteps.hdfsSite(cluster.getConfigurations(), SNAPSHOT_MAPPER).get("dfs.replication");
if (configured != null) {
Integer copies = aboveZero(configured);
if (copies != null) {
return copies;
}
LOG.warnv("The dfs.replication of EMR cluster {0}, {1}, is not a whole number above zero, so it keeps EMR's"
+ " default", cluster.getId(), configured);
}
int core = cluster.getProvisionedCoreNodes();
return core < 4 ? 1 : core < 10 ? 2 : 3;
}
// The whole number a setting gives, when it is one above zero, else null.
private static Integer aboveZero(String setting) {
try {
int number = Integer.parseInt(setting.trim());
return number > 0 ? number : null;
} catch (NumberFormatException e) {
return null;
}
}
private static int coreNodes(EmrCluster cluster) {
int groups = cluster.getInstanceGroups().stream().filter(group -> "CORE".equals(group.getInstanceGroupType()))
.mapToInt(EmrInstanceGroup::getRequestedInstanceCount).sum();
int fleets = cluster.getInstanceFleets().stream().filter(fleet -> "CORE".equals(fleet.getInstanceFleetType()))
.mapToInt(fleet -> fleet.getTargetOnDemandCapacity() + fleet.getTargetSpotCapacity()).sum();
return groups + fleets;
}
/**
* Whether a cluster's primary node runs YARN, which its steps' Spark runs on: "the primary node runs the YARN
* ResourceManager service", and a core node "YARN NodeManager daemons, Hadoop MapReduce tasks, and Spark executors".
@@ -1820,9 +1938,33 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
return "i-" + String.format("%017d", index);
}
/** The private IPv4 address ListInstances gives a cluster's instance {@code index}, counted from 1. */
static String privateIpAddress(int index) {
return "10.0.0." + index;
/**
* 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.
*/
static String privateIpAddress(int group, int ordinal) {
return "10." + group + "." + (ordinal - 1) / 254 + "." + ((ordinal - 1) % 254 + 1);
}
/**
* A cluster's instance group's number in its instances' addresses: 0 for the primary node's group, the first MASTER
* group, and from 1 for the others in the order the cluster has them, which only adds to the end.
*/
static int groupNumber(List<EmrInstanceGroup> groups, EmrInstanceGroup group) {
EmrInstanceGroup primary = groups.stream().filter(EmrService::isMasterGroup).findFirst().orElse(null);
if (group == primary) {
return 0;
}
int number = 1;
for (EmrInstanceGroup other : groups) {
if (other == group) {
return number;
}
if (other != primary) {
number++;
}
}
throw new IllegalArgumentException("The instance group is not one of the cluster's");
}
// The primary instance's: the first of the MASTER group, which ListInstances numbers before the others.
@@ -1833,7 +1975,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
// The primary instance's private DNS name, as ListInstances gives it, which names the cluster's HDFS: the same
// while the other groups resize, so an hdfs:// path naming it keeps leading there.
static String masterPrivateDnsName(EmrCluster cluster) {
return AwsRegions.ec2PrivateIpDnsName(privateIpAddress(1), cluster.getRegion());
return AwsRegions.ec2PrivateIpDnsName(privateIpAddress(0, 1), cluster.getRegion());
}
static boolean isMasterGroup(EmrInstanceGroup group) {
@@ -53,6 +53,7 @@ final class EmrSparkSteps {
// The release pages' core-site, which will "Change values in Hadoop's core-site.xml file", and spark-log4j2,
// which will "Change values in Spark's log4j2.properties file".
private static final String CORE_SITE = "core-site";
private static final String HDFS_SITE = "hdfs-site";
private static final String SPARK_LOG4J2 = "spark-log4j2";
// And mapred-site, which will "Change values in the MapReduce application's mapred-site.xml file", hadoop-log4j
// "Change values in Hadoop's log4j.properties file", and hadoop-env "Change values in the Hadoop environment for
@@ -282,6 +283,11 @@ final class EmrSparkSteps {
return properties;
}
/** The properties of a cluster's {@code hdfs-site}, of which Floci's HDFS applies {@code dfs.replication}. */
static Map<String, String> hdfsSite(String configurations, ObjectMapper objectMapper) {
return properties(configurations, objectMapper, HDFS_SITE);
}
/** The properties of a cluster's {@code core-site}, which its steps' {@code hadoop} command gets too. */
static Map<String, String> coreSite(String configurations, ObjectMapper objectMapper) {
return properties(configurations, objectMapper, CORE_SITE);
@@ -56,6 +56,9 @@ public class EmrCluster {
// Whether the docker runner mode has made the cluster's storage, which goes once the cluster has ended; Floci's
// own, as the API has none.
private boolean storageCreated;
// The core nodes the cluster was created with, which its HDFS's copies of a block follow; Floci's own, as the API
// has none.
private int provisionedCoreNodes;
// The cluster's ManagedScalingPolicy and AutoTerminationPolicy as given, raw JSON; null when none.
private String managedScalingPolicy;
private String autoTerminationPolicy;
@@ -190,6 +193,9 @@ public class EmrCluster {
public boolean isStorageCreated() { return storageCreated; }
public void setStorageCreated(boolean storageCreated) { this.storageCreated = storageCreated; }
public int getProvisionedCoreNodes() { return provisionedCoreNodes; }
public void setProvisionedCoreNodes(int provisionedCoreNodes) { this.provisionedCoreNodes = provisionedCoreNodes; }
public String getManagedScalingPolicy() { return managedScalingPolicy; }
public void setManagedScalingPolicy(String managedScalingPolicy) { this.managedScalingPolicy = managedScalingPolicy; }
@@ -84,6 +84,9 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
private static final String HADOOP_SITE_VARIABLE = "FLOCI_HADOOP_SITE";
private static final String SPARK_LOG4J2_VARIABLE = "FLOCI_SPARK_LOG4J2";
private static final String MAPRED_SITE_VARIABLE = "FLOCI_MAPRED_SITE";
// The copies of a block a cluster's core nodes keep, as an hdfs-site.xml property: there, as the image's own says two
// and a Hadoop client reads hdfs-site.xml after core-site.xml.
private static final String HDFS_SITE_VARIABLE = "FLOCI_HDFS_SITE";
private static final String HADOOP_LOG4J_VARIABLE = "FLOCI_HADOOP_LOG4J";
private static final String HADOOP_ENV_VARIABLE = "FLOCI_HADOOP_ENV";
private static final Pattern SHELL_NAME = Pattern.compile("[A-Za-z_][A-Za-z0-9_]*");
@@ -167,6 +170,9 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
" }",
" site core-site.xml \"$" + HADOOP_SITE_VARIABLE + "\"",
" site mapred-site.xml \"$" + MAPRED_SITE_VARIABLE + "\"",
" if [ -n \"${" + HDFS_SITE_VARIABLE + ":-}\" ]; then",
" site hdfs-site.xml \"$" + HDFS_SITE_VARIABLE + "\"",
" fi",
" if [ ! -s \"$hadoop_conf/log4j.properties\" ]; then",
" printf '%s\\n' '" + String.join("' '", HADOOP_CONSOLE_LOG) + "' > \"$hadoop_conf/log4j.properties\"",
" fi",
@@ -415,6 +421,10 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
if (job.storage() != null && job.engine() == Engine.SPARK) {
container.withEnv(HADOOP_SITE_VARIABLE, hadoopSite(job, endpoint))
.withEnv(MAPRED_SITE_VARIABLE, mapredSite(job));
if (job.storage() != null && job.storage().replication() > 0) {
container.withEnv(HDFS_SITE_VARIABLE, siteProperty("dfs.replication",
String.valueOf(job.storage().replication())));
}
if (!job.hadoopLog4j().isEmpty()) {
container.withEnv(HADOOP_LOG4J_VARIABLE, hadoopLog4jFile(job));
}
@@ -516,7 +526,8 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
for (Container container : containers) {
Map<String, String> labels = container.getLabels() != null ? container.getLabels() : Map.of();
// A live EMR cluster's HDFS, which its storage keeps, carries the service's labels too.
if (Storage.HDFS_COMPONENT.equals(labels.get(ContainerStorageHelper.COMPONENT_LABEL))) {
String component = labels.get(ContainerStorageHelper.COMPONENT_LABEL);
if (Storage.HDFS_COMPONENT.equals(component) || Storage.NODE_COMPONENT.equals(component)) {
continue;
}
if (aliases.consistent(container.getId(), labels)
@@ -984,10 +995,18 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
}
// A cluster's HDFS, as Hadoop settings: its NameNode, on the cluster's primary node, which hdfs:// paths without a
// host, and paths without a scheme, lead to; none before it runs.
// host, and paths without a scheme, lead to, and, as it is a client that says how many copies of a block it writes
// and the image's hdfs-site.xml says two, the copies its core nodes keep; none before it runs.
private static List<SparkSetting> hdfsSettings(Storage storage) {
return storage == null || storage.hdfsHost() == null ? List.of()
: List.of(new SparkSetting("fs.defaultFS", "hdfs://" + storage.hdfsHost() + ":" + HDFS_PORT));
if (storage == null || storage.hdfsHost() == null) {
return List.of();
}
List<SparkSetting> settings = new ArrayList<>();
settings.add(new SparkSetting("fs.defaultFS", "hdfs://" + storage.hdfsHost() + ":" + HDFS_PORT));
if (storage.replication() > 0) {
settings.add(new SparkSetting("dfs.replication", String.valueOf(storage.replication())));
}
return settings;
}
// The cluster's HDFS for a MapReduce job in local mode, which reads the core-site.xml of the hadoop command's
@@ -112,10 +112,11 @@ public interface SparkJobRunner {
* node, named {@code hdfsHost}, which a step's container reaches at {@code hdfsAddress} on the Docker network
* {@code hdfsNetwork}, the cluster's own, which the container joins (all three null until it runs, the network
* also on the host's own network, which steps share with it); and, on a cluster with Hive or HCatalog, the URI of
* the Hive metastore service on that node, or null.
* the Hive metastore service on that node, or null; and how many copies of a block its HDFS keeps, when its core
* nodes hold it, else 0.
*/
record Storage(String home, String mnt, String hdfsHost, String hdfsAddress, String hdfsNetwork,
String hiveMetastore, String resourceManager, String flociEndpoint) {
String hiveMetastore, String resourceManager, String flociEndpoint, int replication) {
/**
* The component label of an EMR cluster's HDFS container, which carries its service's labels as a driver
@@ -123,19 +124,24 @@ public interface SparkJobRunner {
*/
public static final String HDFS_COMPONENT = "emr-hdfs";
/** The component label of an EMR cluster's core or task node's container, its storage's as the HDFS is. */
public static final String NODE_COMPONENT = "emr-node";
/** A cluster's volumes, before its HDFS runs. */
public Storage(String home, String mnt) {
this(home, mnt, null, null, null, null, null, null);
this(home, mnt, null, null, null, null, null, null, 0);
}
/** 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);
return new Storage(home, mnt, host, address, network, hiveMetastore, resourceManager, flociEndpoint,
replication);
}
/** 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);
return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, uri, resourceManager, flociEndpoint,
replication);
}
/**
@@ -143,7 +149,14 @@ public interface SparkJobRunner {
* Floci's address on the HDFS's network.
*/
public Storage withYarn(String host, String flociEndpoint) {
return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, hiveMetastore, host, flociEndpoint);
return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, hiveMetastore, host, flociEndpoint,
replication);
}
/** 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);
}
}