feat(emr): run Hive's metastore service on a docker cluster with Hive (#7636)

A cluster's Hive steps kept their metastore in an embedded Derby
database in the cluster's /mnt, so only one Hive step at a time could
use it ("Another instance of Derby may have already booted the
database"), and Spark steps, with a catalog of their own, saw a Hive
step's tables only through the Glue Data Catalog. "By default, Hive
records metastore information in a MySQL database on the primary node's
file system", and the Glue Data Catalog is the one to pick "when you
require a persistent Hive metastore or a Hive metastore shared by
different clusters".

- On a cluster whose Applications name Hive, the primary node's
  container runs Hive's metastore service on port 9083, once its HDFS
  is up: with the image's Hadoop configuration, as Hive steps run, the
  cluster's HDFS, its Derby database in the node's own volume, which
  only the service opens, and its warehouse in the HDFS. The node is
  ready once it listens, and ends if it exits, as for the HDFS daemons.
- It is on the cluster's own Docker network with the HDFS, so only the
  cluster's steps reach it. It reaches tables' S3 locations through S3A
  on Floci's S3, with a session for the cluster's EC2 instance
  profile's role, which goes with the container: at the host's address
  when Floci runs on the host, and as floci when Floci runs in a
  container, which joins the cluster's network for it, as it joins EC2
  VPC networks, and leaves it when the HDFS container goes. A start
  that fails, or a container an earlier Floci left, does not keep
  Floci there, and one Docker keeps Floci on stays known for the next
  teardown.
- It gets the cluster's core-site and hive-site after its own
  settings, as EMR's primary node does, so a hive-site warehouse folder
  holds for it as for the steps. One an earlier Floci left running
  starts again, as its session went with that Floci, and so does one
  given Floci's address before Floci could join its network.
- A Floci that crashed is still on that network when it starts again,
  and Docker lists it first, so what Floci launched then joined it and
  reached the cluster's HDFS and metastore. Floci's own network is no
  longer one it made, an EMR cluster's or a VPC's, its earlier owner
  label included, or one Docker cannot inspect, unless it is on no
  other, and its DNS server takes its address from that network.
- In a namespace the steps share, host or container:<id>, it does not
  run: Hive 3.1 has no setting for the address it listens on, so it
  would serve every interface of the namespace. Hive steps keep the
  embedded Derby database there, as they do with no network.
- Hive steps get its URI in place of the embedded Derby settings, and
  Spark steps' Hive client gets it too, so a Spark step reads a Hive
  step's tables and makes tables a Hive step reads; a hive-site or
  spark-hive-site naming the Glue Data Catalog's client factory still
  uses Floci's Glue.
- Two Hive sessions starting at once both upload Hive's exec jar to
  the same HDFS folder when it is not there, and one could launch Tez
  tasks with a jar that changed under it, so the primary node puts it
  there first, under the name Hive gives it.

EmrHiveStepsDockerIntegrationTest runs two Hive steps at once on a
cluster's metastore, and a Spark step that reads a Hive step's table
and makes one the next Hive step reads.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-06 23:02:33 -06:00
1 parent ee2cdfc4f8
commit ba9a9c8155
19 files changed
+1200 -147

No files matched your search

@@ -6,6 +6,7 @@ import io.floci.aws.config.TlsConfigSource;
import io.floci.aws.core.common.DomainNames;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.docker.ContainerDetector;
import io.floci.aws.core.common.docker.CurrentContainerNetworkResolver;
import io.quarkus.runtime.Startup;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
@@ -22,6 +23,7 @@ import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
@@ -110,6 +112,16 @@ public class EmbeddedDnsServer {
this(suffixes, List.of());
}
/**
* This container's address on the network the containers it launches join, which is how they reach this server.
* The host's own lookup takes the first of its networks by name, which after a crash can be one Floci made and
* is still on; it answers only when that network cannot be told.
*/
static String ownAddress(CurrentContainerNetworkResolver currentContainer) throws UnknownHostException {
Optional<String> address = currentContainer.resolveContainerIp();
return address.isPresent() ? address.get() : InetAddress.getLocalHost().getHostAddress();
}
/**
* The certificate generator cannot read application.yml, so DNS spoofing without AWS SANs on
* the certificate only happens when the flag and TLS are on but the flag is not visible to it.
@@ -144,7 +156,8 @@ public class EmbeddedDnsServer {
public EmbeddedDnsServer(EmulatorConfig config, ContainerDetector containerDetector, Vertx vertx,
Instance<DnsRecordSource> recordSources,
Instance<DnsForwardingRuleSource> forwardingRuleSources,
Instance<DnsClientVpcSource> clientVpcSources) {
Instance<DnsClientVpcSource> clientVpcSources,
CurrentContainerNetworkResolver currentContainer) {
this.recordSources = recordSources;
this.forwardingRuleSources = forwardingRuleSources;
this.clientVpcSources = clientVpcSources;
@@ -152,7 +165,7 @@ public class EmbeddedDnsServer {
return;
}
try {
String myIp = InetAddress.getLocalHost().getHostAddress();
String myIp = ownAddress(currentContainer);
upstreamDnsServers = composeUpstreams(readResolvConfNameservers(),
config.dns().containerFallbackServers());
@@ -1031,6 +1031,53 @@ public class ContainerLifecycleManager {
.exec();
}
/**
* Connects the running container {@code containerId} to {@code networkName}, where its other containers reach it
* as {@code alias}, unless it is on it already.
*/
public void ensureConnected(String containerId, String networkName, String alias) {
if (networksOf(containerId).containsKey(networkName)) {
return;
}
dockerClient.connectToNetworkCmd()
.withContainerId(containerId)
.withNetworkId(networkName)
.withContainerNetwork(new ContainerNetwork().withAliases(alias))
.exec();
LOG.debugv("Connected {0} to network {1} as {2}", containerId, networkName, alias);
}
/**
* Disconnects the container {@code containerId} from {@code networkName} when it is on it: true once it is not,
* false when Docker kept it there.
*/
public boolean disconnectFromNetwork(String containerId, String networkName) {
try {
if (networksOf(containerId).containsKey(networkName)) {
dockerClient.disconnectFromNetworkCmd()
.withContainerId(containerId)
.withNetworkId(networkName)
.withForce(true)
.exec();
LOG.debugv("Disconnected {0} from network {1}", containerId, networkName);
}
return true;
} catch (NotFoundException e) {
return true;
} catch (Exception e) {
LOG.warnv("Error disconnecting {0} from network {1}: {2}", containerId, networkName, e.getMessage());
return false;
}
}
// The networks a container is on, by name.
private Map<String, ContainerNetwork> networksOf(String containerId) {
InspectContainerResponse inspect = dockerClient.inspectContainerCmd(containerId).exec();
Map<String, ContainerNetwork> networks = inspect.getNetworkSettings() != null
? inspect.getNetworkSettings().getNetworks() : null;
return networks != null ? networks : Map.of();
}
/**
* Removes the network {@code networkName}: true once it is gone, false when Docker kept it, as
* {@link #removeVolume} says of a volume.
@@ -15,6 +15,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;
/**
* Resolves the Docker network used by the Floci container itself.
@@ -154,13 +155,25 @@ public class CurrentContainerNetworkResolver {
}
}
// Docker lists a container's networks by name. One Floci made and joined, an EC2 VPC's or an EMR cluster's, is not
// where its containers belong: a Floci that crashed is still on it when it starts again, and what it launches would
// join that network, reaching what only its owner should. It is taken only when Floci is on no other.
private Optional<CurrentContainerNetwork> selectNetwork(Map<String, ContainerNetwork> networks) {
return selectNetwork(networks, networkName -> !isMadeByFloci(networkName))
.or(() -> selectNetwork(networks, networkName -> true));
}
// The first usable network eligible says, a user-defined one before the others.
private Optional<CurrentContainerNetwork> selectNetwork(Map<String, ContainerNetwork> networks,
Predicate<String> eligible) {
return networks.entrySet().stream()
.filter(entry -> isUsable(entry.getValue()))
.filter(entry -> isUserDefinedNetwork(entry.getKey()))
.filter(entry -> eligible.test(entry.getKey()))
.findFirst()
.or(() -> networks.entrySet().stream()
.filter(entry -> isUsable(entry.getValue()))
.filter(entry -> eligible.test(entry.getKey()))
.findFirst())
.map(entry -> new CurrentContainerNetwork(entry.getKey(), entry.getValue().getIpAddress()));
}
@@ -173,6 +186,21 @@ public class CurrentContainerNetworkResolver {
return !"bridge".equals(networkName) && !"host".equals(networkName) && !"none".equals(networkName);
}
// Whether Floci made the network, as its owner label says, or the label an EC2 VPC's had before it. One Docker
// cannot inspect is taken as Floci's, so it is not mistaken for the user's own.
private boolean isMadeByFloci(String networkName) {
try {
Map<String, String> labels = dockerClient.inspectNetworkCmd().withNetworkId(networkName).exec().getLabels();
return labels != null && (labels.containsKey(ContainerStorageHelper.OWNER_LABEL)
|| ContainerStorageHelper.NETWORK_LABEL_ALIASES.legacyValue(labels,
ContainerStorageHelper.OWNER_LABEL) != null);
} catch (Exception e) {
LOG.warnv(e, "Could not inspect Docker network {0}, so it is not taken for Floci's own: {1}", networkName,
e.getMessage());
return true;
}
}
String currentContainerId() {
try {
return Files.readString(Path.of(HOSTNAME_FILE)).trim();
@@ -2,6 +2,7 @@ package io.floci.aws.services.emr;
import io.floci.aws.services.emrserverless.SparkJobRunner;
import java.util.Map;
import java.util.Set;
import java.util.function.BooleanSupplier;
@@ -20,14 +21,24 @@ public interface ClusterStorage {
void create(String clusterId, String accountId, String region);
/**
* 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.
* Starts {@code clusterId}'s HDFS, a NameNode and a DataNode keeping their data in a volume of their own, and,
* unless {@code hiveMetastore} is null, Hive's metastore service, 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 them: its primary node's {@code host} name, which a step's container resolves to the
* address given, on the network given, and the metastore's URI, null in a namespace the steps share, where it
* does not run. 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, BooleanSupplier stopped);
String dockerNetwork, HiveMetastore hiveMetastore, BooleanSupplier stopped);
/**
* Hive's metastore service on a cluster's primary node, which reaches S3 as the cluster's EC2 instance profile's
* {@code role} does, or as its account when that is null, with the cluster's {@code settings}, its
* {@code core-site} and {@code hive-site} properties, after its own.
*/
record HiveMetastore(String role, Map<String, String> settings) {
}
/**
* Removes {@code clusterId}'s HDFS and the volumes of its storage once it no longer needs them: true when the
@@ -12,13 +12,18 @@ import io.floci.aws.core.common.docker.ContainerBuilder;
import io.floci.aws.core.common.docker.ContainerExec;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.common.docker.ContainerLiveness;
import io.floci.aws.core.common.docker.ContainerSpec;
import io.floci.aws.core.common.docker.ContainerStorageHelper;
import io.floci.aws.core.common.docker.CurrentContainerNetworkResolver;
import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv;
import io.floci.aws.services.emrserverless.EmrServerlessSparkRunner;
import io.floci.aws.services.emrserverless.SparkJobRunner;
import io.floci.aws.services.iam.model.SessionCreds;
import io.floci.aws.services.lambda.launcher.LambdaExecutionRoleCredentials;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.net.URI;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
@@ -39,7 +44,9 @@ import java.util.function.LongSupplier;
* 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.
* step's, which fills it from the step's image. On a cluster with Hive 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.
*/
@ApplicationScoped
public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
@@ -58,7 +65,19 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
// 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.
// The metastore service's --hiveconf settings, Floci's S3 among them; set only on a cluster with Hive.
private static final String HIVE_METASTORE_VARIABLE = "FLOCI_HIVE_METASTORE";
// The cluster's core-site and hive-site, as --hiveconf settings one to a line, which the service gets after its own.
private static final String HIVE_METASTORE_SITE_VARIABLE = "FLOCI_HIVE_METASTORE_SITE";
private static final int HIVE_METASTORE_PORT = 9083;
// The folder a Hive session uploads Hive's exec jar to when it is not there, named after its SHA-256, under the
// image's hive.user.install.directory: the primary node puts it there first, as two sessions uploading it at once
// can leave one with a jar that changed under it, whose Tez tasks then fail to launch.
private static final String HIVE_JARS = "/tmp/hadoop/.hiveJars";
// The name Floci's own container has on a cluster's network, which it joins for the metastore service to reach it.
private static final String FLOCI_ALIAS = "floci";
// How long a cluster's HDFS and metastore may take to start, the 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,
@@ -71,9 +90,14 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
// 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.
// 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 image's Hadoop configuration, 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. 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.
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",
@@ -114,6 +138,26 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
+ " | grep -q \"\\\"Safemode\\\" : \\\"\\\"\"; do "
+ "[ \"$(jobs -rp | wc -l)\" = 2 ] || exit 1; sleep 0.2; done; "
+ "hdfs dfs -mkdir -p /tmp /user/hadoop || exit 1; "
+ "if [ -n \"$" + HIVE_METASTORE_VARIABLE + "\" ]; then "
+ "hdfs dfs -mkdir -p /user/hive/warehouse " + HIVE_JARS + " || exit 1; "
+ "jar=$(ls /usr/lib/hive/lib/hive-exec-[0-9]*.jar | head -1); "
+ "hdfs dfs -put -f \"$jar\" " + HIVE_JARS
+ "/$(basename \"$jar\" .jar)-$(sha256sum \"$jar\" | cut -d\" \" -f1).jar || exit 1; "
+ "[ -z \"$" + HIVE_METASTORE_SITE_VARIABLE + "\" ] || mapfile -t site <<< \"$"
+ HIVE_METASTORE_SITE_VARIABLE + "\"; "
+ "cd /tmp; LOGS_DIR=/tmp/floci-hive-logs HADOOP_CONF_DIR=/etc/hadoop/conf"
+ " hive --service metastore -p " + HIVE_METASTORE_PORT
+ " --hiveconf fs.defaultFS=hdfs://$FLOCI_HDFS_HOST:8020 $"
+ HIVE_METASTORE_VARIABLE
+ " --hiveconf \"javax.jdo.option.ConnectionURL=jdbc:derby:;"
+ "databaseName=/mnt/var/lib/hive/metastore_db;create=true\""
+ " --hiveconf datanucleus.schema.autoCreateAll=true"
+ " --hiveconf hive.metastore.schema.verification=false"
+ " --hiveconf hive.metastore.warehouse.dir=hdfs://$FLOCI_HDFS_HOST:8020/user/hive/warehouse"
+ " \"${site[@]}\" & "
+ "until (exec 3<>/dev/tcp/127.0.0.1/" + HIVE_METASTORE_PORT + ") 2>/dev/null; do "
+ "[ \"$(jobs -rp | wc -l)\" = 3 ] || exit 1; sleep 0.2; done; "
+ "fi; "
+ "touch " + HDFS_READY + "; "
+ "wait -n; rm -f " + HDFS_READY + "; kill $(jobs -rp) 2>/dev/null; exit 1'");
@@ -121,10 +165,16 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
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 metastore services this process started, by container name: the session each reaches S3 with, if any, and
// the address of Floci's it was given.
private final Map<String, MetastoreSession> sessions = 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 LaunchedContainerAwsEnv awsEnv;
private final LambdaExecutionRoleCredentials roleCredentials;
private final CurrentContainerNetworkResolver currentContainer;
private final EmulatorConfig config;
private final Duration hdfsStartTimeout;
private final LongSupplier nanoTime;
@@ -133,14 +183,21 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
@Inject
public EmrClusterStorage(ContainerLifecycleManager lifecycleManager, ContainerBuilder containerBuilder,
EmulatorConfig config) {
this(lifecycleManager, containerBuilder, config, HDFS_START_TIMEOUT, System::nanoTime);
LaunchedContainerAwsEnv awsEnv, LambdaExecutionRoleCredentials roleCredentials,
CurrentContainerNetworkResolver currentContainer, EmulatorConfig config) {
this(lifecycleManager, containerBuilder, awsEnv, roleCredentials, currentContainer, config, HDFS_START_TIMEOUT,
System::nanoTime);
}
EmrClusterStorage(ContainerLifecycleManager lifecycleManager, ContainerBuilder containerBuilder,
EmulatorConfig config, Duration hdfsStartTimeout, LongSupplier nanoTime) {
LaunchedContainerAwsEnv awsEnv, LambdaExecutionRoleCredentials roleCredentials,
CurrentContainerNetworkResolver currentContainer, EmulatorConfig config,
Duration hdfsStartTimeout, LongSupplier nanoTime) {
this.lifecycleManager = lifecycleManager;
this.containerBuilder = containerBuilder;
this.awsEnv = awsEnv;
this.roleCredentials = roleCredentials;
this.currentContainer = currentContainer;
this.config = config;
this.hdfsStartTimeout = hdfsStartTimeout;
this.nanoTime = nanoTime;
@@ -163,7 +220,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
@Override
public SparkJobRunner.Storage hdfs(String clusterId, String accountId, String region, String host, String image,
String dockerNetwork, BooleanSupplier stopped) {
String dockerNetwork, HiveMetastore hiveMetastore, BooleanSupplier stopped) {
String name = hdfsName(clusterId);
String network = network(dockerNetwork);
if (NO_NETWORK.equals(network)) {
@@ -191,10 +248,12 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
+ " runs");
}
boolean found = liveness == ContainerLiveness.RUNNING && attempt == 0
&& inStepsNamespace(name, shared ? network : name);
&& inStepsNamespace(name, shared ? network : name)
&& (shared || hiveMetastore == null || metastoreCurrent(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);
String candidate = found ? name
: start(clusterId, accountId, region, host, imageId, dockerNetwork, hiveMetastore);
if (awaitReady(clusterId, candidate, deadline, teardown, stopped)) {
containerId = candidate;
} else if (!found) {
@@ -206,10 +265,22 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
if (shared) {
return volumes(clusterId).withHdfs(host, LOOPBACK, null);
}
return volumes(clusterId).withHdfs(host, address(clusterId, containerId), name);
SparkJobRunner.Storage storage = volumes(clusterId).withHdfs(host, address(clusterId, containerId), name);
return hiveMetastore != null
? storage.withHiveMetastore("thrift://" + host + ":" + HIVE_METASTORE_PORT) : storage;
}
}
// Whether the metastore service of a primary node found running is one this process started, with a session it
// holds, which reaches Floci's S3 at the address it would be given now, Floci's container joining the network again
// if it has left. One an earlier process left has a session that process's end took away, and one started while
// Floci's container could not join the network has an address there that no join repairs: both start again, on
// the data their volume keeps.
private boolean metastoreCurrent(String name) {
MetastoreSession session = sessions.get(name);
return session != null && session.endpoint().equals(flociEndpointOn(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));
@@ -256,14 +327,16 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
}
// A cluster's HDFS container, started anew on the HDFS data its volume holds, which goes with the cluster's other
// two; 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.
// two, with its metastore service when asked; one a restart, a stop or a daemon's exit left goes first. It runs on
// a Docker network of the cluster's own, which only the cluster's steps join, as its HDFS and its metastore serve
// its files and tables to any client that reaches them: the steps of other clusters, of other accounts too, do
// not. In a namespace the steps share it listens on the loopback alone, and the metastore does not run, as Hive 3's
// has no setting for the address it listens on: it would serve every interface, the host's own for one.
private String start(String clusterId, String accountId, String region, String host, String imageId,
String dockerNetwork) {
String dockerNetwork, HiveMetastore hiveMetastore) {
String network = network(dockerNetwork);
if (!sharesNamespace(network)) {
return createContainer(clusterId, accountId, region, host, imageId, network, false);
return createContainer(clusterId, accountId, region, host, imageId, network, false, hiveMetastore);
}
// 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.
@@ -273,22 +346,23 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
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);
return createContainer(clusterId, accountId, region, host, imageId, network, true, null);
}
}
// 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 network, boolean shared, HiveMetastore hiveMetastore) {
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);
releaseSession(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)
ContainerBuilder.Builder spec = containerBuilder.newContainer(imageId)
.withName(name)
.withUser("root")
.withEntrypoint(List.of("/bin/bash", "-c", HDFS_SCRIPT))
@@ -299,13 +373,79 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
.withNamedVolume(name, "/mnt")
.withDockerNetwork(Optional.of(shared ? network : name))
.withLogRotation()
.withLabels(labels(clusterId, accountId, region, HDFS_COMPONENT))
.build();
String containerId = lifecycleManager.createAndStart(spec).containerId();
.withLabels(labels(clusterId, accountId, region, HDFS_COMPONENT));
String containerId;
try {
if (hiveMetastore != null) {
String endpoint = flociEndpointOn(name);
Optional<SessionCreds> credentials = roleCredentials.forRole(hiveMetastore.role(), accountId, name);
sessions.put(name, new MetastoreSession(accountId,
credentials.map(SessionCreds::accessKeyId).orElse(null), endpoint));
spec.withEnv(awsEnv.sdkBaselineEnv(region, Optional.empty(), endpoint, credentials, accountId))
.withEnv(HIVE_METASTORE_VARIABLE, String.join(" ",
EmrServerlessSparkRunner.hiveMetastoreSettings(region, accountId, endpoint)))
.withEnv(HIVE_METASTORE_SITE_VARIABLE, String.join("\n",
EmrServerlessSparkRunner.hiveSettings(hiveMetastore.settings())))
.withHostDockerInternalOnLinux()
.withJavaTrustStore();
}
containerId = lifecycleManager.createAndStart(spec.build()).containerId();
} catch (RuntimeException e) {
// A start that fails leaves no session, nor Floci's container on a network with no service to reach it.
releaseSession(name);
if (hiveMetastore != null) {
detachFloci(name);
}
throw e;
}
LOG.infov("Started the HDFS of EMR cluster {0} as {1}", clusterId, host);
return containerId;
}
// Where the metastore service, on the cluster's network, which Docker keeps apart from Floci's, reaches Floci's
// S3: Floci on the host at the host's address, as the steps reach it; Floci in a container of its own as
// FLOCI_ALIAS, its container joining the cluster's network, as it joins the networks of EC2 VPCs.
private String flociEndpointOn(String network) {
String endpoint = awsEnv.flociEndpoint(false);
return attachFloci(network) ? "http://" + FLOCI_ALIAS + ":" + URI.create(endpoint).getPort() : endpoint;
}
// Whether Floci's own container is on the network, joined to it unless it was; false when Floci runs on the host,
// or its container could not join, which leaves the metastore service its address on Floci's network.
private boolean attachFloci(String network) {
Optional<String> floci = currentContainer.resolveContainerId();
if (floci.isEmpty()) {
return false;
}
try {
lifecycleManager.ensureConnected(floci.get(), network, FLOCI_ALIAS);
return true;
} catch (RuntimeException e) {
LOG.warnv(e, "Could not connect Floci's container {0} to the Docker network {1}, so the Hive metastore"
+ " on it may not reach Floci's S3: {2}", floci.get(), network, e.getMessage());
return false;
}
}
// Floci's container leaves a cluster's network, which it joined for the metastore service, so the network can go,
// and Floci's container, restarted, does not find itself on it. Whether it is off it.
private boolean detachFloci(String network) {
return currentContainer.resolveContainerId()
.map(floci -> lifecycleManager.disconnectFromNetwork(floci, network))
.orElse(true);
}
// The session the metastore service of the container named so reached S3 with goes with the container.
private void releaseSession(String name) {
MetastoreSession session = sessions.remove(name);
if (session != null && session.accessKeyId() != null) {
roleCredentials.unregister(session.accountId(), session.accessKeyId());
}
}
private record MetastoreSession(String accountId, String accessKeyId, String endpoint) {
}
// 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()
@@ -416,17 +556,22 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
}
}
// 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.
// Removes an HDFS container, forgetting it only once Docker says it is gone and Floci's container has left its
// network: one Docker keeps, or keeps Floci's container on the network of, stays known, so the next reset or
// shutdown tries again. Its metastore's session goes with it. Whether both are done.
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;
}
releaseSession(name);
if (!detachFloci(name)) {
return false;
}
running.remove(name);
return true;
}
@Override
@@ -464,6 +609,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
.exec()) {
Map<String, String> labels = network.getLabels() != null ? network.getLabels() : Map.of();
if (!kept.contains(labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL))) {
detachFloci(network.getName());
lifecycleManager.removeNetwork(network.getName());
}
}
@@ -1470,13 +1470,17 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
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.
// a NameNode and a DataNode, in a container of the release's Hive image, the one with HDFS's daemons, and
// on a cluster with Hive its metastore service.
String clusterId = cluster.getId();
String hdfsHost = masterPrivateDnsName(cluster);
String hdfsImage = hdfsImage(cluster.getReleaseLabel());
ClusterStorage.HiveMetastore hiveMetastore = EmrSparkSteps.installsHive(cluster.getApplications(),
SNAPSHOT_MAPPER) ? new ClusterStorage.HiveMetastore(instanceProfileRole(cluster, accountId),
EmrSparkSteps.hiveMetastoreSettings(cluster.getConfigurations(), SNAPSHOT_MAPPER)) : null;
Function<BooleanSupplier, SparkJobRunner.Storage> hdfs = storage == null ? null
: stopped -> clusterStorage.hdfs(clusterId, accountId, region, hdfsHost, hdfsImage, dockerNetwork,
stopped);
hiveMetastore, stopped);
SparkJobRunner.Job job;
if (hive != null) {
job = new SparkJobRunner.Job(SERVICE, step.getId(), accountId, region, cluster.getReleaseLabel(),
@@ -75,7 +75,8 @@ final class EmrSparkSteps {
// files, a later one winning: core-site, tez-site, which will "Change values in Tez's tez-site.xml file", and
// hive-site, which will "Change values in Hive's hive-site.xml"; and hive-env's exports, which will "Change
// values in the Hive environment".
private static final List<String> HIVE_CLASSIFICATIONS = List.of(CORE_SITE, "tez-site", "hive-site");
private static final String HIVE_SITE = "hive-site";
private static final List<String> HIVE_CLASSIFICATIONS = List.of(CORE_SITE, "tez-site", HIVE_SITE);
private static final String HIVE_ENV = "hive-env";
// EMR's MapReduce jars are in /usr/lib/hadoop-mapreduce, as the image's own hadoop-streaming script has it,
// which the image does not have; its streaming jar is in /usr/lib/hadoop.
@@ -262,6 +263,16 @@ final class EmrSparkSteps {
return properties(configurations, objectMapper, CORE_SITE);
}
/**
* The properties of a cluster's {@code core-site}, then its {@code hive-site}, which configure its Hive metastore
* service as they do on EMR's primary node.
*/
static Map<String, String> hiveMetastoreSettings(String configurations, ObjectMapper objectMapper) {
Map<String, String> settings = new LinkedHashMap<>(properties(configurations, objectMapper, CORE_SITE));
settings.putAll(properties(configurations, objectMapper, HIVE_SITE));
return settings;
}
/** The properties of a cluster's {@code spark-log4j2}, which its steps' Spark gets in its log4j2.properties. */
static Map<String, String> sparkLog4j2(String configurations, ObjectMapper objectMapper) {
return properties(configurations, objectMapper, SPARK_LOG4J2);
@@ -238,11 +238,13 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
new SparkSetting("tez.local.mode", "true"),
new SparkSetting("tez.am.client.am.port-range", "40000-40100"));
// 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("hive.metastore.client.factory.class",
"org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClientFactory"),
// on the primary node's file system": the metastore service on its primary node (see EmrClusterStorage), in place
// of the Glue Data Catalog client the image's hive-site names, or, where that does not run, 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.
private static final SparkSetting HIVE_CLUSTER_CLIENT = new SparkSetting("hive.metastore.client.factory.class",
"org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClientFactory");
private static final List<SparkSetting> HIVE_EMBEDDED_METASTORE = List.of(
new SparkSetting("javax.jdo.option.ConnectionURL",
"jdbc:derby:;databaseName=/mnt/var/lib/hive/metastore_db;create=true"),
new SparkSetting("hive.metastore.schema.verification", "false"),
@@ -743,7 +745,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
settings.addAll(HIVE_SETTINGS);
if (job.storage() != null) {
settings.addAll(hdfsSettings(job.storage()));
settings.addAll(HIVE_CLUSTER_SETTINGS);
settings.addAll(hiveClusterSettings(job.storage()));
}
List<String> arguments = new ArrayList<>();
for (SparkSetting setting : settings) {
@@ -910,16 +912,32 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
// Floci's Hadoop settings: S3A on Floci's S3, and the Glue Data Catalog client on Floci's Glue, in the job's
// account. Given none, the client from emr-7.10.0 asks STS for it, through a client no setting points at Floci.
private static List<SparkSetting> hadoopSettings(Job job, String flociEndpoint) {
return hadoopSettings(job.region(), job.accountId(), flociEndpoint);
}
/**
* The {@code --hiveconf} settings a cluster's Hive metastore service gets, so that it reaches the S3 locations of
* tables as the cluster's steps do: Floci's S3 through S3A.
*/
public static List<String> hiveMetastoreSettings(String region, String accountId, String flociEndpoint) {
List<String> arguments = new ArrayList<>();
for (SparkSetting setting : hadoopSettings(region, accountId, flociEndpoint)) {
addHiveSetting(arguments, setting.key(), setting.value());
}
return arguments;
}
private static List<SparkSetting> hadoopSettings(String region, String accountId, String flociEndpoint) {
return List.of(
new SparkSetting("fs.s3a.endpoint", flociEndpoint),
new SparkSetting("fs.s3a.endpoint.region", job.region()),
new SparkSetting("fs.s3a.endpoint.region", region),
new SparkSetting("fs.s3a.path.style.access", "true"),
new SparkSetting("fs.s3a.committer.magic.track.commits.in.memory.enabled", "true"),
new SparkSetting("fs.s3.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem"),
new SparkSetting("fs.AbstractFileSystem.s3.impl", "org.apache.hadoop.fs.s3a.S3A"),
new SparkSetting("aws.glue.endpoint", flociEndpoint),
new SparkSetting("hive.metastore.glue.catalogid", job.accountId()),
new SparkSetting("aws.region", job.region()));
new SparkSetting("hive.metastore.glue.catalogid", accountId),
new SparkSetting("aws.region", region));
}
// A cluster's HDFS, as Hadoop settings: its NameNode, on the cluster's primary node, which hdfs:// paths without a
@@ -949,9 +967,22 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
return settings;
}
// The cluster's metastore, for its Hive steps (see HIVE_CLUSTER_CLIENT).
private static List<SparkSetting> hiveClusterSettings(Storage storage) {
List<SparkSetting> settings = new ArrayList<>(List.of(HIVE_CLUSTER_CLIENT));
if (storage.hiveMetastore() != null) {
settings.add(new SparkSetting("hive.metastore.uris", storage.hiveMetastore()));
} else {
settings.addAll(HIVE_EMBEDDED_METASTORE);
}
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.
// in HDFS only through it. On a cluster with Hive, Spark's Hive client uses the cluster's metastore too, as the
// Glue Data Catalog is the one to pick "when you require a persistent Hive metastore or a Hive metastore shared by
// different clusters"; a spark-hive-site naming its client factory still wins.
private static List<SparkSetting> sparkSettings(Job job, String flociEndpoint) {
List<SparkSetting> hadoop = new ArrayList<>(hadoopSettings(job, flociEndpoint));
List<SparkSetting> hdfs = hdfsSettings(job.storage());
@@ -959,6 +990,9 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
if (!hdfs.isEmpty()) {
hadoop.add(new SparkSetting("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem"));
}
if (job.storage() != null && job.storage().hiveMetastore() != null) {
hadoop.add(new SparkSetting("hive.metastore.uris", job.storage().hiveMetastore()));
}
List<SparkSetting> settings = new ArrayList<>();
hadoop.forEach(setting -> settings.add(new SparkSetting("spark.hadoop." + setting.key(), setting.value())));
if (job.storage() != null) {
@@ -108,12 +108,14 @@ public interface SparkJobRunner {
/**
* 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).
* {@code /home/hadoop} and {@code mnt} at {@code /mnt}; 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); and, on a cluster with Hive, the URI of the Hive
* metastore service on that node, or null.
*/
record Storage(String home, String mnt, String hdfsHost, String hdfsAddress, String hdfsNetwork) {
record Storage(String home, String mnt, String hdfsHost, String hdfsAddress, String hdfsNetwork,
String hiveMetastore) {
/**
* The component label of an EMR cluster's HDFS container, which carries its service's labels as a driver
@@ -123,12 +125,17 @@ public interface SparkJobRunner {
/** A cluster's volumes, before its HDFS runs. */
public Storage(String home, String mnt) {
this(home, mnt, null, null, null);
this(home, mnt, null, 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);
return new Storage(home, mnt, host, address, network, hiveMetastore);
}
/** This storage, its Hive metastore service at {@code uri}. */
public Storage withHiveMetastore(String uri) {
return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, uri);
}
}