mirror of
https://github.com/floci-io/floci.git
synced 2026-11-26 23:29:28 -05:00
feat(emr): give each docker cluster a real HDFS on its primary node (#7496)
Every EMR cluster runs HDFS: its primary node "also runs the HDFS
NameNode service". In the docker runner mode a cluster's HDFS was a
folder of its /mnt volume behind a view of the hdfs scheme, so an
hdfs:// path naming a host was not served, hadoop fs -ls / failed, and
Hive, which looks up the encryption zone of any hdfs:// path, reached it
under viewfs, where a table at an hdfs:// location failed. Each cluster
now runs a NameNode and a DataNode.
- EmrClusterStorage starts them in a container of their own, from the
release's EMR Serverless Hive image, which has HDFS's daemons where
the release's image has only the client. It runs as root only to add
the primary node's name to its hosts file and give its data volume to
the hadoop user, then runs both daemons as that user, with one copy of
each block and permissions off, and makes /tmp and /user/hadoop once
the DataNode has joined. The data is in a volume of its own, so the
first container to mount the cluster's /mnt volume is still a step's,
which fills it with what the bootstrap actions left there. It is on a
Docker network of the cluster's own, which only the cluster's steps
join besides theirs, as its HDFS serves its files to any client that
reaches it, so another cluster's steps, another account's too, do not.
- The AWS runtime for Apache Spark's releases, emr-spark-8.0.0 on,
publish no Hive image, so their clusters run HDFS from emr-7.5.0's.
Hadoop keeps its client-server protocols compatible across a major
version's minor releases, so their newer client reaches its NameNode.
- A step's thread starts it after the cluster's volumes, from the id
its image's pull, when it is missing, resolves, and waits up to two
minutes from then, the
NameNode on its port its own, the DataNode joined and the NameNode out
of safe mode, as the NameNode's JMX says; a step that comes while
it starts waits, and one that finds it running uses it. A failure
fails the step ("The step could not start: ..."), and one whose
container Docker cannot tell the state of leaves it as it is.
- The daemons log their warnings and errors to the container's output.
- When either daemon exits, the container ends and its readiness goes,
so the next step starts it again on the data its volume keeps; one
that finds it about to stop starts it again once.
- Steps reach it by the primary instance's PrivateDnsName, as
ListInstances gives it, on port 8020: their containers resolve that
name to the HDFS container's address, and fs.defaultFS names it, so
hdfs:// paths without a host and paths without a scheme lead there.
ListInstances numbers the MASTER group's instance first, so the name
holds while other groups resize.
In a namespace the steps share, the host's or another container's,
which the HDFS container joins too, they reach it on its loopback, and
its daemons listen there only, so no other interface serves its files,
which any client could change; one cluster's HDFS runs there at a
time, another's refused while it does. One a process with another
docker-network left running, in another namespace than the steps', is
started again in theirs on its data. With none, steps have no network,
so the cluster runs no HDFS.
- Hadoop's local job runner copies a job's -files to
/tmp/hadoop/mapred/staging on the local file system, then looks for
them at that path of the default file system, as JobResourceUploader
drops the folder's scheme. So in the hadoop command's configuration,
which a custom JAR's MapReduce in the driver reads too, the hdfs
scheme is a view of the cluster's HDFS in which that one folder is
the container's own. Spark and Hive keep HDFS's own client, as Hive
casts an hdfs:// file system to it to look up its encryption zone,
so a Spark step writes a Hive table in HDFS too.
- A reset or a shutdown removes the HDFS containers this process
started, found running or kept from an earlier process, after the
drivers that use them are stopped, and a step or a bootstrap handed to
its thread before it, however it then ends, starts no HDFS, driver or
successor after it but is left as one whose driver was stopped, and
none is handed to a thread until the reset is over; a container Docker
refuses to remove stays known for the next; a cluster's next step
starts its HDFS again on the data its volume keeps. The container and
its network go with the cluster's storage, and the startup sweep
removes those of clusters that are gone or have ended.
Every cluster now needs a Hive image, so the documentation of
image-template and hive-image-template says a mirror sets both.
The Docker-gated tests now cover a Hive table at an hdfs:// location, a
bootstrap action's file in /mnt, a structured streaming query keeping
its checkpoints in HDFS, a Spark step writing a Hive table there, hadoop
fs -ls /, and a DataNode that exits, after which the next step reads an
earlier step's file. The CI prefetch queues the Hive image for
EmrDockerRunnerDockerIntegrationTest's shard too.
This commit is contained in:
1 parent
a5291ca192
commit
3a64d2b761
23 files changed
+2300
-166
No files matched your search
@@ -2060,15 +2060,17 @@ public interface EmulatorConfig {
|
||||
/**
|
||||
* The image a {@code docker} step uses, with {@code %s} standing for the cluster's release label,
|
||||
* for example "registry.internal/emr-serverless/spark/%s:20250425". If omitted, Floci uses the
|
||||
* release's public EMR Serverless image on Amazon ECR Public.
|
||||
* release's public EMR Serverless image on Amazon ECR Public. Every cluster also runs its HDFS in
|
||||
* {@link #hiveImageTemplate()}'s image, so a mirror names both.
|
||||
*/
|
||||
Optional<String> imageTemplate();
|
||||
|
||||
/**
|
||||
* The EMR Serverless Hive image a {@code docker} cluster with Hive takes Hive from, into the image its
|
||||
* bootstrap and steps run in, as {@link #imageTemplate()} names the image Hive is added to, for example
|
||||
* "registry.internal/emr-serverless/hive/%s:20250425". If omitted, Floci uses the release's public EMR
|
||||
* Serverless Hive image on Amazon ECR Public.
|
||||
* The EMR Serverless Hive image every {@code docker} cluster runs its HDFS in, and a cluster with Hive takes
|
||||
* Hive from, into the image its bootstrap and steps run in, as {@link #imageTemplate()} names the image Hive
|
||||
* is added to, for example "registry.internal/emr-serverless/hive/%s:20250425". If omitted, Floci uses the
|
||||
* release's public EMR Serverless Hive image on Amazon ECR Public. An emr-spark-* release has none, so its
|
||||
* clusters run their HDFS in emr-7.5.0's.
|
||||
*/
|
||||
Optional<String> hiveImageTemplate();
|
||||
|
||||
|
||||
@@ -24,4 +24,13 @@ package io.github.hectorvent.floci.core.common;
|
||||
public interface ContainerTeardown {
|
||||
|
||||
void stopManagedContainers();
|
||||
|
||||
/**
|
||||
* Where this teardown runs among the others: {@link ContainerTeardowns#stopAll} runs them in ascending order,
|
||||
* those of one order as CDI lists them. One whose containers others' containers use, as an EMR cluster's HDFS its
|
||||
* steps' drivers, runs after them, so theirs are stopped first and do not fail against it.
|
||||
*/
|
||||
default int teardownOrder() {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import jakarta.enterprise.inject.Instance;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
@@ -25,7 +26,12 @@ public final class ContainerTeardowns {
|
||||
}
|
||||
|
||||
public static void stopAll(Instance<ContainerTeardown> teardowns, Logger log) {
|
||||
List<ContainerTeardown> ordered = new ArrayList<>();
|
||||
for (ContainerTeardown teardown : teardowns) {
|
||||
ordered.add(teardown);
|
||||
}
|
||||
ordered.sort(Comparator.comparingInt(ContainerTeardown::teardownOrder));
|
||||
for (ContainerTeardown teardown : ordered) {
|
||||
try {
|
||||
teardown.stopManagedContainers();
|
||||
} catch (Exception e) {
|
||||
|
||||
+45
@@ -1003,6 +1003,51 @@ public class ContainerLifecycleManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the bridge network {@code networkName} with {@code labels}, as {@link #ensureVolume(String, Map)} does a
|
||||
* volume, when Docker has no network of that name; one that exists is used as it is. Containers on it reach each
|
||||
* other, and containers on no other network reach them through it.
|
||||
*/
|
||||
public void ensureNetwork(String networkName, Map<String, String> labels) {
|
||||
try {
|
||||
dockerClient.inspectNetworkCmd().withNetworkId(networkName).exec();
|
||||
return;
|
||||
} catch (NotFoundException e) {
|
||||
// Made below.
|
||||
}
|
||||
dockerClient.createNetworkCmd()
|
||||
.withName(networkName)
|
||||
.withDriver("bridge")
|
||||
.withLabels(mergedLabels(labels))
|
||||
.exec();
|
||||
LOG.debugv("Created network {0}", networkName);
|
||||
}
|
||||
|
||||
/** Connects the created container {@code containerId} to {@code networkName} too, before it starts. */
|
||||
public void connectToNetwork(String containerId, String networkName) {
|
||||
dockerClient.connectToNetworkCmd()
|
||||
.withContainerId(containerId)
|
||||
.withNetworkId(networkName)
|
||||
.exec();
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the network {@code networkName}: true once it is gone, false when Docker kept it, as
|
||||
* {@link #removeVolume} says of a volume.
|
||||
*/
|
||||
public boolean removeNetwork(String networkName) {
|
||||
try {
|
||||
dockerClient.removeNetworkCmd(networkName).exec();
|
||||
LOG.debugv("Removed network {0}", networkName);
|
||||
return true;
|
||||
} catch (NotFoundException e) {
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Error removing network {0}: {1}", networkName, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds an existing container by name.
|
||||
*
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.emr;
|
||||
import io.github.hectorvent.floci.services.emrserverless.SparkJobRunner;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
/**
|
||||
* A cluster's storage in the EMR {@code docker} runner mode: the disks of its primary node, which every one of
|
||||
@@ -19,8 +20,18 @@ public interface ClusterStorage {
|
||||
void create(String clusterId, String accountId, String region);
|
||||
|
||||
/**
|
||||
* Removes the volumes of {@code clusterId}'s storage once it no longer needs them: true when they are gone,
|
||||
* false when Docker refused, so the caller can try again.
|
||||
* Starts {@code clusterId}'s HDFS, a NameNode and a DataNode keeping their data in a volume of their own, in a
|
||||
* container of {@code image} on a Docker network of the cluster's own, or on the host's when its steps run there,
|
||||
* unless it is running, and returns the cluster's storage with it: its primary node's {@code host} name, which a
|
||||
* step's container resolves to the address given, on the network given. A failure to start it 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, BooleanSupplier stopped);
|
||||
|
||||
/**
|
||||
* Removes {@code clusterId}'s HDFS and the volumes of its storage once it no longer needs them: true when the
|
||||
* volumes are gone, false when Docker refused, so the caller can try again.
|
||||
*/
|
||||
boolean remove(String clusterId);
|
||||
|
||||
@@ -29,4 +40,12 @@ public interface ClusterStorage {
|
||||
* restart, the storage of the clusters that are gone or have ended, and on a reset all of it.
|
||||
*/
|
||||
void removeAllBut(Set<String> kept);
|
||||
|
||||
/** A step stopped while it waited for its cluster's HDFS, by a cancel, its cluster's end or a teardown. */
|
||||
final class Stopped extends RuntimeException {
|
||||
|
||||
public Stopped(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,39 +2,148 @@ package io.github.hectorvent.floci.services.emr;
|
||||
|
||||
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.HostConfig;
|
||||
import com.github.dockerjava.api.model.Network;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig.EcsServiceConfig.ImagePullBehavior;
|
||||
import io.github.hectorvent.floci.core.common.ContainerTeardown;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerExec;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLiveness;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
|
||||
import io.github.hectorvent.floci.services.emrserverless.SparkJobRunner;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.function.LongSupplier;
|
||||
|
||||
/**
|
||||
* Keeps each EMR cluster's storage in two Docker volumes, one for its primary node's {@code /home/hadoop} and one
|
||||
* for its {@code /mnt}, where its HDFS is. Both paths belong to the image's {@code hadoop} user, and Docker gives
|
||||
* an empty volume what the image has at the path it is first mounted on, owner included, so the steps, which
|
||||
* run as that user, can write to both, and what the cluster's bootstrap left there comes with them.
|
||||
* Keeps each EMR cluster's storage in Docker volumes, one for its primary node's {@code /home/hadoop} and one for its
|
||||
* {@code /mnt}. Both paths belong to the image's {@code hadoop} user, and Docker gives an empty volume what the image
|
||||
* has at the path it is first mounted on, owner included, so the steps, which run as that user, can write to both,
|
||||
* and what the cluster's bootstrap left there comes with them. Its HDFS, which every EMR cluster runs (from
|
||||
* emr-7.14.0 on, "When you select Trino as the only application at launch, Amazon EMR no longer starts YARN and
|
||||
* HDFS", a cluster Floci does not run), is a NameNode and a DataNode in a container of their own, the cluster's
|
||||
* 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.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class EmrClusterStorage implements ClusterStorage {
|
||||
public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EmrClusterStorage.class);
|
||||
private static final String SERVICE = "emr";
|
||||
private static final String COMPONENT = "emr-storage";
|
||||
private static final String HDFS_COMPONENT = SparkJobRunner.Storage.HDFS_COMPONENT;
|
||||
private static final String HDFS_CONF = "/tmp/floci-hdfs-conf";
|
||||
private static final String HDFS_READY = "/tmp/floci-hdfs-ready";
|
||||
private static final String HOST_NETWORK = "host";
|
||||
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 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=";
|
||||
// How long a cluster's HDFS may take to start, its NameNode formatted the first time, before a step gives up.
|
||||
private static final Duration HDFS_START_TIMEOUT = Duration.ofSeconds(120);
|
||||
private static final Duration HDFS_POLL_INTERVAL = Duration.ofMillis(500);
|
||||
// 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, and HDFS_READY says it is ready. A
|
||||
// daemon that exits, before or after, ends the container, its readiness gone, so the next step starts it again on
|
||||
// its data.
|
||||
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",
|
||||
"chown hadoop:hadoop /mnt || exit",
|
||||
"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",
|
||||
"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.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>"
|
||||
+ "<value>$FLOCI_HDFS_BIND:9870</value></property>\""
|
||||
+ " \"<property><name>dfs.datanode.address</name><value>$FLOCI_HDFS_BIND:9866</value></property>\""
|
||||
+ " \"<property><name>dfs.datanode.http.address</name>"
|
||||
+ "<value>$FLOCI_HDFS_BIND:9864</value></property>\""
|
||||
+ " \"<property><name>dfs.datanode.ipc.address</name>"
|
||||
+ "<value>$FLOCI_HDFS_BIND:9867</value></property>\""
|
||||
+ " '</configuration>' > " + HDFS_CONF + "/hdfs-site.xml",
|
||||
"printf '%s\\n' 'log4j.rootLogger=WARN,console' 'log4j.appender.console=org.apache.log4j.ConsoleAppender'"
|
||||
+ " 'log4j.appender.console.layout=org.apache.log4j.PatternLayout'"
|
||||
+ " 'log4j.appender.console.layout.ConversionPattern=%d %p %c: %m%n'"
|
||||
+ " > " + HDFS_CONF + "/log4j.properties",
|
||||
"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 & "
|
||||
+ "until curl -sf -m 5 \"" + NAMENODE_JMX + "NameNodeInfo\""
|
||||
+ " | grep -q \"\\\"ClusterId\\\" : \\\"$cid\\\"\"; do "
|
||||
+ "[ \"$(jobs -rp | wc -l)\" = 2 ] || exit 1; sleep 0.2; done; "
|
||||
+ "until curl -sf -m 5 \"" + NAMENODE_JMX + "FSNamesystemState\""
|
||||
+ " | grep -q \"\\\"NumLiveDataNodes\\\" : 1,\"; do "
|
||||
+ "[ \"$(jobs -rp | wc -l)\" = 2 ] || exit 1; sleep 0.2; done; "
|
||||
+ "until curl -sf -m 5 \"" + NAMENODE_JMX + "NameNodeInfo\""
|
||||
+ " | grep -q \"\\\"Safemode\\\" : \\\"\\\"\"; do "
|
||||
+ "[ \"$(jobs -rp | wc -l)\" = 2 ] || exit 1; sleep 0.2; done; "
|
||||
+ "hdfs dfs -mkdir -p /tmp /user/hadoop || exit 1; "
|
||||
+ "touch " + HDFS_READY + "; "
|
||||
+ "wait -n; 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.
|
||||
private final Map<String, Object> starting = 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();
|
||||
private final ContainerLifecycleManager lifecycleManager;
|
||||
private final ContainerBuilder containerBuilder;
|
||||
private final EmulatorConfig config;
|
||||
private final Duration hdfsStartTimeout;
|
||||
private final LongSupplier nanoTime;
|
||||
// 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();
|
||||
|
||||
@Inject
|
||||
public EmrClusterStorage(ContainerLifecycleManager lifecycleManager, EmulatorConfig config) {
|
||||
public EmrClusterStorage(ContainerLifecycleManager lifecycleManager, ContainerBuilder containerBuilder,
|
||||
EmulatorConfig config) {
|
||||
this(lifecycleManager, containerBuilder, config, HDFS_START_TIMEOUT, System::nanoTime);
|
||||
}
|
||||
|
||||
EmrClusterStorage(ContainerLifecycleManager lifecycleManager, ContainerBuilder containerBuilder,
|
||||
EmulatorConfig config, Duration hdfsStartTimeout, LongSupplier nanoTime) {
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.config = config;
|
||||
this.hdfsStartTimeout = hdfsStartTimeout;
|
||||
this.nanoTime = nanoTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -46,25 +155,321 @@ public class EmrClusterStorage implements ClusterStorage {
|
||||
|
||||
@Override
|
||||
public void create(String clusterId, String accountId, String region) {
|
||||
Map<String, String> labels = new LinkedHashMap<>(ContainerStorageHelper.resourceIdentityLabels(SERVICE,
|
||||
clusterId, accountId, region));
|
||||
labels.put(ContainerStorageHelper.COMPONENT_LABEL, COMPONENT);
|
||||
labels.put(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config));
|
||||
Map<String, String> labels = labels(clusterId, accountId, region, COMPONENT);
|
||||
SparkJobRunner.Storage storage = volumes(clusterId);
|
||||
lifecycleManager.ensureVolume(storage.home(), labels);
|
||||
lifecycleManager.ensureVolume(storage.mnt(), labels);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SparkJobRunner.Storage hdfs(String clusterId, String accountId, String region, String host, String image,
|
||||
String dockerNetwork, BooleanSupplier stopped) {
|
||||
String name = hdfsName(clusterId);
|
||||
String network = network(dockerNetwork);
|
||||
if (NO_NETWORK.equals(network)) {
|
||||
// Its steps have no network, so no HDFS reaches them: they run as without one.
|
||||
return volumes(clusterId);
|
||||
}
|
||||
long teardown = teardowns.get();
|
||||
stopIfStopped(clusterId, teardown, stopped);
|
||||
// Its image is there first, pulled when missing: the first pull of the Hive image, 2.7 GB, is no part of the
|
||||
// HDFS's start, which the deadline gives two minutes from then, a step waiting while another starts it too.
|
||||
// It starts from the id that pull resolved, which another pull of the same tag cannot move.
|
||||
String imageId = lifecycleManager.resolveImageForLaunch(containerBuilder.resolveImage(image),
|
||||
ImagePullBehavior.PREFER_CACHED, null).imageId();
|
||||
boolean shared = sharesNamespace(network);
|
||||
long deadline = nanoTime.getAsLong() + hdfsStartTimeout.toNanos();
|
||||
synchronized (starting.computeIfAbsent(clusterId, id -> new Object())) {
|
||||
String containerId = null;
|
||||
// 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);
|
||||
ContainerLiveness liveness = lifecycleManager.probeContainer(name);
|
||||
if (liveness == ContainerLiveness.UNKNOWN) {
|
||||
// Docker did not answer: one that may be serving the cluster's other steps is left as it is.
|
||||
throw new IllegalStateException("Could not tell whether the HDFS of EMR cluster " + clusterId
|
||||
+ " runs");
|
||||
}
|
||||
boolean found = liveness == ContainerLiveness.RUNNING && attempt == 0
|
||||
&& inStepsNamespace(name, shared ? network : name);
|
||||
// Known before it starts, so a teardown while it starts removes it.
|
||||
running.add(name);
|
||||
String candidate = found ? name : start(clusterId, accountId, region, host, imageId, dockerNetwork);
|
||||
if (awaitReady(clusterId, candidate, deadline, teardown, stopped)) {
|
||||
containerId = candidate;
|
||||
} else if (!found) {
|
||||
stopIfStopped(clusterId, teardown, stopped);
|
||||
throw new IllegalStateException("The HDFS of EMR cluster " + clusterId
|
||||
+ " stopped before it was ready");
|
||||
}
|
||||
}
|
||||
if (shared) {
|
||||
return volumes(clusterId).withHdfs(host, LOOPBACK, null);
|
||||
}
|
||||
return volumes(clusterId).withHdfs(host, address(clusterId, containerId), name);
|
||||
}
|
||||
}
|
||||
|
||||
// Where a step reaches the cluster's HDFS: its container's address on the cluster's own Docker network.
|
||||
private String address(String clusterId, String containerId) {
|
||||
String address = lifecycleManager.resolveContainerNetworkIp(containerId, hdfsName(clusterId));
|
||||
if (address == null || address.isBlank()) {
|
||||
throw new IllegalStateException("The HDFS of EMR cluster " + clusterId
|
||||
+ " has no address on Docker network " + hdfsName(clusterId));
|
||||
}
|
||||
return address;
|
||||
}
|
||||
|
||||
// Whether the HDFS container found running is in the namespace the steps run in, as its network mode says: the
|
||||
// cluster's own network, the host's, or the same container's; one a process with another docker-network left
|
||||
// goes, and starts again on its data.
|
||||
private boolean inStepsNamespace(String name, String stepsNetwork) {
|
||||
HostConfig hostConfig = lifecycleManager.getDockerClient().inspectContainerCmd(name).exec().getHostConfig();
|
||||
String networkMode = hostConfig != null ? hostConfig.getNetworkMode() : null;
|
||||
return Objects.equals(namespaceOf(networkMode), namespaceOf(stepsNetwork));
|
||||
}
|
||||
|
||||
// The namespace a network mode puts a container in, the same for a container's name and its id: the network,
|
||||
// the host's, or the id of the container whose namespace it shares.
|
||||
private String namespaceOf(String networkMode) {
|
||||
if (networkMode == null || !networkMode.startsWith(CONTAINER_NETWORK_PREFIX)) {
|
||||
return networkMode;
|
||||
}
|
||||
String owner = networkMode.substring(CONTAINER_NETWORK_PREFIX.length());
|
||||
try {
|
||||
return CONTAINER_NETWORK_PREFIX
|
||||
+ lifecycleManager.getDockerClient().inspectContainerCmd(owner).exec().getId();
|
||||
} catch (RuntimeException e) {
|
||||
return networkMode;
|
||||
}
|
||||
}
|
||||
|
||||
// The network steps run on: docker-network's, else the global one, else Floci's own.
|
||||
private String network(String dockerNetwork) {
|
||||
return containerBuilder.resolveDockerNetwork(Optional.ofNullable(dockerNetwork)).orElse(null);
|
||||
}
|
||||
|
||||
// Whether the steps run in a network namespace they share, the host's or a container's, which the HDFS shares
|
||||
// too, as Docker joins a container placed there to no other network.
|
||||
private static boolean sharesNamespace(String network) {
|
||||
return HOST_NETWORK.equals(network) || network != null && network.startsWith(CONTAINER_NETWORK_PREFIX);
|
||||
}
|
||||
|
||||
// A cluster's HDFS container, started anew on the HDFS data its volume holds, which goes with the cluster's other
|
||||
// two; 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 serves its files to any client that reaches it: the steps of
|
||||
// other clusters, of other accounts too, do not. In a namespace the steps share it listens on the loopback alone.
|
||||
private String start(String clusterId, String accountId, String region, String host, String imageId,
|
||||
String dockerNetwork) {
|
||||
String network = network(dockerNetwork);
|
||||
if (!sharesNamespace(network)) {
|
||||
return createContainer(clusterId, accountId, region, host, imageId, network, false);
|
||||
}
|
||||
// One namespace holds one HDFS's ports, whose daemons would answer this one's readiness and its steps: the look
|
||||
// for another cluster's and this one's start go together, so two clusters' steps cannot both pass it.
|
||||
synchronized (sharedNamespaceStarts) {
|
||||
String other = otherRunningHdfs(clusterId, network);
|
||||
if (other != null) {
|
||||
throw new IllegalStateException("The HDFS of EMR cluster " + clusterId + " cannot start while that of"
|
||||
+ " EMR cluster " + other + " runs in the network namespace they share");
|
||||
}
|
||||
return createContainer(clusterId, accountId, region, host, imageId, network, true);
|
||||
}
|
||||
}
|
||||
|
||||
// Creates and starts the container start() decided on, in the namespace the steps share or on a network of its
|
||||
// cluster's own.
|
||||
private String createContainer(String clusterId, String accountId, String region, String host, String imageId,
|
||||
String network, boolean shared) {
|
||||
String name = hdfsName(clusterId);
|
||||
// One left stopped goes first, and a removal Docker refuses fails the start as it is, not as a name clash.
|
||||
lifecycleManager.removeIfExistsStrict(name);
|
||||
lifecycleManager.ensureVolume(name, labels(clusterId, accountId, region, COMPONENT));
|
||||
if (!shared) {
|
||||
lifecycleManager.ensureNetwork(name, labels(clusterId, accountId, region, HDFS_COMPONENT));
|
||||
}
|
||||
ContainerSpec spec = containerBuilder.newContainer(imageId)
|
||||
.withName(name)
|
||||
.withUser("root")
|
||||
.withEntrypoint(List.of("/bin/bash", "-c", HDFS_SCRIPT))
|
||||
.withEnv("FLOCI_HDFS_HOST", host)
|
||||
.withEnv("FLOCI_HDFS_BIND", shared ? LOOPBACK : "0.0.0.0")
|
||||
.withEnv("HADOOP_CONF_DIR", HDFS_CONF)
|
||||
.withEnv("HADOOP_LOG_DIR", "/tmp/floci-hdfs-logs")
|
||||
.withNamedVolume(name, "/mnt")
|
||||
.withDockerNetwork(Optional.of(shared ? network : name))
|
||||
.withLogRotation()
|
||||
.withLabels(labels(clusterId, accountId, region, HDFS_COMPONENT))
|
||||
.build();
|
||||
String containerId = lifecycleManager.createAndStart(spec).containerId();
|
||||
LOG.infov("Started the HDFS of EMR cluster {0} as {1}", clusterId, host);
|
||||
return containerId;
|
||||
}
|
||||
|
||||
// The cluster of another HDFS container of this deployment running in the namespace network gives, or null.
|
||||
private String otherRunningHdfs(String clusterId, String network) {
|
||||
for (Container container : lifecycleManager.getDockerClient().listContainersCmd()
|
||||
.withLabelFilter(Map.of(ContainerStorageHelper.COMPONENT_LABEL, HDFS_COMPONENT,
|
||||
ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)))
|
||||
.exec()) {
|
||||
String other = container.getLabels() != null
|
||||
? container.getLabels().get(ContainerStorageHelper.RESOURCE_ID_LABEL) : null;
|
||||
// Only one in this very namespace holds its ports, not one on its own network or in another namespace.
|
||||
String networkMode = container.getHostConfig() != null ? container.getHostConfig().getNetworkMode() : null;
|
||||
if (other != null && !other.equals(clusterId)
|
||||
&& Objects.equals(namespaceOf(networkMode), namespaceOf(network))) {
|
||||
return other;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Whether the container became ready by the deadline, false when it stopped first, or the step did, or a teardown
|
||||
// has run since it asked; a failure to become ready in time is thrown.
|
||||
private boolean awaitReady(String clusterId, String containerId, long deadline, long teardown,
|
||||
BooleanSupplier stopped) {
|
||||
while (teardowns.get() == teardown && !stopped.getAsBoolean()) {
|
||||
// Docker refuses an exec into a container that has stopped, so that is looked at first.
|
||||
if (lifecycleManager.probeContainer(containerId) == ContainerLiveness.NOT_RUNNING) {
|
||||
return false;
|
||||
}
|
||||
long exitCode;
|
||||
try {
|
||||
exitCode = ContainerExec.run(lifecycleManager.getDockerClient(), containerId,
|
||||
new String[]{"test", "-f", HDFS_READY}, 10).exitCode();
|
||||
} catch (RuntimeException e) {
|
||||
// It may have stopped after it was looked at, which makes Docker refuse the exec.
|
||||
if (lifecycleManager.probeContainer(containerId) == ContainerLiveness.NOT_RUNNING) {
|
||||
return false;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
if (exitCode == 0) {
|
||||
return true;
|
||||
}
|
||||
if (nanoTime.getAsLong() >= deadline) {
|
||||
throw new IllegalStateException("The HDFS of EMR cluster " + clusterId + " did not start within "
|
||||
+ hdfsStartTimeout.toSeconds() + " seconds");
|
||||
}
|
||||
try {
|
||||
Thread.sleep(HDFS_POLL_INTERVAL.toMillis());
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("Stopped waiting for the HDFS of EMR cluster " + clusterId, e);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// A teardown since the step asked for its cluster's HDFS stops the step as it would its driver, and the container
|
||||
// goes, one the step started after the teardown looked too; a step past starting otherwise, by a cancel, its
|
||||
// cluster's end or a teardown that has not reached the HDFS yet, stops and leaves it to the cluster's other steps.
|
||||
private void stopIfStopped(String clusterId, long teardown, BooleanSupplier stopped) {
|
||||
if (teardowns.get() != teardown) {
|
||||
removeKnown(hdfsName(clusterId));
|
||||
throw new ClusterStorage.Stopped("Floci stopped the HDFS of EMR cluster " + clusterId);
|
||||
}
|
||||
if (stopped.getAsBoolean()) {
|
||||
throw new ClusterStorage.Stopped("A step of EMR cluster " + clusterId + " stopped while its HDFS started");
|
||||
}
|
||||
}
|
||||
|
||||
// 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");
|
||||
}
|
||||
|
||||
private Map<String, String> labels(String clusterId, String accountId, String region, String component) {
|
||||
Map<String, String> labels = new LinkedHashMap<>(ContainerStorageHelper.resourceIdentityLabels(SERVICE,
|
||||
clusterId, accountId, region));
|
||||
labels.put(ContainerStorageHelper.COMPONENT_LABEL, component);
|
||||
labels.put(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config));
|
||||
return labels;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean remove(String clusterId) {
|
||||
// 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);
|
||||
boolean containerGone = removeKnown(hdfsName(clusterId));
|
||||
SparkJobRunner.Storage storage = volumes(clusterId);
|
||||
// Both are tried, so one Docker refused does not keep the other.
|
||||
// Each is tried, so one Docker refused does not keep the others.
|
||||
boolean networkGone = lifecycleManager.removeNetwork(hdfsName(clusterId));
|
||||
boolean homeGone = lifecycleManager.removeVolume(storage.home());
|
||||
return lifecycleManager.removeVolume(storage.mnt()) && homeGone;
|
||||
boolean mntGone = lifecycleManager.removeVolume(storage.mnt());
|
||||
return lifecycleManager.removeVolume(hdfsName(clusterId)) && mntGone && homeGone && networkGone
|
||||
&& containerGone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the HDFS containers this process has started or found running, so a reset or a shutdown leaves none
|
||||
* running; a cluster's next step starts its HDFS again, on the data its volume keeps. A step waiting for one
|
||||
* stops, as its driver would, and removes one it started since. This runs after the teardowns of the drivers,
|
||||
* which use the HDFS, so theirs stop first.
|
||||
*/
|
||||
@Override
|
||||
public void stopManagedContainers() {
|
||||
teardowns.incrementAndGet();
|
||||
for (String name : List.copyOf(running)) {
|
||||
removeKnown(name);
|
||||
}
|
||||
}
|
||||
|
||||
// Removes an HDFS container, forgetting it only once Docker says it is gone: one Docker keeps stays known, so the
|
||||
// next reset or shutdown tries again. Whether it is gone.
|
||||
private boolean removeKnown(String name) {
|
||||
try {
|
||||
lifecycleManager.removeIfExistsStrict(name);
|
||||
running.remove(name);
|
||||
return true;
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not remove the HDFS container {0}: {1}", name, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int teardownOrder() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
@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, HDFS_COMPONENT,
|
||||
ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)))
|
||||
.exec()) {
|
||||
Map<String, String> labels = container.getLabels() != null ? container.getLabels() : Map.of();
|
||||
String clusterId = labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL);
|
||||
if (!kept.contains(clusterId)) {
|
||||
// Known first, so one Docker refuses to remove stays for the next reset or shutdown to remove.
|
||||
String name = clusterId != null ? hdfsName(clusterId) : container.getId();
|
||||
running.add(name);
|
||||
removeKnown(name);
|
||||
} else {
|
||||
// A cluster still up keeps the HDFS an earlier process left, which a reset or a shutdown removes.
|
||||
running.add(hdfsName(clusterId));
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not remove the HDFS of EMR clusters that have ended: {0}", e.getMessage());
|
||||
}
|
||||
try {
|
||||
for (Network network : lifecycleManager.getDockerClient().listNetworksCmd()
|
||||
.withFilter("label", List.of(ContainerStorageHelper.COMPONENT_LABEL + "=" + HDFS_COMPONENT,
|
||||
ContainerStorageHelper.OWNER_LABEL + "=" + ContainerStorageHelper.ownerIdentity(config)))
|
||||
.exec()) {
|
||||
Map<String, String> labels = network.getLabels() != null ? network.getLabels() : Map.of();
|
||||
if (!kept.contains(labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL))) {
|
||||
lifecycleManager.removeNetwork(network.getName());
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not remove the HDFS networks of EMR clusters that have ended: {0}", e.getMessage());
|
||||
}
|
||||
try {
|
||||
ListVolumesResponse response = lifecycleManager.getDockerClient().listVolumesCmd()
|
||||
.withFilter("label", List.of(ContainerStorageHelper.COMPONENT_LABEL + "=" + COMPONENT,
|
||||
@@ -79,7 +484,7 @@ public class EmrClusterStorage implements ClusterStorage {
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Could not remove the storage of EMR clusters that have ended: {0}", e.getMessage());
|
||||
LOG.warnv(e, "Could not remove the storage of EMR clusters that have ended: {0}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -323,11 +323,20 @@ public class EmrHandler {
|
||||
|| (terminated && !withinTerminatedInstanceRetention(cluster.getEndDateTime(), Instant.now()))) {
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
int n = 1;
|
||||
// Listed in their groups' order, the first MASTER group's instances numbered first, so the primary node keeps
|
||||
// its id and address, DescribeCluster's MasterPublicDnsName, while the other groups resize, as an instance
|
||||
// does; any other group's follow, each after those before it.
|
||||
EmrInstanceGroup primary = cluster.getInstanceGroups().stream().filter(EmrService::isMasterGroup)
|
||||
.findFirst().orElse(null);
|
||||
int next = primary == null ? 1 : 1 + listedInstanceCount(primary, terminated);
|
||||
for (EmrInstanceGroup group : cluster.getInstanceGroups()) {
|
||||
int count = listedInstanceCount(group, terminated);
|
||||
int first = group == primary ? 1 : next;
|
||||
for (int i = 0; i < count; i++) {
|
||||
arr.add(syntheticInstanceNode(cluster, group, n++, terminated));
|
||||
arr.add(syntheticInstanceNode(cluster, group, first + i, terminated));
|
||||
}
|
||||
if (group != primary) {
|
||||
next += count;
|
||||
}
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
@@ -749,7 +758,7 @@ public class EmrHandler {
|
||||
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 = "10.0.0." + index;
|
||||
String privateIp = EmrService.privateIpAddress(index);
|
||||
node.put("PrivateDnsName", AwsRegions.ec2PrivateIpDnsName(privateIp, cluster.getRegion()));
|
||||
node.put("PrivateIpAddress", privateIp);
|
||||
node.put("InstanceGroupId", group.getId());
|
||||
|
||||
@@ -8,6 +8,7 @@ import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.core.common.ContainerTeardown;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.Pagination;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
@@ -55,6 +56,8 @@ import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
@@ -76,7 +79,7 @@ import java.util.function.Supplier;
|
||||
* BOOTSTRAPPING, and leave the image its steps then run in.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class EmrService implements Resettable, StoredResourceArns {
|
||||
public class EmrService implements Resettable, StoredResourceArns, ContainerTeardown {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EmrService.class);
|
||||
private static final String UPPER_ALNUM = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
@@ -98,6 +101,10 @@ public class EmrService implements Resettable, StoredResourceArns {
|
||||
"On the master instance (%s), bootstrap action %d could not be read from %s: %s";
|
||||
private static final String BOOTSTRAP_NOT_RUN = "Floci could not run the bootstrap actions: %s";
|
||||
static final String BOOTSTRAP_INTERRUPTED = "Floci stopped while the cluster's bootstrap actions were running.";
|
||||
// The release whose EMR Serverless Hive image runs the HDFS of a cluster of the AWS runtime for Apache Spark,
|
||||
// which publishes none. Hadoop keeps its wire protocols compatible across a major version's minor releases, so
|
||||
// a newer client, such as the runtime's, reaches its NameNode.
|
||||
static final String SPARK_RUNTIME_HDFS_RELEASE = "emr-7.5.0";
|
||||
|
||||
private final AccountAwareStorageBackend<EmrCluster> clusterStore;
|
||||
private final StorageBackend<String, SecurityConfiguration> secConfigStore;
|
||||
@@ -133,6 +140,12 @@ public class EmrService implements Resettable, StoredResourceArns {
|
||||
private final Set<String> storageBeingRemoved = new HashSet<>();
|
||||
// Raised by each reset, so a step's thread from before it writes nothing back after the wipe.
|
||||
private long generation;
|
||||
// How many teardowns, by a reset or a shutdown, have begun: a step handed to its thread before one starts no HDFS
|
||||
// and no driver after it.
|
||||
private final AtomicLong teardowns = new AtomicLong();
|
||||
// From a teardown until its reset is over, no step or bootstrap is handed to a thread: a cluster a wakeup moves on
|
||||
// meanwhile would start containers after the teardowns that remove them. After a shutdown's, never again.
|
||||
private volatile boolean tornDown;
|
||||
|
||||
private static final Set<String> COMPUTE_LIMITS_UNIT_TYPES = Set.of("InstanceFleetUnits", "Instances", "VCPU");
|
||||
private static final Set<String> SCALING_STRATEGIES = Set.of("DEFAULT", "ADVANCED");
|
||||
@@ -295,6 +308,28 @@ public class EmrService implements Resettable, StoredResourceArns {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A reset's or a shutdown's teardown has begun: a step handed to its thread before it, whose driver the runner's
|
||||
* teardown cannot stop yet, starts no HDFS and no driver after it, as its progress reads it, but stops as a
|
||||
* stopped driver does. This runs before the teardowns that stop containers.
|
||||
*/
|
||||
@Override
|
||||
public synchronized void stopManagedContainers() {
|
||||
teardowns.incrementAndGet();
|
||||
tornDown = true;
|
||||
}
|
||||
|
||||
/** A reset is over: steps and bootstraps are handed to threads again. */
|
||||
@Override
|
||||
public synchronized void afterReset() {
|
||||
tornDown = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int teardownOrder() {
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* A reset has begun: the steps' and bootstraps' threads from before it write nothing more, so the storage
|
||||
* wipe that follows leaves none of their clusters behind, and the images bootstrap left, and the clusters'
|
||||
@@ -1406,7 +1441,8 @@ public class EmrService implements Resettable, StoredResourceArns {
|
||||
}
|
||||
|
||||
/** A step handed to a thread: whose it is, where, and under which reset. */
|
||||
private record StepLaunch(String accountId, String region, String clusterId, String stepId, long launchedIn) {}
|
||||
private record StepLaunch(String accountId, String region, String clusterId, String stepId, long launchedIn,
|
||||
long teardownsBefore) {}
|
||||
|
||||
/** Starts each step a cluster runs on a thread of its own, which ends the step once it is done. */
|
||||
private final class ContainerSteps implements EmrClusterLifecycle.StepExecution {
|
||||
@@ -1414,6 +1450,12 @@ public class EmrService implements Resettable, StoredResourceArns {
|
||||
@Override
|
||||
public void start(EmrCluster cluster, EmrStep step, String region) {
|
||||
String accountId = regionResolver.getAccountId();
|
||||
if (tornDown) {
|
||||
// Left RUNNING and counted as running, as a step whose driver the teardown stopped: the reset wipes it,
|
||||
// a restart fails it.
|
||||
executing.add(stepKey(accountId, step.getId()));
|
||||
return;
|
||||
}
|
||||
EmrSparkSteps.HiveCommand hive = EmrSparkSteps.hive(step, cluster.getApplications(),
|
||||
cluster.getConfigurations(), SNAPSHOT_MAPPER);
|
||||
List<String> application = hive == null ? EmrSparkSteps.application(step) : null;
|
||||
@@ -1427,6 +1469,14 @@ public class EmrService implements Resettable, StoredResourceArns {
|
||||
// which the step's thread makes, or the release's.
|
||||
String image = cluster.getBootstrapImage() != null ? cluster.getBootstrapImage() : imageTemplate;
|
||||
Supplier<String> releaseImage = cluster.getBootstrapImage() == null ? releaseImage(cluster) : null;
|
||||
// Every EMR cluster runs HDFS on its primary node, which the step's thread starts when it is not running:
|
||||
// a NameNode and a DataNode, in a container of the release's Hive image, the one with HDFS's daemons.
|
||||
String clusterId = cluster.getId();
|
||||
String hdfsHost = masterPrivateDnsName(cluster);
|
||||
String hdfsImage = hdfsImage(cluster.getReleaseLabel());
|
||||
Function<BooleanSupplier, SparkJobRunner.Storage> hdfs = storage == null ? null
|
||||
: stopped -> clusterStorage.hdfs(clusterId, accountId, region, hdfsHost, hdfsImage, dockerNetwork,
|
||||
stopped);
|
||||
SparkJobRunner.Job job;
|
||||
if (hive != null) {
|
||||
job = new SparkJobRunner.Job(SERVICE, step.getId(), accountId, region, cluster.getReleaseLabel(),
|
||||
@@ -1451,9 +1501,10 @@ public class EmrService implements Resettable, StoredResourceArns {
|
||||
EmrSparkSteps.hadoopLog4j(cluster.getConfigurations(), SNAPSHOT_MAPPER),
|
||||
EmrSparkSteps.hadoopEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER));
|
||||
}
|
||||
StepLaunch launch = new StepLaunch(accountId, region, cluster.getId(), step.getId(), generation);
|
||||
StepLaunch launch = new StepLaunch(accountId, region, cluster.getId(), step.getId(), generation,
|
||||
teardowns.get());
|
||||
executing.add(stepKey(accountId, step.getId()));
|
||||
stepExecutor.execute(() -> runStep(job, launch, releaseImage));
|
||||
stepExecutor.execute(() -> runStep(job, launch, releaseImage, hdfs));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -1464,7 +1515,8 @@ public class EmrService implements Resettable, StoredResourceArns {
|
||||
|
||||
// A step's thread: its driver runs to its end, or the step fails at once when Floci does not run its kind. A
|
||||
// cluster with Hive's image is made first, when it is not there yet, so a failure to make it fails the step.
|
||||
private void runStep(SparkJobRunner.Job job, StepLaunch launch, Supplier<String> releaseImage) {
|
||||
private void runStep(SparkJobRunner.Job job, StepLaunch launch, Supplier<String> releaseImage,
|
||||
Function<BooleanSupplier, SparkJobRunner.Storage> hdfs) {
|
||||
String failure;
|
||||
if (job == null) {
|
||||
failure = EmrSparkSteps.NOT_RUN;
|
||||
@@ -1474,15 +1526,26 @@ public class EmrService implements Resettable, StoredResourceArns {
|
||||
try {
|
||||
SparkJobRunner.Job running = releaseImage != null && !progress.cancelled()
|
||||
? job.inImage(releaseImage.get()) : job;
|
||||
// The cluster's storage is there before its first step's container mounts it. A step a cancel,
|
||||
// its cluster's end or a reset has passed does not start, so it makes none.
|
||||
// The cluster's storage is there, its HDFS running, before its first step's container mounts it. A step
|
||||
// a cancel, its cluster's end or a reset has passed does not start, so it makes none.
|
||||
if (job.storage() != null && !progress.cancelled()) {
|
||||
clusterStorage.create(launch.clusterId(), launch.accountId(), launch.region());
|
||||
running = running.onStorage(hdfs.apply(progress::cancelled));
|
||||
}
|
||||
outcome = sparkRunner.run(running, progress);
|
||||
} catch (ClusterStorage.Stopped e) {
|
||||
// It stopped while its HDFS started, before its driver did, as a driver stopped then would.
|
||||
outcome = SparkJobRunner.Outcome.halted();
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "EMR step {0} could not run", launch.stepId());
|
||||
outcome = SparkJobRunner.Outcome.couldNotStart(e.getMessage());
|
||||
if (progress.cancelled() || Thread.currentThread().isInterrupted()) {
|
||||
// A teardown, a cancel or Floci's shutdown cut its start short, as it would have a driver.
|
||||
LOG.warnv(e, "EMR step {0} stopped while it started, as this failed: {1}", launch.stepId(),
|
||||
e.getMessage());
|
||||
outcome = SparkJobRunner.Outcome.halted();
|
||||
} else {
|
||||
LOG.warnv(e, "EMR step {0} could not run", launch.stepId());
|
||||
outcome = SparkJobRunner.Outcome.couldNotStart(e.getMessage());
|
||||
}
|
||||
}
|
||||
// A reset since the step started has swept the storage and wiped its cluster, so nothing would remove
|
||||
// volumes made, or mounted, after its sweep: they go now, the step's container being gone.
|
||||
@@ -1495,11 +1558,20 @@ public class EmrService implements Resettable, StoredResourceArns {
|
||||
}
|
||||
failure = failureOf(job, outcome);
|
||||
}
|
||||
RequestScopes.runAs(launch.accountId(), launch.region(), () -> run(() -> stepEnded(launch, failure)));
|
||||
// A teardown since the step was handed off ends it as it does a driver, whatever it ran to: ending it now
|
||||
// could start the next step after the teardown has passed. The service's lock orders the two.
|
||||
RequestScopes.runAs(launch.accountId(), launch.region(), () -> run(() -> {
|
||||
if (teardowns.get() != launch.teardownsBefore()) {
|
||||
driverStopped(launch);
|
||||
} else {
|
||||
stepEnded(launch, failure);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
/** A cluster handed to a bootstrap thread: whose it is, where, and under which reset. */
|
||||
private record BootstrapLaunch(String accountId, String region, String clusterId, long launchedIn) {}
|
||||
private record BootstrapLaunch(String accountId, String region, String clusterId, long launchedIn,
|
||||
long teardownsBefore) {}
|
||||
|
||||
/** Runs each cluster's bootstrap actions on a thread of its own, which ends its BOOTSTRAPPING. */
|
||||
private final class ContainerBootstrap implements EmrClusterLifecycle.BootstrapExecution {
|
||||
@@ -1507,13 +1579,20 @@ public class EmrService implements Resettable, StoredResourceArns {
|
||||
@Override
|
||||
public void start(EmrCluster cluster, String region) {
|
||||
String accountId = regionResolver.getAccountId();
|
||||
if (tornDown) {
|
||||
// Left BOOTSTRAPPING and counted as bootstrapping, as one the teardown stopped: the reset wipes it, a
|
||||
// restart ends it.
|
||||
bootstrapping.add(clusterKey(accountId, cluster.getId()));
|
||||
return;
|
||||
}
|
||||
// "logs/<cluster-id>/node/<primary-instance-id>/bootstrap-actions/<action-number>/stdout.gz"
|
||||
String logFolder = EmrServerlessSparkRunner.logFolder(cluster.getLogUri(),
|
||||
cluster.getId() + "/node/" + masterInstanceId(cluster) + "/bootstrap-actions/");
|
||||
BootstrapRunner.Bootstrap bootstrap = new BootstrapRunner.Bootstrap(cluster.getId(), accountId, region,
|
||||
cluster.getReleaseLabel(), imageTemplate, dockerNetwork, instanceProfileRole(cluster, accountId),
|
||||
bootstrapActions(cluster), logFolder);
|
||||
BootstrapLaunch launch = new BootstrapLaunch(accountId, region, cluster.getId(), generation);
|
||||
BootstrapLaunch launch = new BootstrapLaunch(accountId, region, cluster.getId(), generation,
|
||||
teardowns.get());
|
||||
Supplier<String> releaseImage = releaseImage(cluster);
|
||||
bootstrapping.add(clusterKey(accountId, cluster.getId()));
|
||||
stepExecutor.execute(() -> runBootstrap(bootstrap, launch, releaseImage));
|
||||
@@ -1543,6 +1622,16 @@ public class EmrService implements Resettable, StoredResourceArns {
|
||||
return () -> releaseImages.image(release, spark, hive);
|
||||
}
|
||||
|
||||
/**
|
||||
* The image a cluster runs its HDFS in: its release's EMR Serverless Hive image, which has HDFS's daemons, or, for
|
||||
* a release of the AWS runtime for Apache Spark, which has no Hive image, {@link #SPARK_RUNTIME_HDFS_RELEASE}'s.
|
||||
*/
|
||||
private String hdfsImage(String releaseLabel) {
|
||||
String release = EmrServerlessSparkRunner.sparkRuntime(releaseLabel) ? SPARK_RUNTIME_HDFS_RELEASE
|
||||
: releaseLabel;
|
||||
return EmrServerlessSparkRunner.image(hiveImageTemplate, release, SparkJobRunner.Engine.HIVE);
|
||||
}
|
||||
|
||||
// A cluster's BootstrapActionConfig list, as RunJobFlow stored it once it had checked it.
|
||||
private static List<BootstrapRunner.Action> bootstrapActions(EmrCluster cluster) {
|
||||
List<BootstrapRunner.Action> actions = new ArrayList<>();
|
||||
@@ -1565,8 +1654,9 @@ public class EmrService implements Resettable, StoredResourceArns {
|
||||
// removed it, before the thread ran; a failure to make it ends the cluster as one to run the bootstrap does.
|
||||
private void runBootstrap(BootstrapRunner.Bootstrap bootstrap, BootstrapLaunch launch,
|
||||
Supplier<String> releaseImage) {
|
||||
BooleanSupplier cancelled = () -> !RequestScopes.callAs(launch.accountId(), launch.region(),
|
||||
() -> stillBootstrapping(launch));
|
||||
// A teardown since the bootstrap was handed off stops it as it does a step, before it runs or as it goes.
|
||||
BooleanSupplier cancelled = () -> teardowns.get() != launch.teardownsBefore()
|
||||
|| !RequestScopes.callAs(launch.accountId(), launch.region(), () -> stillBootstrapping(launch));
|
||||
BootstrapRunner.Outcome outcome;
|
||||
try {
|
||||
outcome = bootstrapRunner.run(releaseImage != null && !cancelled.getAsBoolean()
|
||||
@@ -1576,8 +1666,17 @@ public class EmrService implements Resettable, StoredResourceArns {
|
||||
outcome = BootstrapRunner.Outcome.couldNotRun(e.getMessage());
|
||||
}
|
||||
BootstrapRunner.Outcome ended = outcome;
|
||||
RequestScopes.runAs(launch.accountId(), launch.region(),
|
||||
() -> run(() -> bootstrapEnded(bootstrap, launch, ended)));
|
||||
// One that ended, however, after a teardown began ends as one Floci stopped, which starts no step: the
|
||||
// service's lock orders the two.
|
||||
AtomicBoolean tornDownSince = new AtomicBoolean();
|
||||
RequestScopes.runAs(launch.accountId(), launch.region(), () -> run(() -> {
|
||||
tornDownSince.set(teardowns.get() != launch.teardownsBefore());
|
||||
bootstrapEnded(bootstrap, launch, tornDownSince.get() ? BootstrapRunner.Outcome.halted() : ended);
|
||||
}));
|
||||
// An image it committed as the teardown began goes, as no cluster starts from it.
|
||||
if (tornDownSince.get() && ended.image() != null) {
|
||||
bootstrapRunner.removeImage(ended.image());
|
||||
}
|
||||
}
|
||||
|
||||
// Whether a cluster's bootstrap may still start, or go on: one that ended, or a reset removed, is past it.
|
||||
@@ -1638,18 +1737,26 @@ public class EmrService implements Resettable, StoredResourceArns {
|
||||
return "i-" + String.format("%017d", index);
|
||||
}
|
||||
|
||||
// The primary instance's: the first of the MASTER group in the order ListInstances lists them.
|
||||
/** 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 primary instance's: the first of the MASTER group, which ListInstances numbers before the others.
|
||||
static String masterInstanceId(EmrCluster cluster) {
|
||||
int index = 1;
|
||||
for (EmrInstanceGroup group : cluster.getInstanceGroups()) {
|
||||
if ("MASTER".equals(group.getInstanceGroupType())) {
|
||||
return ec2InstanceId(index);
|
||||
}
|
||||
index += group.getRunningInstanceCount();
|
||||
}
|
||||
return ec2InstanceId(1);
|
||||
}
|
||||
|
||||
// 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());
|
||||
}
|
||||
|
||||
static boolean isMasterGroup(EmrInstanceGroup group) {
|
||||
return "MASTER".equals(group.getInstanceGroupType());
|
||||
}
|
||||
|
||||
/** What a step's thread asks the service while its driver goes: a step has no timeout to report. */
|
||||
private final class StepProgress implements SparkJobRunner.Progress {
|
||||
|
||||
@@ -1671,7 +1778,8 @@ public class EmrService implements Resettable, StoredResourceArns {
|
||||
|
||||
@Override
|
||||
public boolean cancelled() {
|
||||
return !RequestScopes.callAs(launch.accountId(), launch.region(), () -> stillRunning(launch));
|
||||
return teardowns.get() != launch.teardownsBefore()
|
||||
|| !RequestScopes.callAs(launch.accountId(), launch.region(), () -> stillRunning(launch));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+72
-35
@@ -62,12 +62,13 @@ import java.util.zip.GZIPOutputStream;
|
||||
* are unpacked into its working directory before the driver starts. The driver's output goes to
|
||||
* Floci's log and, while it runs, to the run's CloudWatch log streams, when it has some; once it ends, its
|
||||
* standard output and error go, gzipped, to the run's log folder in Floci's S3, when it has one. An EMR step's
|
||||
* container mounts its cluster's storage, where {@code hdfs://} paths, and paths without a scheme, lead, and a
|
||||
* step's {@code hadoop} command, and a MapReduce job its {@code spark-submit} starts, reach Floci's S3 and run
|
||||
* MapReduce in local mode, with the cluster's Hadoop configuration. A Hive run starts {@code hive} in a container of
|
||||
* the release's EMR Serverless Hive image instead, with Tez in local mode in Hive's JVM, S3A on Floci's S3 and the
|
||||
* Glue Data Catalog client, the image's metastore, on Floci's Glue; an EMR step's in the image of its cluster, which
|
||||
* holds Spark and Hive, on its storage, with the cluster's HDFS and the cluster's own metastore.
|
||||
* container mounts its cluster's storage and reaches its cluster's HDFS, where {@code hdfs://} paths, and paths
|
||||
* without a scheme, lead, and a step's {@code hadoop} command, and a MapReduce job its {@code spark-submit}
|
||||
* starts, reach Floci's S3 and run MapReduce in local mode, with the cluster's Hadoop configuration. A Hive run
|
||||
* starts {@code hive} in a container of the release's EMR Serverless Hive image instead, with Tez in local mode in
|
||||
* Hive's JVM, S3A on Floci's S3 and the Glue Data Catalog client, the image's metastore, on Floci's Glue; an EMR
|
||||
* step's in the image of its cluster, which holds Spark and Hive, on its storage, with the cluster's HDFS and the
|
||||
* cluster's own metastore.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardown {
|
||||
@@ -85,21 +86,18 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
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_]*");
|
||||
// A cluster's HDFS, as Hadoop settings: hdfs:// paths, and those without a scheme ("hdfs:// (or no prefix)"),
|
||||
// lead to the HDFS folder of the cluster's /mnt volume, through a view of it under the hdfs scheme, as the
|
||||
// image has no HDFS of its own.
|
||||
private static final String HDFS_FOLDER = "/mnt/hdfs";
|
||||
private static final List<SparkSetting> HDFS_SETTINGS = List.of(
|
||||
new SparkSetting("fs.defaultFS", "hdfs:///"),
|
||||
new SparkSetting("fs.hdfs.impl", "org.apache.hadoop.fs.viewfs.ViewFileSystemOverloadScheme"),
|
||||
new SparkSetting("fs.viewfs.mounttable.default.linkFallback", "file://" + HDFS_FOLDER));
|
||||
// Spark's default checkpoint manager goes through Hadoop's FileContext, which refuses an hdfs:// path
|
||||
// without a host, so a streaming query keeps its checkpoints through the file system instead.
|
||||
// The port of a cluster's NameNode, HDFS's own default, which hdfs:// paths and those without a scheme
|
||||
// ("hdfs:// (or no prefix)") reach through the cluster's primary node.
|
||||
private static final int HDFS_PORT = 8020;
|
||||
// Spark's default checkpoint manager goes through Hadoop's FileContext, which refuses an hdfs:// path without a
|
||||
// host, though "hdfs:///path-to-data" and "/path-to-data" "would resolve to the same location in HDFS", as the
|
||||
// Management Guide puts it; so a streaming query keeps its checkpoints through the file system instead.
|
||||
private static final SparkSetting FILE_SYSTEM_CHECKPOINTS = new SparkSetting(
|
||||
"spark.sql.streaming.checkpointFileManagerClass",
|
||||
"org.apache.spark.sql.execution.streaming.FileSystemBasedCheckpointFileManager");
|
||||
// Where Hadoop's local job runner puts a job's files, -files and -archives among them: a folder of the local
|
||||
// file system, whose files it then names by their path alone, which leads to the cluster's HDFS.
|
||||
// file system, whose files it then names by their path alone, which leads to the cluster's HDFS (see
|
||||
// localJobHdfsSettings).
|
||||
private static final String MAPRED_STAGING = "/tmp/hadoop/mapred/staging";
|
||||
// A step's MapReduce runs in the JVM that starts it, as there is no YARN to run it on.
|
||||
private static final String MAPRED_SITE = "<property><name>mapreduce.framework.name</name><value>local</value>"
|
||||
@@ -167,10 +165,6 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
" }",
|
||||
" site core-site.xml \"$" + HADOOP_SITE_VARIABLE + "\"",
|
||||
" site mapred-site.xml \"$" + MAPRED_SITE_VARIABLE + "\"",
|
||||
// The local staging folder is a link to the same path in the HDFS folder, so a job's files are where
|
||||
// their path leads.
|
||||
" mkdir -p \"" + HDFS_FOLDER + MAPRED_STAGING + "\" \"$(dirname " + MAPRED_STAGING + ")\"",
|
||||
" ln -sfn \"" + HDFS_FOLDER + MAPRED_STAGING + "\" " + MAPRED_STAGING,
|
||||
" if [ ! -s \"$hadoop_conf/log4j.properties\" ]; then",
|
||||
" printf '%s\\n' '" + String.join("' '", HADOOP_CONSOLE_LOG) + "' > \"$hadoop_conf/log4j.properties\"",
|
||||
" fi",
|
||||
@@ -243,15 +237,10 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
private static final List<SparkSetting> HIVE_SETTINGS = List.of(
|
||||
new SparkSetting("tez.local.mode", "true"),
|
||||
new SparkSetting("tez.am.client.am.port-range", "40000-40100"));
|
||||
// On a cluster, after the HDFS settings, Hive's file system is their view of the cluster's HDFS under the viewfs
|
||||
// scheme: Hive looks up the HDFS encryption zone of a path of the hdfs scheme, which only HDFS answers, as its
|
||||
// shim takes that path's file system for HDFS's own, so a table Hive makes in the cluster's HDFS is at a viewfs:
|
||||
// path, the folder an hdfs:// path leads to in other steps. Its metastore is the cluster's own, as "Hive records
|
||||
// metastore information in a MySQL database on the primary node's file system": an embedded Derby database in
|
||||
// the cluster's /mnt, whose tables DataNucleus creates on first use. A cluster's hive-site replaces them, with
|
||||
// the Glue Data Catalog's client factory for one.
|
||||
// On a cluster, Hive's metastore is the cluster's own, as "Hive records metastore information in a MySQL database
|
||||
// on the primary node's file system": an embedded Derby database in the cluster's /mnt, whose tables DataNucleus
|
||||
// creates on first use. A cluster's hive-site replaces it, with the Glue Data Catalog's client factory for one.
|
||||
private static final List<SparkSetting> HIVE_CLUSTER_SETTINGS = List.of(
|
||||
new SparkSetting("fs.defaultFS", "viewfs:///"),
|
||||
new SparkSetting("hive.metastore.client.factory.class",
|
||||
"org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClientFactory"),
|
||||
new SparkSetting("javax.jdo.option.ConnectionURL",
|
||||
@@ -393,6 +382,10 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
if (job.storage() != null) {
|
||||
container.withNamedVolume(job.storage().home(), "/home/hadoop")
|
||||
.withNamedVolume(job.storage().mnt(), "/mnt");
|
||||
// The primary node's name leads to its HDFS, as the cluster's DNS resolves it.
|
||||
if (job.storage().hdfsHost() != null) {
|
||||
container.withExtraHost(job.storage().hdfsHost(), job.storage().hdfsAddress());
|
||||
}
|
||||
}
|
||||
// Hive's settings reach it as --hiveconf settings, so only a Spark job's container sets up Hadoop.
|
||||
if (job.storage() != null && job.engine() == Engine.SPARK) {
|
||||
@@ -415,6 +408,10 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
.build();
|
||||
String containerId = lifecycleManager.create(spec);
|
||||
launch.started(containerId);
|
||||
// A cluster's HDFS is on a network of its own, which only its steps join.
|
||||
if (job.storage() != null && job.storage().hdfsNetwork() != null) {
|
||||
lifecycleManager.connectToNetwork(containerId, job.storage().hdfsNetwork());
|
||||
}
|
||||
// A stop, a reset or a shutdown while the image was pulled, the trust store copied or the archives put
|
||||
// in is read now, before the driver starts; one before an archive or while it streams in puts in no
|
||||
// more of them.
|
||||
@@ -491,6 +488,10 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
Container::getId);
|
||||
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))) {
|
||||
continue;
|
||||
}
|
||||
if (aliases.consistent(container.getId(), labels)
|
||||
&& aliases.matches(labels, ContainerStorageHelper.OWNER_LABEL, owner)) {
|
||||
lifecycleManager.removeIfExists(container.getId());
|
||||
@@ -564,10 +565,15 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
public static String image(String imageTemplate, String releaseLabel, Engine engine) {
|
||||
String template = imageTemplate != null ? imageTemplate
|
||||
: engine == Engine.HIVE ? HIVE_DEFAULT_IMAGE
|
||||
: releaseLabel.startsWith("emr-spark-") ? SPARK_RUNTIME_DEFAULT_IMAGE : DEFAULT_IMAGE;
|
||||
: sparkRuntime(releaseLabel) ? SPARK_RUNTIME_DEFAULT_IMAGE : DEFAULT_IMAGE;
|
||||
return template.formatted(releaseLabel);
|
||||
}
|
||||
|
||||
/** Whether {@code releaseLabel} is a release of the AWS runtime for Apache Spark, emr-spark-8.0.0 on. */
|
||||
public static boolean sparkRuntime(String releaseLabel) {
|
||||
return releaseLabel.startsWith("emr-spark-");
|
||||
}
|
||||
|
||||
/** A driver's environment: Floci's own variables, then the job's, one of which replaces Floci's of its name. */
|
||||
static List<String> environment(List<String> flocis, Map<String, String> jobs) {
|
||||
Map<String, String> byName = new LinkedHashMap<>();
|
||||
@@ -736,7 +742,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
List<SparkSetting> settings = new ArrayList<>(hadoopSettings(job, flociEndpoint));
|
||||
settings.addAll(HIVE_SETTINGS);
|
||||
if (job.storage() != null) {
|
||||
settings.addAll(HDFS_SETTINGS);
|
||||
settings.addAll(hdfsSettings(job.storage()));
|
||||
settings.addAll(HIVE_CLUSTER_SETTINGS);
|
||||
}
|
||||
List<String> arguments = new ArrayList<>();
|
||||
@@ -808,7 +814,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
*/
|
||||
static String hadoopSite(Job job, String flociEndpoint) {
|
||||
List<SparkSetting> settings = new ArrayList<>(hadoopSettings(job, flociEndpoint));
|
||||
settings.addAll(HDFS_SETTINGS);
|
||||
settings.addAll(localJobHdfsSettings(job.storage()));
|
||||
List<String> properties = new ArrayList<>();
|
||||
for (SparkSetting setting : settings) {
|
||||
properties.add(siteProperty(setting.key(), setting.value()));
|
||||
@@ -916,11 +922,42 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
new SparkSetting("aws.region", job.region()));
|
||||
}
|
||||
|
||||
// Floci's settings, then the job's spark-defaults, in the order a later one wins.
|
||||
// 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.
|
||||
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));
|
||||
}
|
||||
|
||||
// The cluster's HDFS for a MapReduce job in local mode, which reads the core-site.xml of the hadoop command's
|
||||
// configuration, a custom JAR's in the driver included: Hadoop's JobResourceUploader copies a job's files to
|
||||
// MAPRED_STAGING, on the local file system, then drops that folder's scheme, so the job looks for them at the
|
||||
// same path of the cluster's HDFS. The hdfs scheme is therefore a view of the cluster's HDFS in which that one
|
||||
// folder is the local one; the view names its mount table after the host alone. Spark and Hive keep HDFS's own
|
||||
// client (see sparkSettings), as Hive casts an hdfs:// file system to it to look up its encryption zones.
|
||||
private static List<SparkSetting> localJobHdfsSettings(Storage storage) {
|
||||
List<SparkSetting> settings = new ArrayList<>(hdfsSettings(storage));
|
||||
if (!settings.isEmpty()) {
|
||||
String mountTable = "fs.viewfs.mounttable." + storage.hdfsHost();
|
||||
settings.add(new SparkSetting("fs.hdfs.impl", "org.apache.hadoop.fs.viewfs.ViewFileSystemOverloadScheme"));
|
||||
settings.add(new SparkSetting("fs.viewfs.overload.scheme.target.hdfs.impl",
|
||||
"org.apache.hadoop.hdfs.DistributedFileSystem"));
|
||||
settings.add(new SparkSetting(mountTable + ".link." + MAPRED_STAGING, "file://" + MAPRED_STAGING));
|
||||
settings.add(new SparkSetting(mountTable + ".linkFallback",
|
||||
"hdfs://" + storage.hdfsHost() + ":" + HDFS_PORT));
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
|
||||
// Floci's settings, then the job's spark-defaults, in the order a later one wins. Spark's own Hadoop configuration
|
||||
// takes HDFS's client back from the core-site.xml's view, for Spark and its Hive client, which writes a Hive table
|
||||
// in HDFS only through it.
|
||||
private static List<SparkSetting> sparkSettings(Job job, String flociEndpoint) {
|
||||
List<SparkSetting> hadoop = new ArrayList<>(hadoopSettings(job, flociEndpoint));
|
||||
if (job.storage() != null) {
|
||||
hadoop.addAll(HDFS_SETTINGS);
|
||||
List<SparkSetting> hdfs = hdfsSettings(job.storage());
|
||||
hadoop.addAll(hdfs);
|
||||
if (!hdfs.isEmpty()) {
|
||||
hadoop.add(new SparkSetting("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem"));
|
||||
}
|
||||
List<SparkSetting> settings = new ArrayList<>();
|
||||
hadoop.forEach(setting -> settings.add(new SparkSetting("spark.hadoop." + setting.key(), setting.value())));
|
||||
|
||||
+30
-3
@@ -90,6 +90,14 @@ public interface SparkJobRunner {
|
||||
Map<String, String> sparkLog4j2, Map<String, String> mapredSite, Map<String, String> hadoopLog4j,
|
||||
Map<String, String> hadoopEnvironment) {
|
||||
|
||||
/** This job, on {@code storage}. */
|
||||
public Job onStorage(Storage storage) {
|
||||
return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage,
|
||||
dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder,
|
||||
cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j,
|
||||
hadoopEnvironment);
|
||||
}
|
||||
|
||||
/** This job, run in {@code image}. */
|
||||
public Job inImage(String image) {
|
||||
return new Job(service, runId, accountId, region, releaseLabel, engine, image, customImage, dockerNetwork,
|
||||
@@ -99,10 +107,29 @@ public interface SparkJobRunner {
|
||||
}
|
||||
|
||||
/**
|
||||
* The Docker volumes holding an EMR cluster's storage, which every one of its steps' containers mounts:
|
||||
* {@code home} at {@code /home/hadoop}, and {@code mnt} at {@code /mnt}, where its HDFS is.
|
||||
* An EMR cluster's storage: the Docker volumes every one of its steps' containers mounts, {@code home} at
|
||||
* {@code /home/hadoop} and {@code mnt} at {@code /mnt}; and its HDFS, whose NameNode is on the cluster's
|
||||
* primary 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).
|
||||
*/
|
||||
record Storage(String home, String mnt) {
|
||||
record Storage(String home, String mnt, String hdfsHost, String hdfsAddress, String hdfsNetwork) {
|
||||
|
||||
/**
|
||||
* The component label of an EMR cluster's HDFS container, which carries its service's labels as a driver
|
||||
* does but is the cluster's storage's to keep or remove, not a driver.
|
||||
*/
|
||||
public static final String HDFS_COMPONENT = "emr-hdfs";
|
||||
|
||||
/** A cluster's volumes, before its HDFS runs. */
|
||||
public Storage(String home, String mnt) {
|
||||
this(home, mnt, null, null, null);
|
||||
}
|
||||
|
||||
/** This storage, its HDFS's NameNode on {@code host}, at {@code address} on {@code network}. */
|
||||
public Storage withHdfs(String host, String address, String network) {
|
||||
return new Storage(home, mnt, host, address, network);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user