feat(emr): run Trino on a docker cluster whose Applications name it (#9382)

A cluster whose Applications named Trino ran none, as no AWS image
carries it. With floci.services.emr.trino.enabled on, off by default, a
docker cluster that installs Trino now runs its coordinator, and its
steps run EMR's trino-cli against it.

- The coordinator, which runs the queries too, runs on the cluster's
  primary node, in a container of its own that shares the node's
  network: from the Trino project's image of the version the release's
  page in the Release Guide gives (trino.image, trinodb/trino:%s, 446
  for emr-7.5.0), with trino.memory-mb of memory (2048), on port 8889,
  EMR's.
- EMR installs hive-client and hcatalog-server with Trino, so the
  cluster's image has Hive and its primary node runs Hive's metastore
  service. Trino's hive catalog is that metastore, or Floci's Glue Data
  Catalog when trino-connector-hive sets hive.metastore to glue, the
  classification's other properties after Floci's. Trino reaches S3 and
  Glue with a session for the cluster's instance profile's role, as the
  metastore does.
- The cluster's image gets Trino's CLI from Trino's image, and a
  trino-cli that runs it on the image's Java 17 against the coordinator,
  whose address the steps get, unless a step names a server of its own.
- The cluster's first step starts Trino with the HDFS and waits for it.
  It goes before the primary node when the cluster ends, on a reset and
  on a shutdown, and one an earlier Floci left goes when the service
  starts.
- A nightly check runs trino-cli steps on a cluster with the metastore
  and on one with Glue. It joins the docker-runner group, whose budget
  grows by its 24 minutes, and the prefetch pulls its Trino image.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-24 17:17:07 -04:00
1 parent 33d873b705
commit 8dd85097f0
19 files changed
+1221 -42

No files matched your search

@@ -2456,6 +2456,9 @@ public interface EmulatorConfig {
/** Apache Pig for a {@code docker} cluster's Pig steps, which no AWS image carries; off unless enabled. */
EmrPigConfig pig();
/** Trino on a {@code docker} cluster's primary node, which no AWS image carries; off unless enabled. */
EmrTrinoConfig trino();
/**
* When true, Floci removes, in the {@code docker} runner mode, every EMR step driver and bootstrap
* container a previous run of <em>this same</em> Floci left on the daemon (matched by the
@@ -2500,6 +2503,35 @@ public interface EmulatorConfig {
String sha256();
}
interface EmrTrinoConfig {
/**
* When true, a {@code docker} cluster whose {@code Applications} name Trino runs Trino's coordinator on its
* primary node, from {@link #image()}, and its steps run {@code trino-cli}. Off by default, as the image is the
* Trino project's, not AWS's, about 1 GB to pull, and its container takes {@link #memoryMb()}.
*
* Env var: FLOCI_SERVICES_EMR_TRINO_ENABLED
*/
@WithDefault("false")
boolean enabled();
/**
* The image Trino runs from, {@code %s} the Trino version of the cluster's release as the Release Guide gives
* it, without AWS's build suffix. One with no {@code %s} serves every release.
*
* Env var: FLOCI_SERVICES_EMR_TRINO_IMAGE
*/
@WithDefault("trinodb/trino:%s")
String image();
/**
* The memory, in MiB, of the container Trino runs in, 80% of which its image gives Trino's heap.
*
* Env var: FLOCI_SERVICES_EMR_TRINO_MEMORY_MB
*/
@WithDefault("2048")
int memoryMb();
}
interface WafV2ServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -82,9 +82,10 @@ public interface ClusterStorage {
* unless it is running, and returns the cluster's storage with them: its primary node's {@code host} name, which a
* step's container resolves to the address given, on the network given, the metastore's URI, and YARN's
* ResourceManager with the address Floci has on that network, the metastore and YARN only on a network of the
* cluster's own. Its core and task nodes, {@code yarn}'s, run in containers of their own on that network, and
* {@code yarn} is read as they start, so a resize since the step was queued counts. A failure to start them is
* thrown, and {@link Stopped} once {@code stopped} says the step is past starting, or a teardown
* cluster's own, where Trino's coordinator runs too, in a container of its own on the primary node's network,
* when {@code hiveMetastore} asks for it. Its core and task nodes, {@code yarn}'s, run in containers of their own
* on that network, and {@code yarn} is read as they start, so a resize since the step was queued counts. A failure
* to start them is thrown, and {@link Stopped} once {@code stopped} says the step is past starting, or a teardown
* has stopped the HDFS.
*/
SparkJobRunner.Storage hdfs(String clusterId, String accountId, String region, String host, String image,
@@ -109,9 +110,23 @@ public interface ClusterStorage {
/**
* 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.
* {@code core-site} and {@code hive-site} properties, after its own, and {@code trino} beside it unless that is
* null, as EMR installs {@code hcatalog-server} with Trino.
*/
record HiveMetastore(String role, Map<String, String> settings) {
record HiveMetastore(String role, Map<String, String> settings, Trino trino) {
/** The metastore alone. */
HiveMetastore(String role, Map<String, String> settings) {
this(role, settings, null);
}
}
/**
* Trino's coordinator on a cluster's primary node: the {@code image} it runs from, the memory its container gets,
* and the cluster's {@code trino-connector-hive} properties, which its {@code hive} catalog gets after Floci's
* (see {@link EmrTrino#hiveCatalog}). It reaches S3 and Glue as the metastore does.
*/
record Trino(String image, int memoryMb, Map<String, String> hiveConnector) {
}
/**
@@ -108,7 +108,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
// 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;
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.
@@ -192,6 +192,13 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
// gives up.
private static final Duration HDFS_START_TIMEOUT = Duration.ofSeconds(120);
private static final Duration HDFS_POLL_INTERVAL = Duration.ofMillis(500);
// How long Trino's coordinator has to answer once its container starts: it took 18 s on a laptop, its image's
// catalogs loaded.
private static final Duration TRINO_START_TIMEOUT = Duration.ofMinutes(3);
// How long Trino keeps running a query before it counts as ready. A query that reads a catalog needs a node that
// serves it, which Trino's node manager learns from the nodes' announcements as it refreshes, every five seconds
// (DiscoveryNodeManager), and Trino runs a query with no catalog before then: twice that, from its first answer.
private static final Duration TRINO_SETTLE = Duration.ofSeconds(10);
// How long a node being decommissioned may take before it goes anyway: EMR's default for a graceful one, "3600s
// (one hour)", and a minute more for the ResourceManager's own timeout to pass first.
private static final Duration GRACEFUL_DECOMMISSION = Duration.ofHours(1);
@@ -545,6 +552,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
private final Set<String> running = ConcurrentHashMap.newKeySet();
// The core and task nodes' containers this process has started or found, by name.
private final Set<String> runningNodes = ConcurrentHashMap.newKeySet();
// The Trino containers this process has started, which a reset or a shutdown removes before the primary nodes whose
// network they share.
private final Set<String> runningTrino = ConcurrentHashMap.newKeySet();
// Those of them that have become ready, which a later step finds running and has at once.
private final Set<String> readyTrino = ConcurrentHashMap.newKeySet();
// What each cluster's last step started its nodes from, which a resize starts new ones from.
private final Map<String, NodeRequest> nodeRequests = new ConcurrentHashMap<>();
// For each cluster, the nodes being decommissioned, by container name.
@@ -846,6 +858,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
String imageId = lifecycleManager.resolveImageForLaunch(containerBuilder.resolveImage(image),
ImagePullBehavior.PREFER_CACHED, null).imageId();
boolean shared = sharesNamespace(network);
// Trino's too, about 1 GB at its first pull, where it runs: beside the metastore, on a network of the
// cluster's own.
Trino trino = hiveMetastore != null && !shared ? hiveMetastore.trino() : null;
String trinoImageId = trino == null ? null : lifecycleManager.resolveImageForLaunch(
containerBuilder.resolveImage(trino.image()), ImagePullBehavior.PREFER_CACHED, null).imageId();
long deadline = nanoTime.getAsLong() + hdfsStartTimeout.toNanos();
synchronized (starting.computeIfAbsent(clusterId, id -> new Object())) {
// Read here, so a resize before this took the lock counts, and one after it waits and finds these nodes.
@@ -891,6 +908,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
awaitNodes(nodeRequest, nodes, deadline, teardown, stopped);
nodeRequests.put(clusterId, nodeRequest);
}
// After the nodes, whose wait has the HDFS's deadline, as Trino's has its own.
if (trino != null) {
trino(clusterId, accountId, region, containerId, trinoImageId, hiveMetastore.role(), trino, teardown,
stopped);
}
SparkJobRunner.Storage storage = volumes(clusterId).withHdfs(host, address(clusterId, containerId), name);
if (hiveMetastore != null) {
storage = storage.withHiveMetastore("thrift://" + host + ":" + HIVE_METASTORE_PORT);
@@ -1442,7 +1464,9 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
private String createContainer(String clusterId, String accountId, String region, String host, String imageId,
String network, boolean shared, HiveMetastore hiveMetastore, Yarn yarn) {
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.
// One left stopped goes first, and a removal Docker refuses fails the start as it is, not as a name clash: the
// Trino on its network before it.
removeTrino(trinoName(clusterId));
lifecycleManager.removeIfExistsStrict(name);
releaseSession(name);
lifecycleManager.ensureVolume(name, labels(clusterId, accountId, region, COMPONENT));
@@ -1550,6 +1574,149 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
return containerId;
}
// Trino's coordinator beside the metastore on cluster clusterId's primary node, the container primary, in a
// container of its own that shares that node's network, as a daemon of the node does, reaching Floci's S3 and Glue
// with a session for role, as the metastore does: one there is kept when it runs on this primary node with a
// session of this process's, else another starts. Until it has become ready it is waited for, as the step that
// asks runs trino-cli at once.
private void trino(String clusterId, String accountId, String region, String primary, String imageId, String role,
Trino trino, long teardown, BooleanSupplier stopped) {
String name = trinoName(clusterId);
String network = CONTAINER_NETWORK_PREFIX
+ lifecycleManager.getDockerClient().inspectContainerCmd(primary).exec().getId();
boolean current = trinoCurrent(name, network);
if (current && readyTrino.contains(name)) {
// It became ready for an earlier step, and runs on.
return;
}
if (!current) {
removeTrino(name);
String endpoint = flociEndpointOn(hdfsName(clusterId));
Optional<SessionCreds> credentials = roleCredentials.forRole(role, accountId, name);
sessions.put(name, new MetastoreSession(accountId,
credentials.map(SessionCreds::accessKeyId).orElse(null), endpoint));
// Known before it starts, so a teardown while it starts removes it.
runningTrino.add(name);
try {
lifecycleManager.createAndStart(containerBuilder.newContainer(imageId)
.withName(name)
.withNetworkMode(network)
.withMemoryMb(trino.memoryMb())
.withEntrypoint(List.of("/bin/bash", "-c", EmrTrino.ENTRYPOINT))
.withEnv(awsEnv.sdkBaselineEnv(region, Optional.empty(), endpoint, credentials, accountId))
.withEnv(EmrTrino.CONFIG_VARIABLE, EmrTrino.CONFIG)
.withEnv(EmrTrino.CATALOG_VARIABLE,
EmrTrino.properties(EmrTrino.hiveCatalog(trino.hiveConnector(), endpoint, region)))
.withJavaTrustStore()
.withLogRotation()
.withLabels(labels(clusterId, accountId, region, EmrTrino.COMPONENT))
.build());
} catch (RuntimeException e) {
releaseSession(name);
throw e;
}
// A teardown that looked for it before Docker made it has passed it by: it goes now, with the HDFS.
stopIfStopped(clusterId, teardown, stopped);
LOG.infov("Started the Trino of EMR cluster {0}", clusterId);
}
awaitTrino(clusterId, name, teardown, stopped);
readyTrino.add(name);
}
// Whether the Trino container named so runs on network, the namespace of the primary node now running, with a
// session of this process's; one an earlier process left has none.
private boolean trinoCurrent(String name, String network) {
if (!sessions.containsKey(name) || lifecycleManager.probeContainer(name) != ContainerLiveness.RUNNING) {
return false;
}
try {
HostConfig hostConfig = lifecycleManager.getDockerClient().inspectContainerCmd(name).exec()
.getHostConfig();
return hostConfig != null && network.equals(hostConfig.getNetworkMode());
} catch (NotFoundException e) {
return false;
}
}
// Removes the Trino container named so, and its session, a removal Docker refuses thrown.
private void removeTrino(String name) {
lifecycleManager.removeIfExistsStrict(name);
releaseSession(name);
runningTrino.remove(name);
readyTrino.remove(name);
}
// Removes the Trino container named so, a removal Docker refuses logged and the container kept known, so the next
// reset or shutdown tries again. Whether it is gone.
private boolean removeTrinoKnown(String name) {
try {
removeTrino(name);
return true;
} catch (RuntimeException e) {
LOG.warnv(e, "Could not remove the Trino container {0}: {1}", name, e.getMessage());
return false;
}
}
// Waits for the Trino container named so to have run a query for TRINO_SETTLE, within TRINO_START_TIMEOUT: until
// its node manager has learnt that it serves its catalogs, a query that reads one fails "No nodes available to run
// query", one with none running already.
private void awaitTrino(String clusterId, String name, long teardown, BooleanSupplier stopped) {
long deadline = nanoTime.getAsLong() + TRINO_START_TIMEOUT.toNanos();
long answering = Long.MIN_VALUE;
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(name) == ContainerLiveness.NOT_RUNNING) {
logTrinoOutput(clusterId, name);
throw new IllegalStateException("The Trino of EMR cluster " + clusterId
+ " stopped before it was ready");
}
ContainerExec.Result query;
try {
query = ContainerExec.run(lifecycleManager.getDockerClient(), name,
EmrTrino.READY_QUERY.toArray(String[]::new), 30);
} catch (RuntimeException e) {
// It may have stopped after it was looked at, which makes Docker refuse the exec: the next look
// says so.
if (lifecycleManager.probeContainer(name) == ContainerLiveness.NOT_RUNNING) {
continue;
}
throw e;
}
long now = nanoTime.getAsLong();
if (query.exitCode() != 0) {
answering = Long.MIN_VALUE;
} else if (answering == Long.MIN_VALUE) {
answering = now;
}
if (answering != Long.MIN_VALUE && now - answering >= TRINO_SETTLE.toNanos()) {
return;
}
if (now >= deadline) {
logTrinoOutput(clusterId, name);
throw new IllegalStateException("The Trino of EMR cluster " + clusterId + " did not start within "
+ TRINO_START_TIMEOUT.toSeconds() + " seconds");
}
try {
Thread.sleep(HDFS_POLL_INTERVAL.toMillis());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Stopped waiting for the Trino of EMR cluster " + clusterId, e);
}
}
stopIfStopped(clusterId, teardown, stopped);
}
// What a Trino that did not become ready last wrote, in Floci's log, as its container goes with its cluster.
private void logTrinoOutput(String clusterId, String name) {
LOG.warnv("The Trino of EMR cluster {0} did not become ready. It last wrote:\n{1}", clusterId,
lifecycleManager.lastLogLines(name, NODE_LOG_LINES, NODE_LOG_READ));
}
private String trinoName(String clusterId) {
return ContainerStorageHelper.dockerName(config, SERVICE + "-" + clusterId + "-trino");
}
// The subnet of a cluster's own network, which exists, as Docker says it: where it is known, the cluster's nodes join
// the steps' network too, their HDFS and YARN listening on their address in that subnet alone (see BIND_SETUP), so
// the steps' network's containers, other clusters' among them, reach neither; where it is not, they stay on their
@@ -1920,6 +2087,8 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
// 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) {
// Its Trino first, which shares the HDFS container's network.
removeTrinoKnown(trinoName(clusterId));
removeKnown(hdfsName(clusterId));
throw new ClusterStorage.Stopped("Floci stopped the HDFS of EMR cluster " + clusterId);
}
@@ -1978,7 +2147,9 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
LOG.warnv(e, "Could not find the nodes of EMR cluster {0} to remove: {1}", clusterId, e.getMessage());
nodesGone = false;
}
boolean containerGone = removeKnown(hdfsName(clusterId));
// Its Trino before its primary node, whose network it shares.
boolean trinoGone = removeTrinoKnown(trinoName(clusterId));
boolean containerGone = trinoGone && removeKnown(hdfsName(clusterId));
// Its relay goes, trusted no more, and every address given on its network with it.
boolean relayGone = relays == null || relays.stop(clusterId);
identities.remove(clusterId);
@@ -1990,7 +2161,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
boolean homeGone = lifecycleManager.removeVolume(storage.home());
boolean mntGone = lifecycleManager.removeVolume(storage.mnt());
return lifecycleManager.removeVolume(hdfsName(clusterId)) && mntGone && homeGone && networkGone
&& containerGone && nodesGone && relayGone;
&& containerGone && trinoGone && nodesGone && relayGone;
}
/**
@@ -2008,6 +2179,9 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
for (String name : List.copyOf(runningNodes)) {
removeNode(name, false);
}
for (String name : List.copyOf(runningTrino)) {
removeTrinoKnown(name);
}
for (String name : List.copyOf(running)) {
// What its history interfaces show goes into its kept history first, as nothing reads its HDFS after.
if (lifecycleManager.probeContainer(name) == ContainerLiveness.RUNNING) {
@@ -2053,7 +2227,21 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
@Override
public void removeAllBut(Set<String> kept) {
// Each sweep on its own, so Docker refusing one list does not keep the others from going.
// Each sweep on its own, so Docker refusing one list does not keep the others from going. The Trino an earlier
// process left goes whatever its cluster, as its session went with that process: its cluster's next step
// starts another. It goes first, as it shares its primary node's network.
try {
for (Container container : lifecycleManager.getDockerClient().listContainersCmd().withShowAll(true)
.withLabelFilter(Map.of(ContainerStorageHelper.COMPONENT_LABEL, EmrTrino.COMPONENT,
ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)))
.exec()) {
String name = container.getNames()[0].substring(1);
runningTrino.add(name);
removeTrinoKnown(name);
}
} catch (RuntimeException e) {
LOG.warnv(e, "Could not remove the Trino an earlier Floci left: {0}", e.getMessage());
}
try {
for (Container container : lifecycleManager.getDockerClient().listContainersCmd().withShowAll(true)
.withLabelFilter(Map.of(ContainerStorageHelper.COMPONENT_LABEL, NODE_COMPONENT,
@@ -49,7 +49,9 @@ import java.util.concurrent.ConcurrentHashMap;
* release's HDFS and YARN do not run on its newer Hadoop, so its image gets the whole of that release's Hadoop, in a
* folder apart, which only its primary node's daemons run from. For a cluster with Pig, which no AWS image carries,
* the image gets Tez, as Pig's scripts run on it, and Apache Pig, downloaded as it is made ({@link PigDistribution}),
* whose checksum its name holds.
* whose checksum its name holds. For a cluster with Floci's Trino, it gets Trino's CLI from the Trino image the
* cluster's coordinator runs, never started either, and EMR's {@code trino-cli} command ({@link EmrTrino#COMMAND}),
* and its name holds that image's id.
*/
@ApplicationScoped
public class EmrReleaseImages implements ReleaseImages {
@@ -94,6 +96,9 @@ public class EmrReleaseImages implements ReleaseImages {
new Copy("/usr/lib/tez", "/usr/lib"),
new Copy("/etc/tez", "/etc"),
new Copy(GOODIES, EMR_SHARE, HIVE_GOODIES));
// What a cluster with Floci's Trino adds, from Trino's image: Trino's CLI, for its trino-cli (EmrTrino.COMMAND).
static final Copy TRINO_CLI = new Copy(EmrTrino.IMAGE_CLI, "/usr/lib",
EmrTrino.CLI.substring("/usr/lib/".length()));
private static final String HADOOP_APART = "/opt";
// What it adds for a release of the AWS runtime for Apache Spark: another release's Hadoop, whole and kept apart.
static final List<Copy> HADOOP_APART_COPIES = List.of(
@@ -140,27 +145,33 @@ public class EmrReleaseImages implements ReleaseImages {
*/
@Override
public String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive,
boolean withPig) {
boolean withPig, String trinoImage) {
List<Copy> copies = copies(releaseLabel, withHive, withPig);
PigDistribution pig = withPig && hadoopFolder(releaseLabel) == null ? pigDistribution : null;
// What is copied, and the Pig written after it, by its checksum.
String content = copies + (pig != null ? "\n" + pig.identity() : "");
String trino = trinoImage != null ? containerBuilder.resolveImage(trinoImage) : null;
// What is copied, the Pig written after it, by its checksum, and Trino's CLI with its command.
String content = copies + (pig != null ? "\n" + pig.identity() : "")
+ (trino != null ? "\n" + TRINO_CLI + "\n" + EmrTrino.COMMAND : "");
String spark = containerBuilder.resolveImage(sparkImage);
String hive = containerBuilder.resolveImage(hiveImage);
String repository = ContainerStorageHelper.dockerName(config, COMPONENT);
String kind = Digests.sha256Hex(releaseLabel + "\n" + spark + "\n" + hive + "\n" + content).substring(0, 12);
String kind = Digests.sha256Hex(releaseLabel + "\n" + spark + "\n" + hive + "\n" + content
+ (trino != null ? "\n" + trino : "")).substring(0, 12);
synchronized (making.computeIfAbsent(repository + ":" + kind, name -> new Object())) {
String sparkId = imageCacheService.resolveForLaunch(spark, ImagePullBehavior.PREFER_CACHED, null)
.imageId();
String hiveId = imageCacheService.resolveForLaunch(hive, ImagePullBehavior.PREFER_CACHED, null).imageId();
String tag = releaseLabel + "-"
+ Digests.sha256Hex(sparkId + "\n" + hiveId + "\n" + content).substring(0, 12);
String trinoId = trino != null
? imageCacheService.resolveForLaunch(trino, ImagePullBehavior.PREFER_CACHED, null).imageId() : null;
String tag = releaseLabel + "-" + Digests.sha256Hex(sparkId + "\n" + hiveId + "\n" + content
+ (trinoId != null ? "\n" + trinoId : "")).substring(0, 12);
DockerClient docker = lifecycleManager.getDockerClient();
try {
return hold(docker.inspectImageCmd(repository + ":" + tag).exec().getId());
} catch (NotFoundException e) {
LOG.infov("Making {0}:{1} for EMR clusters {2}, from {3} and {4}", repository, tag,
(withHive ? "with Hive" : "without Hive") + (pig != null ? ", with Pig" : ""), spark, hive);
(withHive ? "with Hive" : "without Hive") + (pig != null ? ", with Pig" : "")
+ (trino != null ? ", with Trino's CLI from " + trino : ""), spark, hive);
}
String user = docker.inspectImageCmd(sparkId).exec().getConfig().getUser();
Map<String, String> labels = new LinkedHashMap<>();
@@ -192,6 +203,15 @@ public class EmrReleaseImages implements ReleaseImages {
RetryingTarCopier.copyBytes(docker, target, PigDistribution.COMMAND_FOLDER, PigDistribution.NAME,
PigDistribution.COMMAND.getBytes(StandardCharsets.UTF_8), 0755);
}
if (trinoId != null) {
String cli = docker.createContainerCmd(trinoId).withLabels(labels).exec().getId();
containers.add(cli);
RetryingTarCopier.copyStreamed(docker, target, TRINO_CLI.into(), TRINO_CLI.from(),
out -> copy(docker.copyArchiveFromContainerCmd(cli, TRINO_CLI.from()).exec(), out,
TRINO_CLI));
RetryingTarCopier.copyBytes(docker, target, EmrTrino.COMMAND_FOLDER, EmrTrino.COMMAND_NAME,
EmrTrino.COMMAND.getBytes(StandardCharsets.UTF_8), 0755);
}
made = lifecycleManager.commit(target, repository, tag,
user == null || user.isBlank() ? "root" : user, labels);
} finally {
@@ -201,6 +201,11 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
private final String dockerNetwork;
// Whether a cluster whose Applications name Pig gets Apache Pig in its image (floci.services.emr.pig.enabled).
private final boolean pigEnabled;
// Whether a cluster whose Applications name Trino runs it (floci.services.emr.trino.enabled), from which image, the
// release's Trino version for %s, and with how much memory.
private final boolean trinoEnabled;
private final String trinoImageTemplate;
private final int trinoMemoryMb;
// What the NodeManager of a cluster that runs YARN offers its containers.
private final ClusterStorage.Yarn nodeManager;
private final int maxWorkerNodes;
@@ -383,6 +388,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
this.hiveImageTemplate = config.services().emr().hiveImageTemplate().orElse(null);
this.dockerNetwork = config.services().emr().dockerNetwork().orElse(null);
this.pigEnabled = config.services().emr().pig().enabled();
this.trinoEnabled = config.services().emr().trino().enabled();
this.trinoImageTemplate = trinoEnabled ? config.services().emr().trino().image() : null;
this.trinoMemoryMb = trinoEnabled ? config.services().emr().trino().memoryMb() : 0;
this.nodeManager = new ClusterStorage.Yarn(config.services().emr().yarnNodeMemoryMb(),
config.services().emr().yarnNodeVcores());
this.maxWorkerNodes = config.services().emr().yarnMaxWorkerNodes();
@@ -3097,10 +3105,12 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
String hdfsHost = masterPrivateDnsName(cluster);
String hdfsImage = hdfsImage(cluster.getReleaseLabel());
Supplier<ClusterStorage.Yarn> nodeYarn = runsYarn(cluster) ? currentYarn(cluster, accountId, region) : null;
ClusterStorage.HiveMetastore hiveMetastore = EmrSparkSteps.installsHive(cluster.getReleaseLabel(),
cluster.getApplications(), SNAPSHOT_MAPPER)
String trinoImage = trinoImage(cluster);
ClusterStorage.Trino trino = trinoImage == null ? null : new ClusterStorage.Trino(trinoImage, trinoMemoryMb,
EmrSparkSteps.trinoHiveConnector(cluster.getConfigurations(), SNAPSHOT_MAPPER));
ClusterStorage.HiveMetastore hiveMetastore = withHiveImage(cluster)
? new ClusterStorage.HiveMetastore(instanceProfileRole(cluster, accountId),
EmrSparkSteps.hiveMetastoreSettings(cluster.getConfigurations(), SNAPSHOT_MAPPER))
EmrSparkSteps.hiveMetastoreSettings(cluster.getConfigurations(), SNAPSHOT_MAPPER), trino)
: null;
BiFunction<String, BooleanSupplier, SparkJobRunner.Storage> hdfs = volumes == null ? null
: (stepImage, stopped) -> clusterStorage.hdfs(clusterId, accountId, region, hdfsHost,
@@ -3154,7 +3164,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
EmrSparkSteps.sparkDefaults(cluster.getConfigurations(), SNAPSHOT_MAPPER),
application != null ? application : List.of(), command, Duration.ZERO,
EmrSparkSteps.logFolder(cluster, step), null,
stepEnvironment(step, cluster, command != null && pig), List.of(),
stepEnvironment(step, cluster, command != null && pig,
trinoImage(cluster) != null ? EmrTrino.server(masterPrivateDnsName(cluster)) : null),
List.of(),
storage, EmrSparkSteps.coreSite(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.sparkLog4j2(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.mapredSite(cluster.getConfigurations(), SNAPSHOT_MAPPER),
@@ -3358,8 +3370,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
if (releaseImages == null) {
return null;
}
boolean withHive = EmrSparkSteps.installsHive(cluster.getReleaseLabel(), cluster.getApplications(),
SNAPSHOT_MAPPER);
boolean withHive = withHiveImage(cluster);
boolean withPig = withPig(cluster);
if (!withHive && !withPig && !runsYarn(cluster)) {
return null;
@@ -3367,7 +3378,25 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
String release = cluster.getReleaseLabel();
String spark = EmrServerlessSparkRunner.image(imageTemplate, release);
String hive = hdfsImage(release);
return () -> releaseImages.image(release, spark, hive, withHive, withPig);
String trino = trinoImage(cluster);
return () -> releaseImages.image(release, spark, hive, withHive, withPig, trino);
}
// Whether a cluster's image has Hive, and its primary node Hive's metastore service: it installs Hive or HCatalog,
// or runs Floci's Trino, with which EMR installs hive-client and hcatalog-server.
private boolean withHiveImage(EmrCluster cluster) {
return EmrSparkSteps.installsHive(cluster.getReleaseLabel(), cluster.getApplications(), SNAPSHOT_MAPPER)
|| trinoImage(cluster) != null;
}
// The image a cluster's Trino runs from: it installs Trino, floci.services.emr.trino.enabled runs it, and its
// release's Trino version is known (EmrTrino.image); null otherwise.
private String trinoImage(EmrCluster cluster) {
if (!trinoEnabled || !EmrSparkSteps.installsTrino(cluster.getReleaseLabel(), cluster.getApplications(),
SNAPSHOT_MAPPER)) {
return null;
}
return EmrTrino.image(trinoImageTemplate, cluster.getReleaseLabel());
}
// Whether a cluster's image has Floci's Pig: it installs Pig, and floci.services.emr.pig.enabled adds it.
@@ -3377,12 +3406,17 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
}
// The variables a step that is not a Hive step runs with: its cluster's spark-env exports and its own Properties
// (see EmrSparkSteps.environment), and for a command on a cluster with Floci's Pig, its Pig configuration.
private static Map<String, String> stepEnvironment(EmrStep step, EmrCluster cluster, boolean pig) {
// (see EmrSparkSteps.environment), for a command on a cluster with Floci's Pig, its Pig configuration, and on one
// with Floci's Trino, where its trino-cli reaches the coordinator, unless trinoServer is null.
private static Map<String, String> stepEnvironment(EmrStep step, EmrCluster cluster, boolean pig,
String trinoServer) {
Map<String, String> variables = EmrSparkSteps.environment(step, cluster.getConfigurations(), SNAPSHOT_MAPPER);
if (pig) {
variables.putAll(EmrSparkSteps.pigEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER));
}
if (trinoServer != null) {
variables.put(EmrTrino.SERVER_VARIABLE, trinoServer);
}
return variables;
}
@@ -3393,14 +3427,13 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
*/
// The YARN timeline server runs on a cluster with Hadoop, and the Tez UI on one with Tez too, as their persistent
// interfaces are there (EmrAppUiService), but for a release of the AWS runtime for Apache Spark; the Tez UI only
// where the cluster's image has Tez, which one with Hive or Floci's Pig has (releaseImage).
// where the cluster's image has Tez, which one with Hive, Floci's Trino or Floci's Pig has (releaseImage).
private ClusterStorage.Yarn yarnOf(EmrCluster cluster) {
List<ClusterStorage.Node> nodes = workerNodes(cluster);
boolean timeline = EmrSparkSteps.names(cluster.getApplications(), SNAPSHOT_MAPPER, "Hadoop")
&& !(cluster.getReleaseLabel() != null
&& EmrServerlessSparkRunner.sparkRuntime(cluster.getReleaseLabel()));
boolean tezImage = EmrSparkSteps.installsHive(cluster.getReleaseLabel(), cluster.getApplications(),
SNAPSHOT_MAPPER) || withPig(cluster);
boolean tezImage = withHiveImage(cluster) || withPig(cluster);
long coreNodes = nodes.stream().filter(ClusterStorage.Node::core).count();
return nodeManager.withHadoopFolder(EmrReleaseImages.hadoopFolder(cluster.getReleaseLabel()))
.onNodes(nodes, (int) Math.max(1, Math.min(replication(cluster), coreNodes)),
@@ -270,8 +270,21 @@ final class EmrSparkSteps {
return installs(releaseLabel, applications, objectMapper, PIG);
}
/**
* Whether a cluster installs Trino: its {@code Applications} name it, unless its release is of the AWS runtime for
* Apache Spark, whose applications do not include it.
*/
static boolean installsTrino(String releaseLabel, String applications, ObjectMapper objectMapper) {
return installs(releaseLabel, applications, objectMapper, EmrTrino.APPLICATION);
}
/** The properties of a cluster's {@code trino-connector-hive}, which its Trino's {@code hive} catalog gets. */
static Map<String, String> trinoHiveConnector(String configurations, ObjectMapper objectMapper) {
return properties(configurations, objectMapper, EmrTrino.HIVE_CONNECTOR);
}
// Whether a cluster's Applications name any of names, in any case, unless its release is of the AWS runtime for
// Apache Spark, which installs neither Hive, HCatalog nor Pig.
// Apache Spark, which installs none of Hive, HCatalog, Pig and Trino.
private static boolean installs(String releaseLabel, String applications, ObjectMapper objectMapper,
String... names) {
return (releaseLabel == null || !EmrServerlessSparkRunner.sparkRuntime(releaseLabel))
@@ -0,0 +1,136 @@
package io.floci.aws.services.emr;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Trino on the primary node of a {@code docker} cluster whose {@code Applications} name it, with
* {@code floci.services.emr.trino.enabled} on: no AWS image carries Trino, so its coordinator, which runs the queries
* too, as a cluster of one node's does, runs from the Trino project's image of the version the release's page in the
* Release Guide gives, in a container of its own that shares the primary node's network, as a daemon of that node.
* "By default, Amazon EMR configures the Presto web interface on the Presto coordinator to use port 8889 (for PrestoDB
* and Trino)", where it listens. EMR installs {@code hcatalog-server} with Trino, so its {@code hive} catalog is the
* cluster's Hive metastore, unless the cluster's {@code trino-connector-hive} classification sets
* {@code hive.metastore} to {@code glue}, as the Release Guide's "Launch an Amazon EMR cluster with Trino" does. Its
* steps run {@code trino-cli}, EMR's command for Trino's CLI, which this class writes for the image they run in.
*/
final class EmrTrino {
/** The application's name, as the Release Guide's list of applications spells it. */
static final String APPLICATION = "Trino";
/** The port Trino listens on, on the primary node. */
static final int PORT = 8889;
/** The classification whose properties go into the {@code hive} catalog. */
static final String HIVE_CONNECTOR = "trino-connector-hive";
/** The component label of a cluster's Trino container, which goes with its primary node's. */
static final String COMPONENT = "emr-trino";
/** The variable a step's {@code trino-cli} reads the coordinator's address from. */
static final String SERVER_VARIABLE = "FLOCI_TRINO_SERVER";
/** Trino's CLI in its image, an executable jar, which the cluster's image takes. */
static final String IMAGE_CLI = "/usr/bin/trino";
/** Where the cluster's image keeps that jar. */
static final String CLI = "/usr/lib/trino/trino-cli";
/** The folder of EMR's {@code trino-cli} command, and its name. */
static final String COMMAND_FOLDER = "/usr/bin";
static final String COMMAND_NAME = "trino-cli";
/**
* EMR's {@code trino-cli}: the CLI on the image's Java 17, which a release whose default is Java 8 has besides, to
* the cluster's coordinator, unless the step names a server of its own.
*/
static final String COMMAND = """
#!/bin/bash
java=/usr/lib/jvm/jre-17/bin/java
[ -x "$java" ] || java=java
for argument in "$@"; do
case "$argument" in
--server|--server=*) exec "$java" -jar %1$s "$@" ;;
esac
done
exec "$java" -jar %1$s --server "${%2$s:-localhost:%3$d}" "$@"
""".formatted(CLI, SERVER_VARIABLE, PORT);
/** What tells the Trino container is ready: a query, run with the CLI of its image. */
static final List<String> READY_QUERY = List.of(IMAGE_CLI, "--server", "localhost:" + PORT, "--execute",
"SELECT 1");
/** The variables the Trino container's entrypoint writes its configuration from. */
static final String CONFIG_VARIABLE = "FLOCI_TRINO_CONFIG";
static final String CATALOG_VARIABLE = "FLOCI_TRINO_CATALOG_HIVE";
/**
* The Trino container's entrypoint: its configuration, and its {@code hive} catalog alone, as EMR's Trino has the
* catalogs the cluster configures, then Trino, as its image starts it. Its image names the node after its host,
* which is the primary node's, whose dots Trino refuses in a node's id, so the node is named with hyphens instead.
*/
static final String ENTRYPOINT = "printf '%s\\n' \"$" + CONFIG_VARIABLE + "\" > /etc/trino/config.properties"
+ " && rm -f /etc/trino/catalog/*.properties"
+ " && printf '%s\\n' \"$" + CATALOG_VARIABLE + "\" > /etc/trino/catalog/hive.properties"
+ " && printf 'node.id=%s\\n' \"${HOSTNAME//./-}\" >> /etc/trino/node.properties"
+ " && exec /usr/lib/trino/bin/run-trino";
/** A coordinator that runs the queries too, on {@link #PORT}. */
static final String CONFIG = """
coordinator=true
node-scheduler.include-coordinator=true
http-server.http.port=%1$d
discovery.uri=http://localhost:%1$d""".formatted(PORT);
private static final String GLUE = "glue";
private EmrTrino() {
}
/**
* The image Trino runs from for a release: {@code template} with the release's Trino version for {@code %s}, as
* its page in the Release Guide gives it without AWS's build suffix, or {@code template} itself when it has no
* {@code %s}. Null for a release whose version Floci does not know, which then runs no Trino.
*/
static String image(String template, String releaseLabel) {
if (template == null || template.isBlank()) {
return null;
}
if (!template.contains("%s")) {
return template;
}
return EmrReleaseCatalog.release(releaseLabel)
.flatMap(release -> release.applications().stream()
.filter(application -> APPLICATION.equals(application.name())).findFirst())
.map(application -> template.formatted(application.version()))
.orElse(null);
}
/** The address a step's {@code trino-cli} reaches the coordinator at, on the primary node named {@code host}. */
static String server(String host) {
return "http://" + host + ":" + PORT;
}
/**
* The {@code hive} catalog: the cluster's metastore, which runs beside Trino on the primary node, or, with
* {@code hive.metastore} set to {@code glue}, Floci's Glue; Floci's S3 at {@code endpoint} in {@code region}, by
* path, the HDFS of the cluster's warehouse through Hadoop's file system; and the cluster's
* {@code trino-connector-hive} properties after these, each in its place. Credentials come from the container's
* environment, as neither file system has a setting for a session's token.
*/
static Map<String, String> hiveCatalog(Map<String, String> classification, String endpoint, String region) {
Map<String, String> catalog = new LinkedHashMap<>();
catalog.put("connector.name", "hive");
if (GLUE.equalsIgnoreCase(classification.get("hive.metastore"))) {
catalog.put("hive.metastore", GLUE);
catalog.put("hive.metastore.glue.region", region);
catalog.put("hive.metastore.glue.endpoint-url", endpoint);
} else {
catalog.put("hive.metastore.uri", "thrift://localhost:" + EmrClusterStorage.HIVE_METASTORE_PORT);
}
catalog.put("fs.native-s3.enabled", "true");
catalog.put("fs.hadoop.enabled", "true");
catalog.put("s3.endpoint", endpoint);
catalog.put("s3.region", region);
catalog.put("s3.path-style-access", "true");
catalog.putAll(classification);
return catalog;
}
/** {@code properties} as the lines of a Java properties file, in their order. */
static String properties(Map<String, String> properties) {
return properties.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue())
.collect(Collectors.joining("\n"));
}
}
@@ -14,7 +14,17 @@ public interface ReleaseImages {
* Hadoop's services alone, and with Pig or without, made first when the Docker daemon does not have it, which may
* take as long as pulling the two, and downloading Pig; a failure is thrown.
*/
String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive, boolean withPig);
default String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive,
boolean withPig) {
return image(releaseLabel, sparkImage, hiveImage, withHive, withPig, null);
}
/**
* {@link #image(String, String, String, boolean, boolean)}, with EMR's {@code trino-cli} for the Trino of
* {@code trinoImage}, unless that is null, which pulling that image may take long too.
*/
String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive, boolean withPig,
String trinoImage);
/**
* The step or the bootstrap that {@link #image} gave {@code imageId} to has ended, so a newer image of its kind may