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

@@ -41,11 +41,14 @@ import io.floci.aws.services.lambda.launcher.BootstrapProcess;
import io.floci.aws.services.lambda.launcher.ImageCacheService;
import io.floci.aws.services.lambda.launcher.LambdaExecutionRoleCredentials;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.testing.ParallelLocks;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.api.parallel.ResourceAccessMode;
import org.junit.jupiter.api.parallel.ResourceLock;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
@@ -102,6 +105,8 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** A cluster's storage: Docker volumes, and its HDFS in a container of its own, on its primary node. */
// It names Trino's port, localhost:8889, and opens no socket.
@ResourceLock(value = ParallelLocks.PORTS, mode = ResourceAccessMode.READ)
class EmrClusterStorageTest {
private static final String IMAGE = "public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest";
@@ -119,6 +124,10 @@ class EmrClusterStorageTest {
// A cluster with Hive, whose EC2 instance profile's role is r, with no core-site or hive-site.
private static final ClusterStorage.HiveMetastore METASTORE =
new ClusterStorage.HiveMetastore("arn:aws:iam::123456789012:role/r", Map.of());
// The same with Trino beside it, from the image of emr-7.5.0's Trino.
private static final ClusterStorage.HiveMetastore TRINO_METASTORE =
new ClusterStorage.HiveMetastore("arn:aws:iam::123456789012:role/r", Map.of(),
new ClusterStorage.Trino("trinodb/trino:446", 2048, Map.of()));
private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
private final DockerClient docker = mock(DockerClient.class);
@@ -131,6 +140,12 @@ class EmrClusterStorageTest {
private final S3Service s3 = mock(S3Service.class);
private final EmrClusterStorage storage = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv,
roleCredentials, currentContainer, config, s3, Duration.ofSeconds(120), System::nanoTime);
// A storage whose clock moves on five seconds each time it is read, so Trino's ten seconds of answering pass
// at once.
private final AtomicLong fiveSecondTicks = new AtomicLong();
private final EmrClusterStorage ticking = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv,
roleCredentials, currentContainer, config, s3, Duration.ofSeconds(120),
() -> fiveSecondTicks.addAndGet(TimeUnit.SECONDS.toNanos(5)));
private final String hdfsName = ContainerStorageHelper.dockerName(config, "emr-j-1-hdfs");
private final String historyName = ContainerStorageHelper.dockerName(config, "emr-j-1-history");
private final String coreName = ContainerStorageHelper.dockerName(config, "emr-j-1-node-1-1");
@@ -1970,6 +1985,164 @@ class EmrClusterStorageTest {
verify(roleCredentials).unregister("123456789012", "ASIAMETASTORE");
}
@Test
void trinoRunsBesideTheMetastoreOnThePrimaryNodesNetworkAndGoesBeforeIt() {
String trinoName = ContainerStorageHelper.dockerName(config, "emr-j-1-trino");
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-6", Map.of()),
new ContainerLifecycleManager.ContainerInfo("t-1", Map.of()));
TrinoStubs trino = trinoStarts(trinoName);
ContainerBuilder.Builder trinoSpec = trino.spec();
List<List<String>> asked = trino.asked();
List<String> removed = trino.removed();
ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", TRINO_METASTORE, null,
NOT_STOPPED);
verify(trinoSpec).withName(trinoName);
// On the primary node's network, as a daemon of it, with its memory, its configuration and its hive catalog.
verify(trinoSpec).withNetworkMode("container:c6c6c6");
verify(trinoSpec).withMemoryMb(2048);
verify(trinoSpec).withEnv(List.of("AWS_ACCESS_KEY_ID=ASIATRINO"));
verify(trinoSpec).withEnv(EmrTrino.CONFIG_VARIABLE, EmrTrino.CONFIG);
verify(trinoSpec).withEnv(EmrTrino.CATALOG_VARIABLE, EmrTrino.properties(EmrTrino.hiveCatalog(Map.of(),
"http://host.docker.internal:4566", "us-east-1")));
verify(trinoSpec).withEntrypoint(List.of("/bin/bash", "-c", EmrTrino.ENTRYPOINT));
verify(trinoSpec).withJavaTrustStore();
verify(trinoSpec).withLabels(argThat(labels ->
EmrTrino.COMPONENT.equals(labels.get(ContainerStorageHelper.COMPONENT_LABEL))));
// Waited for, until it has run a query for ten seconds: its first query fails, the next three answer.
List<String> query = List.of("/usr/bin/trino", "--server", "localhost:8889", "--execute", "SELECT 1");
assertEquals(List.of(query, query, query, query), asked);
ticking.remove("j-1");
// It goes before the primary node, whose network it shares, and its session with it.
assertEquals(List.of(trinoName, hdfsName), removed.subList(removed.size() - 2, removed.size()));
verify(roleCredentials).unregister("123456789012", "ASIATRINO");
}
@Test
void trinoIsReadyOnceItHasRunAQueryForTenSecondsAFailureBetweenStartingThemAgain() {
String trinoName = ContainerStorageHelper.dockerName(config, "emr-j-1-trino");
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-6", Map.of()),
new ContainerLifecycleManager.ContainerInfo("t-1", Map.of()));
trinoStarts(trinoName);
// It answers, then fails, as Trino may before its node manager has caught up, then answers on.
List<List<String>> asked = ContainerExecStubs.completeEveryExec(docker, trinoName, List.of(0L, 1L, 0L), "",
"");
ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", TRINO_METASTORE, null,
NOT_STOPPED);
// Five seconds between each: ten seconds of answers only from the third.
assertEquals(5, asked.size(), asked.toString());
}
@Test
void theClustersNextStepHasATrinoThatBecameReadyAtOnce() {
String trinoName = ContainerStorageHelper.dockerName(config, "emr-j-1-trino");
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-6", Map.of()),
new ContainerLifecycleManager.ContainerInfo("t-1", Map.of()));
TrinoStubs trino = trinoStarts(trinoName);
// Started by this process, then found running by the cluster's next step, Trino on its network.
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING, ContainerLiveness.RUNNING);
when(lifecycle.resolveContainerNetworkIp(anyString(), eq(hdfsName))).thenReturn("172.18.0.7");
runningOn(hdfsName, hdfsName);
when(docker.inspectContainerCmd(hdfsName).exec().getId()).thenReturn("c6c6c6");
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
runningOn(trinoName, "container:c6c6c6");
ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", TRINO_METASTORE, null,
NOT_STOPPED);
int asked = trino.asked().size();
ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", TRINO_METASTORE, null,
NOT_STOPPED);
// No other container, and no other wait.
verify(lifecycle, times(2)).createAndStart(any());
assertEquals(asked, trino.asked().size());
}
@Test
void aTrinoATeardownPassedByWhileDockerMadeItGoesWithTheHdfs() {
String trinoName = ContainerStorageHelper.dockerName(config, "emr-j-1-trino");
TrinoStubs trino = trinoStarts(trinoName);
// A reset looks for Trino while Docker makes its container, so it finds none to remove.
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-6", Map.of()))
.thenAnswer(starting -> {
ticking.stopManagedContainers();
trino.removed().add("made");
return new ContainerLifecycleManager.ContainerInfo("t-1", Map.of());
});
assertThrows(ClusterStorage.Stopped.class, () -> ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", TRINO_METASTORE, null, NOT_STOPPED));
// Once made, it goes, before the HDFS it shares a network with, and is not waited for.
List<String> afterMade = trino.removed().subList(trino.removed().indexOf("made") + 1, trino.removed().size());
assertEquals(List.of(trinoName, hdfsName), afterMade);
assertEquals(List.of(), trino.asked());
verify(roleCredentials).unregister("123456789012", "ASIATRINO");
}
@Test
void trinoStartsOnceTheNodesAreReadySoItsWaitLeavesThemTheirDeadline() {
String trinoName = ContainerStorageHelper.dockerName(config, "emr-j-1-trino");
trinoStarts(trinoName);
when(awsEnv.flociEndpoint()).thenReturn("http://floci:4566");
// When the nodes are looked at, and when Trino's container is made.
List<String> events = new ArrayList<>();
when(lifecycle.createAndStart(any())).thenAnswer(creating -> {
ContainerSpec created = creating.getArgument(0);
events.add("made " + created.image());
return new ContainerLifecycleManager.ContainerInfo("sha256:trino".equals(created.image()) ? "t-1" : "c-6",
Map.of());
});
for (String node : List.of(coreName, taskName)) {
when(lifecycle.probeContainer(node)).thenAnswer(looking -> {
events.add("looked at " + node);
return ContainerLiveness.RUNNING;
});
ContainerExecStubs.completeEveryExec(docker, node, 0L, "", "");
}
ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", TRINO_METASTORE,
() -> TWO_NODES, NOT_STOPPED);
assertTrue(events.contains("made sha256:trino"), events.toString());
assertTrue(events.lastIndexOf("looked at " + coreName) < events.indexOf("made sha256:trino"),
events.toString());
assertTrue(events.lastIndexOf("looked at " + taskName) < events.indexOf("made sha256:trino"),
events.toString());
}
@Test
void theTrinoAnEarlierFlociLeftGoesAtStartWhateverItsCluster() {
String trinoName = ContainerStorageHelper.dockerName(config, "emr-j-up-trino");
Container left = nodeOf("j-up", trinoName);
AtomicReference<Map<String, String>> filter = new AtomicReference<>();
ListContainersCmd list = mock(ListContainersCmd.class, RETURNS_SELF);
when(docker.listContainersCmd()).thenReturn(list);
when(list.withLabelFilter(any(Map.class))).thenAnswer(asked -> {
filter.set(asked.getArgument(0));
return list;
});
when(list.exec()).thenAnswer(reading ->
EmrTrino.COMPONENT.equals(filter.get().get(ContainerStorageHelper.COMPONENT_LABEL))
? List.of(left) : List.of());
ListNetworksCmd networks = mock(ListNetworksCmd.class, RETURNS_SELF);
when(docker.listNetworksCmd()).thenReturn(networks);
when(networks.exec()).thenReturn(List.of());
ListVolumesCmd volumes = mock(ListVolumesCmd.class, RETURNS_SELF);
when(docker.listVolumesCmd()).thenReturn(volumes);
when(volumes.exec()).thenReturn(mock(ListVolumesResponse.class));
// Its cluster is up, but its session went with the Floci that left it: the cluster's next step starts another.
storage.removeAllBut(Set.of("j-up"));
verify(lifecycle).removeIfExistsStrict(trinoName);
}
@Test
void aMetastoresSessionGoesWithItsContainerOnAResetOrAShutdownAndWhenItCannotStart() {
ClusterStorage.HiveMetastore metastore = METASTORE;
@@ -2997,6 +3170,45 @@ class EmrClusterStorageTest {
return volume;
}
// What a Trino container named trinoName meets beside a primary node that starts as c-6: its image, the query
// it runs once its coordinator schedules on itself, failing first, its session, and the removals, in order.
private TrinoStubs trinoStarts(String trinoName) {
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
when(lifecycle.probeContainer("c-6")).thenReturn(ContainerLiveness.RUNNING);
when(lifecycle.resolveContainerNetworkIp("c-6", hdfsName)).thenReturn("172.18.0.7");
ContainerExecStubs.completeEveryExec(docker, "c-6", 0L, "", "");
InspectContainerCmd primary = mock(InspectContainerCmd.class, RETURNS_DEEP_STUBS);
when(primary.exec().getId()).thenReturn("c6c6c6");
when(docker.inspectContainerCmd("c-6")).thenReturn(primary);
// Trino's image, pulled as the HDFS's is, and its container, which runs a query once its coordinator
// schedules on itself.
ContainerBuilder.Builder trinoSpec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.resolveImage("trinodb/trino:446")).thenReturn("trinodb/trino:446");
when(lifecycle.resolveImageForLaunch("trinodb/trino:446", ImagePullBehavior.PREFER_CACHED, null))
.thenReturn(new ImageCacheService.LaunchImage("sha256:trino", null));
when(containerBuilder.newContainer("sha256:trino")).thenReturn(trinoSpec);
when(trinoSpec.build()).thenReturn(new ContainerSpec("sha256:trino"));
when(lifecycle.probeContainer(trinoName)).thenReturn(ContainerLiveness.RUNNING);
List<List<String>> asked = ContainerExecStubs.completeEveryExec(docker, trinoName, List.of(1L, 0L), "\"1\"",
"");
// Its own session for the cluster's instance profile's role, as the metastore has.
Optional<SessionCreds> trinoSession = Optional.of(new SessionCreds("ASIATRINO", "s", "t"));
when(roleCredentials.forRole("arn:aws:iam::123456789012:role/r", "123456789012", hdfsName))
.thenReturn(Optional.of(new SessionCreds("ASIAMETASTORE", "s", "t")));
when(roleCredentials.forRole("arn:aws:iam::123456789012:role/r", "123456789012", trinoName))
.thenReturn(trinoSession);
when(awsEnv.flociEndpoint(false)).thenReturn("http://host.docker.internal:4566");
when(awsEnv.sdkBaselineEnv(anyString(), any(), anyString(), any(), anyString())).thenReturn(List.of());
when(awsEnv.sdkBaselineEnv("us-east-1", Optional.empty(), "http://host.docker.internal:4566", trinoSession,
"123456789012")).thenReturn(List.of("AWS_ACCESS_KEY_ID=ASIATRINO"));
List<String> removed = new ArrayList<>();
doAnswer(removing -> removed.add(removing.getArgument(0))).when(lifecycle).removeIfExistsStrict(anyString());
return new TrinoStubs(trinoSpec, asked, removed);
}
private record TrinoStubs(ContainerBuilder.Builder spec, List<List<String>> asked, List<String> removed) {
}
private static Container nodeOf(String clusterId, String name) {
Container container = mock(Container.class);
when(container.getNames()).thenReturn(new String[]{"/" + name});
@@ -179,6 +179,27 @@ class EmrReleaseImagesTest {
assertTrue(withHive.containsAll(EmrReleaseImages.TEZ_COPIES));
}
@Test
void anImageForAClusterWithFlocisTrinoHasTrinosCliFromItsImageAndANameOfItsOwn() {
List<String> copied = makesMissing("emr-7.5.0", true, false, "trinodb/trino:446");
// Hive's, then the CLI, from a container of the Trino image the coordinator runs, never started.
List<String> expected = new ArrayList<>(EmrReleaseImages.COPIES.stream().map(EmrReleaseImages.Copy::from)
.toList());
expected.add("cli:/usr/bin/trino");
assertEquals(expected, copied);
assertEquals("/usr/lib", EmrReleaseImages.TRINO_CLI.into());
assertEquals("trino/trino-cli", EmrReleaseImages.TRINO_CLI.as());
verify(docker).removeContainerCmd("cli");
ArgumentCaptor<String> tags = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<Map<String, String>> labels = mapCaptor();
images.image("emr-7.5.0", SPARK, HIVE, true, false);
verify(lifecycle, times(2)).commit(eq("target"), anyString(), tags.capture(), anyString(), labels.capture());
assertNotEquals(tags.getAllValues().get(0), tags.getAllValues().get(1));
assertNotEquals(labels.getAllValues().get(0).get(EmrReleaseImages.KIND_LABEL),
labels.getAllValues().get(1).get(EmrReleaseImages.KIND_LABEL));
}
@Test
void aReleaseOfTheAwsRuntimeForSparkGetsNoPig() throws IOException {
// "Pig and Oozie are not included."
@@ -500,6 +521,11 @@ class EmrReleaseImagesTest {
}
private List<String> makesMissing(String release, boolean withHive, boolean withPig) {
return makesMissing(release, withHive, withPig, null);
}
// What the image made copies, a path of the Trino image's container as cli:<path>, with Trino's CLI of trino.
private List<String> makesMissing(String release, boolean withHive, boolean withPig, String trino) {
when(lifecycle.getDockerClient()).thenReturn(docker);
String repository = ContainerStorageHelper.dockerName(config, "emr-release");
// The two are pulled as a container's image would be, from the image-registry-base it names.
@@ -527,6 +553,16 @@ class EmrReleaseImagesTest {
when(from.exec()).thenAnswer(read -> new ByteArrayInputStream(new byte[0]));
return from;
});
if (trino != null) {
resolves("mirror/" + trino, "sha256:trino");
container("sha256:trino", "cli");
when(docker.copyArchiveFromContainerCmd(eq("cli"), anyString())).thenAnswer(invocation -> {
copied.add("cli:" + invocation.getArgument(1));
CopyArchiveFromContainerCmd from = mock(CopyArchiveFromContainerCmd.class);
when(from.exec()).thenAnswer(read -> new ByteArrayInputStream(new byte[0]));
return from;
});
}
when(docker.copyArchiveToContainerCmd("target"))
.thenReturn(copyCommand());
when(lifecycle.commit(eq("target"), eq(repository), anyString(), eq("hadoop:hadoop"), any()))
@@ -535,7 +571,7 @@ class EmrReleaseImagesTest {
when(listImages.exec()).thenAnswer(invocation -> listed);
when(docker.listImagesCmd()).thenReturn(listImages);
assertEquals("sha256:made", images.image(release, SPARK, HIVE, withHive, withPig));
assertEquals("sha256:made", images.image(release, SPARK, HIVE, withHive, withPig, trino));
return copied;
}
@@ -69,6 +69,7 @@ class EmrServiceContainerStepsTest {
private static final String DRIVER_FAILED = "The Spark driver exited with code 1.";
private static final String INSTALL = "s3://bucket/bootstrap/install.sh";
private static final String PIG = "[{\"Name\": \"Hadoop\"}, {\"Name\": \"Pig\"}]";
private static final String TRINO = "[{\"Name\": \"Trino\"}]";
private static final String ERROR_CODE_PAGES = "https://docs.aws.amazon.com/emr/latest/ManagementGuide/";
// The id of the image a bootstrap kept, which the cluster's steps run in.
private static final String IMAGE = "sha256:" + "2".repeat(64);
@@ -1098,6 +1099,49 @@ class EmrServiceContainerStepsTest {
job.environment().get("FLOCI_PIG_PROPERTIES"));
}
@Test
void aClusterWithFlocisTrinoRunsItBesideTheMetastoreWhereItsStepsTrinoCliReachesIt() {
EmrService withTrino = fixture.withTrino();
EmrStep query = sparkStep("query", "CONTINUE");
List<String> args = List.of("trino-cli", "--execute", "SHOW CATALOGS");
query.setArgs(args);
EmrCluster requested = cluster("trino", true, query);
requested.setApplications(TRINO);
requested.setConfigurations("[{\"Classification\": \"trino-connector-hive\", \"Properties\": "
+ "{\"hive.metastore\": \"glue\"}}]");
withTrino.runJobFlow(requested, REGION);
fixture.runStepThread();
// The image has Hive, as EMR installs hive-client and hcatalog-server with Trino, and the CLI of the Trino the
// release ships, 446 for emr-7.5.0.
assertEquals(List.of(List.of("emr-7.5.0", "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest",
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "true", "false")),
fixture.releaseImages.asked);
assertEquals(List.of("trinodb/trino:446"), fixture.releaseImages.trinoImages);
assertEquals(new ClusterStorage.Trino("trinodb/trino:446", 2048, Map.of("hive.metastore", "glue")),
fixture.clusterStorage.metastores.get(0).trino());
SparkJobRunner.Job job = runner.jobs.get(0);
assertEquals(args, job.command());
String host = fixture.clusterStorage.hdfs.get(0).get(1);
assertEquals("http://" + host + ":8889", job.environment().get("FLOCI_TRINO_SERVER"));
}
@Test
void aClusterWithTrinoRunsNoneWhileFlocisTrinoIsOff() {
EmrStep query = sparkStep("query", "CONTINUE");
query.setArgs(List.of("trino-cli", "--execute", "SHOW CATALOGS"));
EmrCluster requested = cluster("trino", true, query);
requested.setApplications(TRINO);
service.runJobFlow(requested, REGION);
fixture.runStepThread();
assertEquals(List.of(), fixture.releaseImages.asked);
assertEquals(List.of(), fixture.clusterStorage.metastores);
assertFalse(runner.jobs.get(0).environment().containsKey("FLOCI_TRINO_SERVER"));
}
@Test
void aStreamingStepRunsItsCommandOnTheClustersStorage() {
EmrStep streaming = sparkStep("Streaming program", "CONTINUE");
@@ -256,14 +256,17 @@ final class EmrServiceFixture {
static final String IMAGE = "sha256:" + "3".repeat(64);
// Each image asked for: its release, then the two it is made of, then whether it has Hive, and Pig.
final List<List<String>> asked = new ArrayList<>();
// The Trino image each one asked for has the CLI of, null for none, in the same order.
final List<String> trinoImages = new ArrayList<>();
// Each image released, by id.
final List<String> released = new ArrayList<>();
RuntimeException failure;
@Override
public String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive,
boolean withPig) {
boolean withPig, String trinoImage) {
asked.add(List.of(releaseLabel, sparkImage, hiveImage, String.valueOf(withHive), String.valueOf(withPig)));
trinoImages.add(trinoImage);
if (failure != null) {
throw failure;
}
@@ -427,6 +430,20 @@ final class EmrServiceFixture {
iam);
}
/**
* A new service on the same storage and clock, as {@link #restart} builds, with Floci's Trino on at its defaults,
* its steps' threads this fixture's, and its events not delivered.
*/
EmrService withTrino() {
EmulatorConfig config = config(false);
when(config.services().emr().trino().enabled()).thenReturn(true);
when(config.services().emr().trino().image()).thenReturn("trinodb/trino:%s");
when(config.services().emr().trino().memoryMb()).thenReturn(2048);
return new EmrService(storage, config, new RegionResolver(REGION, ACCOUNT), publisher, clock,
mock(EmrService.Wakeups.class), runner, bootstrap, clusterStorage, releaseImages, this::handToThread,
iam);
}
/** A new service on the same storage and clock, as {@link #restart} builds, with this default release label. */
EmrService withDefaultReleaseLabel(String label) {
EmulatorConfig config = config(false);
@@ -232,6 +232,34 @@ class EmrSparkStepsTest {
assertFalse(EmrSparkSteps.installsPig("emr-spark-8.1.0", "[{\"Name\": \"Pig\"}]", objectMapper));
}
@Test
void aClusterInstallsTrinoWhereItsApplicationsNameItOnANumberedRelease() {
assertTrue(EmrSparkSteps.installsTrino(RELEASE, "[{\"Name\": \"Trino\"}]", objectMapper));
assertTrue(EmrSparkSteps.installsTrino(RELEASE, "[{\"Name\": \"Spark\"}, {\"Name\": \"trino\"}]",
objectMapper));
for (String applications : new String[]{HIVE_AND_SPARK, "[]", null, "[{"}) {
assertFalse(EmrSparkSteps.installsTrino(RELEASE, applications, objectMapper));
}
// The AWS runtime for Apache Spark's applications are "AmazonCloudWatchAgent, Delta, Hudi, Iceberg,
// JupyterEnterpriseGateway, Livy, and Spark".
assertFalse(EmrSparkSteps.installsTrino("emr-spark-8.1.0", "[{\"Name\": \"Trino\"}]", objectMapper));
}
@Test
void trinosHiveCatalogGetsTheClustersTrinoConnectorHiveALaterConfigurationWinning() {
String configurations = """
[{"Classification": "trino-connector-hive", "Properties": {"hive.metastore": "glue",
"hive.metastore.glue.catalogid": "111122223333"}},
{"Classification": "hive-site", "Properties": {"hive.metastore.uris": "thrift://elsewhere:9083"}},
{"Classification": "trino-connector-hive",
"Properties": {"hive.metastore.glue.catalogid": "444455556666"}}]
""";
assertEquals(Map.of("hive.metastore", "glue", "hive.metastore.glue.catalogid", "444455556666"),
EmrSparkSteps.trinoHiveConnector(configurations, objectMapper));
assertEquals(Map.of(), EmrSparkSteps.trinoHiveConnector(null, objectMapper));
}
@Test
void aPigCommandRunsOnTezWithTheClustersTezSiteThenItsPigProperties() {
String configurations = """
@@ -0,0 +1,210 @@
package io.floci.aws.services.emr;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.PullImageResultCallback;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.CloudFormationSettingsProfile;
import io.floci.aws.testing.DockerAvailability;
import io.floci.aws.testing.EmrRequests;
import io.floci.aws.testing.PartitionCleanup;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.floci.aws.testing.S3TestClients;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.glue.GlueClient;
import software.amazon.awssdk.services.glue.model.EntityNotFoundException;
import software.amazon.awssdk.services.glue.model.Table;
import software.amazon.awssdk.services.s3.S3Client;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static io.floci.aws.testing.EmrRequests.awaitStep;
import static io.floci.aws.testing.EmrRequests.emr;
import static io.floci.aws.testing.EmrRequests.terminateClusterAndAwaitCleanup;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Trino on an EMR cluster through Floci's Docker runner for real, with {@code floci.services.emr.trino.enabled} on: a
* cluster whose {@code Applications} name Trino runs its coordinator on its primary node, and a step runs EMR's
* {@code trino-cli} against it, as the Release Guide's "Connect to the primary node for the Amazon EMR cluster and run
* queries" does, over a CSV in Floci's S3. Its {@code hive} catalog is the cluster's Hive metastore, or, with
* {@code trino-connector-hive} setting {@code hive.metastore} to {@code glue}, Floci's Glue Data Catalog.
*
* <p>A nightly check: it pulls the Trino image of {@code emr-7.5.0}'s Trino, 446, about 1 GB, and the release's Spark
* and Hive images.
*/
@QuarkusTest
@TestProfile(EmrTrinoNightlyIntegrationTest.TrinoProfile.class)
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
// One instance, so that the image is pulled once for the class.
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class EmrTrinoNightlyIntegrationTest {
private static final ObjectMapper JSON = new ObjectMapper();
private static final String TRINO_IMAGE = "trinodb/trino:446";
private static final String SALES = "1,apple,3\n2,pear,5\n3,apple,7\n";
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Inject
EmrService emrService;
@Inject
DockerClient docker;
private S3Client s3;
private String bucket;
private String clusterId;
/** The Docker data planes, with Floci's Trino on. */
public static class TrinoProfile extends CloudFormationSettingsProfile {
@Override
public Map<String, String> getConfigOverrides() {
Map<String, String> overrides = new HashMap<>(super.getConfigOverrides());
overrides.put("floci.services.emr.trino.enabled", "true");
return overrides;
}
}
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
// Trino's image is there before a step's five minutes start, as the step would pull it while the cluster's image
// is made.
@BeforeAll
@Timeout(value = 10, unit = TimeUnit.MINUTES)
void pullImage() throws InterruptedException {
assertTrue(DockerAvailability.isAvailable(), "the nightly check needs a Docker daemon");
docker.pullImageCmd(TRINO_IMAGE).exec(new PullImageResultCallback()).awaitCompletion(9, TimeUnit.MINUTES);
}
@BeforeEach
void putSales() {
s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), "000000000000", Region.US_EAST_1);
cleanup.register(s3::close);
bucket = "emr-trino-" + UUID.randomUUID().toString().substring(0, 8);
s3.createBucket(request -> request.bucket(bucket));
cleanup.register(() -> S3TestClients.deleteBucket(s3, bucket));
s3.putObject(request -> request.bucket(bucket).key("data/sales/sales.csv"), RequestBody.fromString(SALES));
}
// The cluster's image made with Trino's CLI, its HDFS and metastore started, then Trino, within the step's five
// minutes, and the cluster's end.
@Test
@Timeout(value = 7, unit = TimeUnit.MINUTES)
void trinoCliQueriesTheClustersMetastoreTablesOnFlocisS3() {
String schema = bucket.replace('-', '_');
GlueClient glue = AwsTestClients.create(GlueClient.builder(), "000000000000", Region.US_EAST_1);
cleanup.register(glue::close);
startCluster("[]");
String step = trinoStep("SHOW CATALOGS; " + tables(schema));
assertEquals("COMPLETED", state(step), () -> logs(step));
String logs = logs(step);
// Its one catalog, as EMR's Trino has the catalogs the cluster configures, and its sums.
assertTrue(logs.contains("\"hive\"\n\"system\"") || logs.contains("\"system\"\n\"hive\""), logs);
assertTrue(logs.contains("\"apple\",\"10\"\n\"pear\",\"5\""), logs);
// The table Trino made, in its schema's folder of Floci's S3.
assertFalse(s3.listObjectsV2(request -> request.bucket(bucket).prefix("warehouse/totals/")).contents()
.isEmpty());
// The cluster's metastore holds them, not Floci's Glue.
assertThrows(EntityNotFoundException.class, () -> glue.getDatabase(request -> request.name(schema)));
}
@Test
@Timeout(value = 7, unit = TimeUnit.MINUTES)
void withTrinoConnectorHiveOnGlueTrinoCliQueriesFlocisGlueDataCatalog() {
String schema = bucket.replace('-', '_');
GlueClient glue = AwsTestClients.create(GlueClient.builder(), "000000000000", Region.US_EAST_1);
cleanup.register(glue::close);
cleanup.register(() -> {
for (Table table : glue.getTables(request -> request.databaseName(schema)).tableList()) {
glue.deleteTable(request -> request.databaseName(schema).name(table.name()));
}
glue.deleteDatabase(request -> request.name(schema));
});
// The Release Guide's configuration for Trino on the Glue Data Catalog.
startCluster("""
[{"Classification": "trino-connector-hive", "Properties": {"hive.metastore": "glue"}}]""");
String step = trinoStep(tables(schema));
assertEquals("COMPLETED", state(step), () -> logs(step));
assertTrue(logs(step).contains("\"apple\",\"10\"\n\"pear\",\"5\""), () -> logs(step));
assertEquals(List.of("sales", "totals"), glue.getTables(request -> request.databaseName(schema)).tableList()
.stream().map(Table::name).sorted().toList());
}
// A schema in the bucket's warehouse folder, an external table over the CSV, a table of each item's sum, then the
// sums.
private String tables(String schema) {
return "CREATE SCHEMA hive." + schema + " WITH (location = '" + s3Uri("warehouse/") + "'); "
+ "CREATE TABLE hive." + schema + ".sales (id integer, item varchar, qty integer) WITH (format = "
+ "'TEXTFILE', textfile_field_separator = ',', external_location = '" + s3Uri("data/sales/") + "'); "
+ "CREATE TABLE hive." + schema + ".totals AS SELECT item, sum(qty) AS total FROM hive." + schema
+ ".sales GROUP BY item; "
+ "SELECT item, total FROM hive." + schema + ".totals ORDER BY item";
}
private void startCluster(String configurations) {
ObjectNode request = JSON.createObjectNode().put("Name", "trino").put("ReleaseLabel", "emr-7.5.0")
.put("LogUri", s3Uri("logs/"));
try {
request.set("Applications", JSON.readTree("[{\"Name\":\"Trino\"}]"));
request.set("Configurations", JSON.readTree(configurations));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
request.putObject("Instances").put("KeepJobFlowAliveWhenNoSteps", true).putArray("InstanceGroups")
.addObject().put("Name", "primary").put("InstanceRole", "MASTER").put("InstanceType", "m5.xlarge")
.put("InstanceCount", 1);
clusterId = emr("RunJobFlow", request.toString()).then().statusCode(200).extract().jsonPath()
.getString("JobFlowId");
cleanup.register(() -> terminateClusterAndAwaitCleanup(clusterId, emrService));
}
// EMR's trino-cli, through command-runner.jar, running the statements given.
private String trinoStep(String statements) {
return EmrRequests.addStep(clusterId, "trino", "command-runner.jar", "trino-cli", "--execute", statements);
}
private String state(String stepId) {
return awaitStep(clusterId, stepId).jsonPath().getString("Step.Status.State");
}
// What a step wrote to its standard output, then its standard error.
private String logs(String stepId) {
String folder = "logs/" + clusterId + "/steps/" + stepId + "/";
return S3TestClients.gunzipped(s3, bucket, folder + "stdout.gz") + "\n"
+ S3TestClients.gunzipped(s3, bucket, folder + "stderr.gz");
}
private String s3Uri(String key) {
return "s3://" + bucket + "/" + key;
}
}
@@ -0,0 +1,143 @@
package io.floci.aws.services.emr;
import io.floci.aws.testing.ParallelLocks;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.api.parallel.ResourceAccessMode;
import org.junit.jupiter.api.parallel.ResourceLock;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
// It names Trino's port, localhost:8889, and opens no socket.
@ResourceLock(value = ParallelLocks.PORTS, mode = ResourceAccessMode.READ)
class EmrTrinoTest {
private static final String ENDPOINT = "http://floci:4566";
private static final String SERVER = "http://ip-10-0-0-1.ec2.internal:8889";
@Test
void theImageIsOfTheTrinoTheReleaseShips() {
assertEquals("trinodb/trino:446", EmrTrino.image("trinodb/trino:%s", "emr-7.5.0"));
assertEquals("trinodb/trino:479", EmrTrino.image("trinodb/trino:%s", "emr-7.14.0"));
// The AWS runtime for Apache Spark ships none, and a release Floci does not list has no version.
assertNull(EmrTrino.image("trinodb/trino:%s", "emr-spark-8.0.0"));
assertNull(EmrTrino.image("trinodb/trino:%s", "emr-9.9.9"));
// An image with no %s serves every release.
assertEquals("registry.internal/trino:446", EmrTrino.image("registry.internal/trino:446", "emr-9.9.9"));
}
@Test
void theHiveCatalogIsTheClustersMetastoreOnFlocisS3() {
Map<String, String> catalog = EmrTrino.hiveCatalog(Map.of(), ENDPOINT, "us-east-1");
assertEquals(List.of("connector.name=hive", "hive.metastore.uri=thrift://localhost:9083",
"fs.native-s3.enabled=true", "fs.hadoop.enabled=true", "s3.endpoint=" + ENDPOINT,
"s3.region=us-east-1", "s3.path-style-access=true"),
List.of(EmrTrino.properties(catalog).split("\n")));
}
@Test
void theHiveCatalogIsFlocisGlueWhenTheClassificationSaysSoItsOwnPropertiesWinning() {
Map<String, String> classification = new LinkedHashMap<>();
classification.put("hive.metastore", "glue");
classification.put("hive.metastore.glue.catalogid", "111122223333");
classification.put("s3.path-style-access", "false");
Map<String, String> catalog = EmrTrino.hiveCatalog(classification, ENDPOINT, "eu-west-1");
assertEquals(List.of("connector.name=hive", "hive.metastore=glue", "hive.metastore.glue.region=eu-west-1",
"hive.metastore.glue.endpoint-url=" + ENDPOINT, "fs.native-s3.enabled=true",
"fs.hadoop.enabled=true", "s3.endpoint=" + ENDPOINT, "s3.region=eu-west-1",
"s3.path-style-access=false", "hive.metastore.glue.catalogid=111122223333"),
List.of(EmrTrino.properties(catalog).split("\n")));
}
@Test
void theCoordinatorRunsTheQueriesTooOnEmrsPort() {
assertEquals(List.of("coordinator=true", "node-scheduler.include-coordinator=true",
"http-server.http.port=8889", "discovery.uri=http://localhost:8889"),
List.of(EmrTrino.CONFIG.split("\n")));
}
@Test
void theEntrypointWritesTheConfigurationTheHiveCatalogAloneAndANodeIdTrinoTakes(@TempDir Path etc)
throws Exception {
Files.createDirectories(etc.resolve("catalog"));
Files.writeString(etc.resolve("catalog/tpch.properties"), "connector.name=tpch\n");
Files.writeString(etc.resolve("node.properties"), "node.environment=docker\n");
// The image's /etc/trino here, and its Trino left out.
String entrypoint = EmrTrino.ENTRYPOINT.replace("/etc/trino", etc.toString())
.replace("exec /usr/lib/trino/bin/run-trino", "true");
assertTrue(EmrTrino.ENTRYPOINT.endsWith("exec /usr/lib/trino/bin/run-trino"));
ProcessBuilder builder = new ProcessBuilder("bash", "-c", entrypoint).redirectErrorStream(true);
builder.environment().put(EmrTrino.CONFIG_VARIABLE, EmrTrino.CONFIG);
builder.environment().put(EmrTrino.CATALOG_VARIABLE, "connector.name=hive");
// The primary node's host name, which the container shares.
builder.environment().put("HOSTNAME", "ip-10-0-0-1.ec2.internal");
Process process = builder.start();
String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
assertTrue(process.waitFor(30, TimeUnit.SECONDS));
assertEquals(0, process.exitValue(), output);
assertEquals(EmrTrino.CONFIG + "\n", Files.readString(etc.resolve("config.properties")));
try (Stream<Path> catalogs = Files.list(etc.resolve("catalog"))) {
assertEquals(List.of("hive.properties"), catalogs.map(path -> path.getFileName().toString()).toList());
}
assertEquals("connector.name=hive\n", Files.readString(etc.resolve("catalog/hive.properties")));
// Trino takes letters, digits, hyphens and underscores in a node's id, and the image's run-trino names none
// once node.properties does.
assertEquals("node.environment=docker\nnode.id=ip-10-0-0-1-ec2-internal\n",
Files.readString(etc.resolve("node.properties")));
}
@Test
void trinoCliReachesTheClustersCoordinatorUnlessTheStepNamesAServer(@TempDir Path folder) throws Exception {
// A java that prints its arguments, one to a line, in place of the image's Java 17.
Path java = folder.resolve("java");
Files.writeString(java, "#!/bin/sh\nprintf '%s\\n' \"$@\"\n");
Files.setPosixFilePermissions(java, PosixFilePermissions.fromString("rwxr-xr-x"));
Path command = folder.resolve("trino-cli");
assertTrue(EmrTrino.COMMAND.contains("/usr/lib/jvm/jre-17/bin/java"));
Files.writeString(command, EmrTrino.COMMAND.replace("/usr/lib/jvm/jre-17/bin/java", java.toString()));
assertEquals(List.of("-jar", EmrTrino.CLI, "--server", SERVER, "--execute", "SHOW CATALOGS"),
run(command, SERVER, "--execute", "SHOW CATALOGS"));
assertEquals(List.of("-jar", EmrTrino.CLI, "--server", "localhost:8889", "--version"),
run(command, null, "--version"));
assertEquals(List.of("-jar", EmrTrino.CLI, "--server=http://other:8080", "--version"),
run(command, SERVER, "--server=http://other:8080", "--version"));
assertEquals(List.of("-jar", EmrTrino.CLI, "--execute", "SELECT 1", "--server", "http://other:8080"),
run(command, SERVER, "--execute", "SELECT 1", "--server", "http://other:8080"));
}
// What command passes its java, run with server as its FLOCI_TRINO_SERVER, unless that is null.
private static List<String> run(Path command, String server, String... arguments)
throws IOException, InterruptedException {
List<String> line = new ArrayList<>(List.of("bash", command.toString()));
line.addAll(List.of(arguments));
ProcessBuilder builder = new ProcessBuilder(line).redirectErrorStream(true);
builder.environment().remove(EmrTrino.SERVER_VARIABLE);
if (server != null) {
builder.environment().put(EmrTrino.SERVER_VARIABLE, server);
}
Process process = builder.start();
String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
assertTrue(process.waitFor(30, TimeUnit.SECONDS));
assertEquals(0, process.exitValue(), output);
return List.of(output.strip().split("\n"));
}
}