diff --git a/.github/ci/select-nightly-checks.sh b/.github/ci/select-nightly-checks.sh index da5c53d22e..081dcfa19d 100755 --- a/.github/ci/select-nightly-checks.sh +++ b/.github/ci/select-nightly-checks.sh @@ -111,7 +111,7 @@ grep -vE "$RUNNER|$DOCKER_E2E" "$work/selected.txt" > "$work/standard.txt" || tr # Timeouts in minutes: each group's checks run one after another, plus about twenty minutes for compilation, the image # and the prefetch (see nightly-checks.yml). docker-e2e's tests took about 23 minutes in the shards on 2026-11-23. matrix='[]' -for entry in standard:359 docker-runner:228 docker-e2e:60; do +for entry in standard:359 docker-runner:235 docker-e2e:60; do group="${entry%%:*}" timeout="${entry##*:}" count=$(wc -l < "$work/$group.txt" | tr -d ' ') diff --git a/.github/workflows/nightly-checks.yml b/.github/workflows/nightly-checks.yml index 710fabb9e5..d0732c73c8 100644 --- a/.github/workflows/nightly-checks.yml +++ b/.github/workflows/nightly-checks.yml @@ -78,8 +78,8 @@ jobs: # EmrClusterShrinkNightlyIntegrationTest's sixteen-minute method and two-minute setup, and # EmrContainersSparkNightlyIntegrationTest's three six-minute methods, eleven-minute method, two-minute setup before # each and 21-minute image pull, EmrContainersGatewayNightlyIntegrationTest's twenty-four-minute, seven-minute and - # eighteen-minute methods and 21-minute image pull, and EmrTrinoNightlyIntegrationTest's four seven-minute - # methods and ten-minute image pull, 208 minutes. docker-e2e holds the *DockerNightlyIntegrationTest + # eighteen-minute methods and 21-minute image pull, and EmrTrinoNightlyIntegrationTest's five seven-minute + # methods and ten-minute image pull, 215 minutes. docker-e2e holds the *DockerNightlyIntegrationTest # classes, about 23 minutes of tests on 2026-11-23 when they still ran in the shards. A check added, or a bound # raised, raises its group's timeout with it, so a slow check fails with its own message. strategy: diff --git a/docs/services/emr.md b/docs/services/emr.md index 676699f6d0..1735f1fa84 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -862,24 +862,40 @@ holding the driver and its executors, or a command or a script. The cluster itse project's Trino takes neither EMR's `exchange.use-local-hdfs` nor an `hdfs://` directory in the `filesystem` exchange manager EMR names, so Floci leaves the first out and gives HDFS directories Trino's own `hdfs` exchange manager, its `hdfs.config.resources` a `core-site.xml` that names the cluster's NameNode, as EMR's "uses the paths to - core-site.xml, hdfs-site.xml files". Trino reaches S3 and Glue as the cluster's EC2 instance profile's role, with a + core-site.xml, hdfs-site.xml files". `trino-password-authenticator`, which changes "Trino's + password-authenticator.properties file", makes Trino's password authenticator, which a `trino-config` + `http-server.authentication.type` of `PASSWORD` turns on, as the Release Guide's "Using LDAP authentication for Presto + on Amazon EMR" has it for Trino. The files its `file.password-file`, `ldap.ssl.keystore.path` and + `ldap.ssl.truststore.path` (or that one's older name, `ldap.ssl-trust-certificate`) name are copied into Trino's + container, readable by its `trino` user, from the image the cluster's bootstrap actions left, as EMR's Trino finds + what they wrote on the primary node it runs on; one that image does not hold stays as Trino's own image has it. Trino + refuses to start with authentication on and no shared secret for its internal communication, so Floci gives it a new + one each time it starts, unless `trino-config` names one, as EMR "automatically configures a shared secret key for + secure internal communication between cluster nodes ... and you can override the configuration with your own secret + key". Trino takes a password only over HTTPS, and answers a request over plain HTTP with a `403`, with a password or + without (measured on Trino 446), so a client sends one through Floci with its TLS on (see below), and a step's + `trino-cli`, which reaches Trino over plain HTTP, gets that `403` (see **Known limitations**). Trino reaches S3 and + Glue as the cluster's EC2 instance profile's role, with a session of its own, as the metastore does. A step runs `trino-cli`, as the Release Guide's "Start the Trino CLI by running trino-cli" does on the primary node, through `command-runner.jar`: the CLI of the same Trino, which Floci copies into the cluster's image from Trino's image as it makes it, on the image's Java 17, connects to the coordinator unless the step names a `--server` of its own. As the cluster becomes ready, its bootstrap done, Floci starts its primary node, with its HDFS and Trino, in the background, steps or none, as an application UI link does, the cluster - `WAITING` or `RUNNING` meanwhile; Trino is ready once it has answered a query for ten seconds, within three minutes, - as Trino runs a query that reads a catalog once it has learnt that its node serves the catalog. A step that comes + `WAITING` or `RUNNING` meanwhile; Trino is ready once its image's health check, which asks Trino's `/v1/info` + whether it is still starting and takes no credentials, has passed for ten seconds, within three minutes, as Trino + runs a query that reads a catalog once it has learnt that its node serves the catalog. A step that comes first starts them itself and waits for Trino, a Trino that does not answer failing the step; the cluster's next steps have it at once. Clients outside the cluster reach it through Floci, on a host of the cluster's own, `http://.emr-trino.:`, as EMR's reach Trino's port on the primary node: Trino's CLI with `--server=http://j-2AXXXXXXGAPLF.emr-trino.localhost:4566`, or `jdbc:trino://j-2AXXXXXXGAPLF.emr-trino.localhost:4566/hive`. Floci's host must resolve its subdomains, as for application UIs: `localhost` and `localhost.floci.io` do, and Floci's TLS certificate names `*.emr-trino.localhost` - and `*.emr-trino.localhost.floci.io`. The host takes no credentials, as Floci's Trino has no authentication, so - whoever reaches Floci's port reaches the cluster's Trino. Trino names a query's next pages by the host it was asked - on, and by the scheme the client used, which Floci passes on as `X-Forwarded-Proto` (Floci sets - `http-server.process-forwarded` in `config.properties`). Until Trino answers, the host answers with a `503`, which + and `*.emr-trino.localhost.floci.io`. The host asks for no credentials of its own: the cluster's Trino asks for + those its `trino-config` and `trino-password-authenticator` configure, and where they configure none, whoever + reaches Floci's port reaches the cluster's Trino. Trino names a query's next pages by the host it was asked on, and + by the scheme the client used, which Floci passes on as `X-Forwarded-Proto` (Floci sets + `http-server.process-forwarded` in `config.properties`), and takes a password only where that scheme is `https`: + `--server=https://j-2AXXXXXXGAPLF.emr-trino.localhost.floci.io:4566 --user alice --password` with Floci's TLS on. Until Trino answers, the host answers with a `503`, which Trino's clients ask again on, and starts the primary node where it is not running, as after a restart; once the cluster is ending or has ended, a `404`. Trino's port is published on the primary node's container, on the host's loopback interface alone, as the node's web interfaces' are. It goes before its primary node, whose network it shares, @@ -1105,8 +1121,12 @@ holding the driver and its executors, or a command or a script. The cluster itse own `-amzn` builds; Floci runs the Trino project's image of the same version (see **Trino**), so a connector that image has no plugin for stops Trino, with what it logged, and the step. Floci starts it in the background as the cluster becomes ready, so the cluster is `WAITING` before Trino answers, where EMR's runs once the cluster is up, and - a client meanwhile gets a `503`. Its `trino-connector-*`, `trino-config`, `trino-node`, `trino-log`, `trino-env` and - `trino-exchange-manager` classifications apply; `trino-password-authenticator` does not yet. With `docker-network` set + a client meanwhile gets a `503`. Its `trino-connector-*`, `trino-config`, `trino-node`, `trino-log`, `trino-env`, + `trino-exchange-manager` and `trino-password-authenticator` classifications apply. Trino has no HTTPS of its own: + EMR serves it over HTTPS on port 8446 with a security configuration's in-transit encryption, which its LDAP guide + has password authentication need and which Floci does not apply, so Trino takes a password only through Floci with + its TLS on, and a step's `trino-cli`, over plain HTTP, gets Trino's `403` once Trino takes passwords. With + `docker-network` set to `host`, `container:` or `none` it does not run, as the metastore service does not. From `emr-7.14.0` on, "When you select Trino as the only application at launch, Amazon EMR no longer starts YARN and HDFS"; Floci's primary node still runs the HDFS, beside the metastore. diff --git a/src/main/java/io/floci/aws/core/common/docker/ContainerFiles.java b/src/main/java/io/floci/aws/core/common/docker/ContainerFiles.java new file mode 100644 index 0000000000..ff0ac773b2 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/docker/ContainerFiles.java @@ -0,0 +1,41 @@ +package io.floci.aws.core.common.docker; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.exception.NotFoundException; +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.util.Optional; + +/** + * A file read out of a container, running or not, through Docker's archive API, which needs no shell in it: Docker + * sends a path as a tar whose first entry is the path itself. + */ +public final class ContainerFiles { + + private ContainerFiles() { + } + + /** What the file at {@code path} in container {@code containerId} holds, or empty where it holds no file there. */ + public static Optional read(DockerClient docker, String containerId, String path) { + return read(docker, containerId, path, Integer.MAX_VALUE); + } + + /** As {@link #read(DockerClient, String, String)}: at most the first {@code maxBytes} of it. */ + public static Optional read(DockerClient docker, String containerId, String path, int maxBytes) { + try (InputStream archive = docker.copyArchiveFromContainerCmd(containerId, path).exec(); + TarArchiveInputStream entries = new TarArchiveInputStream(archive)) { + TarArchiveEntry entry = entries.getNextEntry(); + return entry != null && entry.isFile() ? Optional.of(entries.readNBytes(maxBytes)) : Optional.empty(); + } catch (NotFoundException expected) { + // Docker's answer for a path the container does not hold: no file there, which callers ask about. + return Optional.empty(); + } catch (IOException e) { + throw new UncheckedIOException("Could not read " + path + " from container " + containerId + ": " + + e.getMessage(), e); + } + } +} diff --git a/src/main/java/io/floci/aws/services/elasticache/container/ElastiCacheContainerManager.java b/src/main/java/io/floci/aws/services/elasticache/container/ElastiCacheContainerManager.java index e0513910f2..92f688f91c 100644 --- a/src/main/java/io/floci/aws/services/elasticache/container/ElastiCacheContainerManager.java +++ b/src/main/java/io/floci/aws/services/elasticache/container/ElastiCacheContainerManager.java @@ -6,6 +6,7 @@ import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.docker.ContainerBuilder; import io.floci.aws.core.common.docker.ContainerDetector; import io.floci.aws.core.common.docker.ContainerExec; +import io.floci.aws.core.common.docker.ContainerFiles; import io.floci.aws.core.common.docker.ContainerLifecycleManager; import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo; import io.floci.aws.core.common.docker.ContainerLifecycleManager.EndpointInfo; @@ -16,14 +17,12 @@ import io.floci.aws.core.common.docker.ContainerStorageHelper; import io.floci.aws.core.common.docker.RetryingTarCopier; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; -import org.apache.commons.compress.archivers.tar.TarArchiveEntry; -import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.jboss.logging.Logger; import java.io.Closeable; import java.io.IOException; -import java.io.InputStream; import java.io.OutputStream; +import java.io.UncheckedIOException; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.charset.StandardCharsets; @@ -425,20 +424,15 @@ public class ElastiCacheContainerManager { fileName = config.services().elasticache().shellLessBackendDbfilename(); } String path = directory.endsWith("/") ? directory + fileName : directory + "/" + fileName; - try (InputStream tar = lifecycleManager.getDockerClient() - .copyArchiveFromContainerCmd(containerId, path).exec(); - TarArchiveInputStream entries = new TarArchiveInputStream(tar)) { - TarArchiveEntry entry = entries.getNextEntry(); - while (entry != null && !entry.isFile()) { - entry = entries.getNextEntry(); - } - if (entry == null) { - throw new IllegalStateException("the snapshot file " + path + " is not in the backend"); - } - return Base64.getEncoder().encodeToString(entries.readAllBytes()); - } catch (IOException e) { - throw new IllegalStateException("could not read the snapshot file " + path + ": " + e.getMessage(), e); + byte[] snapshot; + try { + snapshot = ContainerFiles.read(lifecycleManager.getDockerClient(), containerId, path).orElseThrow( + () -> new IllegalStateException("the snapshot file " + path + " is not in the backend")); + } catch (UncheckedIOException e) { + throw new IllegalStateException("could not read the snapshot file " + path + ": " + + e.getCause().getMessage(), e.getCause()); } + return Base64.getEncoder().encodeToString(snapshot); } public void stop(ElastiCacheContainerHandle handle) { diff --git a/src/main/java/io/floci/aws/services/emr/ClusterStorage.java b/src/main/java/io/floci/aws/services/emr/ClusterStorage.java index e594cb24ac..95086327db 100644 --- a/src/main/java/io/floci/aws/services/emr/ClusterStorage.java +++ b/src/main/java/io/floci/aws/services/emr/ClusterStorage.java @@ -127,13 +127,17 @@ public interface ClusterStorage { * {@link EmrTrino#catalogs}), its {@code trino-config} properties, which its {@code config.properties} gets after * Floci's (see {@link EmrTrino#config}), its {@code trino-node} and {@code trino-log} properties, which its * {@code node.properties} and {@code log.properties} get after its image's own (see {@link EmrTrino#ENTRYPOINT}), - * the variables its {@code trino-env} exports, which its environment gets after Floci's own, and its + * the variables its {@code trino-env} exports, which its environment gets after Floci's own, its * {@code trino-exchange-manager} properties, null where it has none, which make its exchange manager (see - * {@link EmrTrino#exchangeManager}). It reaches S3 and Glue as the metastore does. + * {@link EmrTrino#exchangeManager}), its {@code trino-password-authenticator} properties, which make its password + * authenticator, and the image its bootstrap actions left, null where it has none, from which the files those + * properties name are copied into Trino's container ({@link EmrTrino#authenticatorFiles}), as EMR's Trino finds + * what they wrote on the primary node it runs on. It reaches S3 and Glue as the metastore does. */ record Trino(String image, int memoryMb, Map> connectors, Map config, Map node, Map log, Map environment, - Map exchangeManager) { + Map exchangeManager, Map passwordAuthenticator, + String bootstrapImage) { } /** diff --git a/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java b/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java index b99f6ed07b..717d88e8bb 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java +++ b/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java @@ -1,5 +1,6 @@ package io.floci.aws.services.emr; +import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.command.InspectVolumeResponse; import com.github.dockerjava.api.command.ListVolumesResponse; @@ -14,11 +15,13 @@ import io.floci.aws.core.common.ContainerTeardown; import io.floci.aws.core.common.S3Uri; import io.floci.aws.core.common.docker.ContainerBuilder; import io.floci.aws.core.common.docker.ContainerExec; +import io.floci.aws.core.common.docker.ContainerFiles; import io.floci.aws.core.common.docker.ContainerLifecycleManager; import io.floci.aws.core.common.docker.ContainerLiveness; 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.core.common.docker.RetryingTarCopier; import io.floci.aws.services.ec2.model.Instance; import io.floci.aws.services.emrserverless.EmrServerlessSparkRunner; import io.floci.aws.services.emrserverless.SparkJobRunner; @@ -195,9 +198,10 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // 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. + // How long Trino keeps saying it has started 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 says it has started, and runs a query with no catalog, before then: + // twice that, from the first time it says so. 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. @@ -1616,6 +1620,8 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { .withEnv(EmrTrino.CONFIG_VARIABLE, EmrTrino.properties(EmrTrino.config(trino.config()))) .withEnv(EmrTrino.NODE_VARIABLE, EmrTrino.properties(trino.node())) .withEnv(EmrTrino.LOG_VARIABLE, EmrTrino.properties(trino.log())) + .withEnv(EmrTrino.PASSWORD_AUTHENTICATOR_VARIABLE, + EmrTrino.properties(trino.passwordAuthenticator())) .withJavaTrustStore() .withLogRotation() .withLabels(labels(clusterId, accountId, region, EmrTrino.COMPONENT)); @@ -1625,7 +1631,13 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { spec.withEnv(EmrTrino.EXCHANGE_VARIABLE, EmrTrino.properties(EmrTrino.exchangeManager( trino.exchangeManager(), endpoint, region))); } - lifecycleManager.createAndStart(spec.build()); + List files = EmrTrino.authenticatorFiles(trino.passwordAuthenticator()); + if (files.isEmpty() || trino.bootstrapImage() == null) { + lifecycleManager.createAndStart(spec.build()); + } else { + lifecycleManager.createAndStart(spec.build(), container -> copyAuthenticatorFiles(clusterId, + accountId, region, container, trino.bootstrapImage(), files)); + } } catch (RuntimeException e) { releaseSession(name); throw e; @@ -1634,10 +1646,35 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { stopIfStopped(clusterId, teardown, stopped); LOG.infov("Started the Trino of EMR cluster {0}", clusterId); } - awaitTrino(clusterId, name, EmrTrino.port(trino.config()), teardown, stopped); + awaitTrino(clusterId, name, teardown, stopped); readyTrino.add(name); } + // The files the cluster's password authenticator names, copied into container, its Trino's, made and not started, + // from image, the one its bootstrap actions left, as EMR's Trino finds what they wrote on the primary node it runs + // on: readable by the user Trino runs as, whoever owned them there. One the image does not hold is left to Trino's + // own image, and Trino says so where neither holds it. The image is read in a container made from it and never + // started, labelled as the cluster's Trino, so that a Floci that stops while it copies sweeps it with that Trino. + private void copyAuthenticatorFiles(String clusterId, String accountId, String region, String container, + String image, List files) { + DockerClient docker = lifecycleManager.getDockerClient(); + String source = docker.createContainerCmd(image) + .withLabels(labels(clusterId, accountId, region, EmrTrino.COMPONENT)).exec().getId(); + try { + for (String file : files) { + ContainerFiles.read(docker, source, file).ifPresent(content -> + RetryingTarCopier.copyBytes(docker, container, "/", file.substring(1), content, 0644)); + } + } finally { + try { + docker.removeContainerCmd(source).withForce(true).exec(); + } catch (RuntimeException e) { + LOG.warnv("Could not remove container {0}, made to copy the Trino files of EMR cluster {1}: {2}", + source, clusterId, e.getMessage()); + } + } + } + // 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) { @@ -1673,10 +1710,10 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { } } - // Waits for the Trino container named so to have run a query on port 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, int port, long teardown, BooleanSupplier stopped) { + // Waits for the Trino container named so to have said it has started for TRINO_SETTLE, within TRINO_START_TIMEOUT + // (EmrTrino.READY_CHECK): 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()) { @@ -1686,10 +1723,10 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { throw new IllegalStateException("The Trino of EMR cluster " + clusterId + " stopped before it was ready"); } - ContainerExec.Result query; + ContainerExec.Result check; try { - query = ContainerExec.run(lifecycleManager.getDockerClient(), name, - EmrTrino.readyQuery(port).toArray(String[]::new), 30); + check = ContainerExec.run(lifecycleManager.getDockerClient(), name, + EmrTrino.READY_CHECK.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. @@ -1699,7 +1736,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { throw e; } long now = nanoTime.getAsLong(); - if (query.exitCode() != 0) { + if (check.exitCode() != 0) { answering = Long.MIN_VALUE; } else if (answering == Long.MIN_VALUE) { answering = now; diff --git a/src/main/java/io/floci/aws/services/emr/EmrService.java b/src/main/java/io/floci/aws/services/emr/EmrService.java index f05ae11d6d..a88fee82b9 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrService.java @@ -3148,7 +3148,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear EmrSparkSteps.trinoNode(cluster.getConfigurations(), SNAPSHOT_MAPPER), EmrSparkSteps.trinoLog(cluster.getConfigurations(), SNAPSHOT_MAPPER), EmrSparkSteps.trinoEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER), - EmrSparkSteps.trinoExchangeManager(cluster.getConfigurations(), SNAPSHOT_MAPPER)); + EmrSparkSteps.trinoExchangeManager(cluster.getConfigurations(), SNAPSHOT_MAPPER), + EmrSparkSteps.trinoPasswordAuthenticator(cluster.getConfigurations(), SNAPSHOT_MAPPER), + cluster.getBootstrapImage()); ClusterStorage.HiveMetastore hiveMetastore = withHiveImage(cluster) ? new ClusterStorage.HiveMetastore(instanceProfileRole(cluster, accountId), EmrSparkSteps.hiveMetastoreSettings(cluster.getConfigurations(), SNAPSHOT_MAPPER), trino) diff --git a/src/main/java/io/floci/aws/services/emr/EmrSparkSteps.java b/src/main/java/io/floci/aws/services/emr/EmrSparkSteps.java index 3e078290ad..282e1bb534 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrSparkSteps.java +++ b/src/main/java/io/floci/aws/services/emr/EmrSparkSteps.java @@ -321,6 +321,14 @@ final class EmrSparkSteps { : properties(configurations, objectMapper, EmrTrino.EXCHANGE_CLASSIFICATION); } + /** + * The properties of a cluster's {@code trino-password-authenticator}, which make its Trino's + * {@code password-authenticator.properties}. + */ + static Map trinoPasswordAuthenticator(String configurations, ObjectMapper objectMapper) { + return properties(configurations, objectMapper, EmrTrino.PASSWORD_AUTHENTICATOR_CLASSIFICATION); + } + /** The properties of a cluster's {@code trino-log}, which make its Trino's {@code log.properties}. */ static Map trinoLog(String configurations, ObjectMapper objectMapper) { return properties(configurations, objectMapper, EmrTrino.LOG_CLASSIFICATION); diff --git a/src/main/java/io/floci/aws/services/emr/EmrTrino.java b/src/main/java/io/floci/aws/services/emr/EmrTrino.java index e3c2fc33f1..3cdb44dba8 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrTrino.java +++ b/src/main/java/io/floci/aws/services/emr/EmrTrino.java @@ -44,6 +44,15 @@ final class EmrTrino { static final String EXCHANGE_CLASSIFICATION = "trino-exchange-manager"; /** The classification whose nested {@code export} gives Trino's environment, Trino's {@code trino-env.sh}. */ static final String ENV_CLASSIFICATION = "trino-env"; + /** The classification that makes Trino's {@code password-authenticator.properties}. */ + static final String PASSWORD_AUTHENTICATOR_CLASSIFICATION = "trino-password-authenticator"; + /** + * The properties of Trino's password authenticators that name a file on the coordinator: the {@code file} + * authenticator's password file, and the key and trust stores of the {@code ldap} one's connection to its server, + * the trust store under its older name too, as Trino 446's plugins name them. + */ + static final List AUTHENTICATOR_FILES = List.of("file.password-file", "ldap.ssl.keystore.path", + "ldap.ssl.truststore.path", "ldap.ssl-trust-certificate"); /** The catalog every Trino cluster has. */ static final String HIVE = "hive"; /** @@ -87,6 +96,7 @@ final class EmrTrino { static final String NODE_VARIABLE = "FLOCI_TRINO_NODE"; static final String LOG_VARIABLE = "FLOCI_TRINO_LOG"; static final String EXCHANGE_VARIABLE = "FLOCI_TRINO_EXCHANGE"; + static final String PASSWORD_AUTHENTICATOR_VARIABLE = "FLOCI_TRINO_PASSWORD_AUTHENTICATOR"; /** The cluster's NameNode, which Trino reaches on the primary node whose network it shares. */ static final String NAMENODE = "hdfs://localhost:8020"; /** @@ -100,13 +110,21 @@ final class EmrTrino { /** The prefix of the variables it writes its catalogs from, one each, the rest of whose name names it. */ static final String CATALOG_PREFIX = "FLOCI_TRINO_CATALOG_"; /** - * The Trino container's entrypoint: its configuration; the cluster's node and log properties after those of its - * image's own files, which a property given twice takes the later of, so an image of the cluster's own keeps its - * settings; and the catalogs Floci gives it alone, as EMR's Trino has the catalogs the cluster configures; then - * Trino, as its image starts it. Where {@code node.properties} gives the node no id, its image names it after its - * host, the primary node's, whose dots Trino refuses in a node's id, so Floci names it with hyphens instead. + * The Trino container's entrypoint: its configuration, with a shared secret for Trino's internal communication + * unless the cluster's {@code trino-config} names one, as EMR "automatically configures a shared secret key for + * secure internal communication between cluster nodes ... and you can override the configuration with your own + * secret key", without which Trino refuses to start with authentication on, a new one each time it starts, which + * its one node shares with none; the cluster's node and log properties after those of its image's own files, which + * a property given twice takes the later of, so an image of the cluster's own keeps its settings; its password + * authenticator, where the cluster gives one; and the catalogs Floci gives it alone, as EMR's Trino has the + * catalogs the cluster configures; then Trino, as its image starts it. Where {@code node.properties} gives the node + * no id, its image names it after its host, the primary node's, whose dots Trino refuses in a node's id, so Floci + * names it with hyphens instead. */ static final String ENTRYPOINT = "printf '%s\\n' \"$" + CONFIG_VARIABLE + "\" > /etc/trino/config.properties" + + " && { grep -q '^internal-communication\\.shared-secret=' /etc/trino/config.properties" + + " || printf 'internal-communication.shared-secret=%s\\n' \"$(head -c 32 /dev/urandom | base64 -w0)\"" + + " >> /etc/trino/config.properties; }" + " && { [ -z \"$" + NODE_VARIABLE + "\" ] || printf '\\n%s\\n' \"$" + NODE_VARIABLE + "\"" + " >> /etc/trino/node.properties; }" + " && { [ -z \"$" + LOG_VARIABLE + "\" ] || printf '\\n%s\\n' \"$" + LOG_VARIABLE + "\"" @@ -114,6 +132,8 @@ final class EmrTrino { + " && { [ -z \"$" + EXCHANGE_VARIABLE + "\" ] || { printf '%s\\n' \"$" + EXCHANGE_VARIABLE + "\"" + " > /etc/trino/exchange-manager.properties && printf '%s\\n' '" + EXCHANGE_CORE_SITE + "' > " + EXCHANGE_HDFS_CONFIG + "; }; }" + + " && { [ -z \"$" + PASSWORD_AUTHENTICATOR_VARIABLE + "\" ] || printf '%s\\n' \"$" + + PASSWORD_AUTHENTICATOR_VARIABLE + "\" > /etc/trino/password-authenticator.properties; }" + " && rm -f /etc/trino/catalog/*.properties" + " && for catalog in ${!" + CATALOG_PREFIX + "@}; do printf '%s\\n' \"${!catalog}\"" + " > \"/etc/trino/catalog/${catalog#" + CATALOG_PREFIX + "}.properties\" || exit; done" @@ -185,10 +205,12 @@ final class EmrTrino { + base.getRawAuthority(); } - /** What tells the Trino container is ready: a query, run with the CLI of its image on {@code port}. */ - static List readyQuery(int port) { - return List.of(IMAGE_CLI, "--server", "localhost:" + port, "--execute", "SELECT 1"); - } + /** + * What tells the Trino container is ready: its image's own health check, which asks Trino, on the port its + * {@code config.properties} names, whether it is still starting, at {@code /v1/info}, which takes no credentials. A + * query would need those of a Trino that takes passwords, which Floci does not have. + */ + static final List READY_CHECK = List.of("/usr/lib/trino/bin/health-check"); /** * The coordinator's {@code config.properties}: a coordinator that runs the queries too, on its {@link #port}, its @@ -299,6 +321,16 @@ final class EmrTrino { return catalog; } + /** + * The files a cluster's {@code trino-password-authenticator} properties name ({@link #AUTHENTICATOR_FILES}), each + * once, in their order: those whose path is absolute, as Trino's container has no folder of the cluster's own a + * relative one would be in. + */ + static List authenticatorFiles(Map passwordAuthenticator) { + return AUTHENTICATOR_FILES.stream().map(passwordAuthenticator::get) + .filter(path -> path != null && path.trim().startsWith("/")).map(String::trim).distinct().toList(); + } + /** {@code properties} as the lines of a Java properties file, in their order. */ static String properties(Map properties) { return properties.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue()) diff --git a/src/main/java/io/floci/aws/services/emr/EmrTrinoRoutes.java b/src/main/java/io/floci/aws/services/emr/EmrTrinoRoutes.java index 43cfe2c41f..0e40ece480 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrTrinoRoutes.java +++ b/src/main/java/io/floci/aws/services/emr/EmrTrinoRoutes.java @@ -18,11 +18,13 @@ import java.util.regex.Pattern; /** * A cluster's Trino as clients outside the cluster reach it, through Floci, on a host of the cluster's own, * {@code .}{@value EmrTrino#HOST_LABEL}{@code .} ({@link EmrTrino#address}), as - * EMR's clients reach Trino on the primary node: no AWS API gives an address for it. The host takes no credentials, as - * Floci's Trino has no authentication, so whoever reaches Floci's port reaches the cluster's Trino. Trino names a - * query's next pages by the host it was asked on, which the request keeps, and by the scheme it was reached over, - * which goes on as {@code X-Forwarded-Proto}. A cluster whose Trino is not running yet has its primary node started, - * as an application UI link does, and the request answered with a {@code 503}, which Trino's clients try again on. + * EMR's clients reach Trino on the primary node: no AWS API gives an address for it. The host asks for no credentials + * of its own: the cluster's Trino asks for those its {@code trino-config} and {@code trino-password-authenticator} + * configure, and where they configure none, whoever reaches Floci's port reaches the cluster's Trino. Trino names a + * query's next pages by the host it was asked on, which the request keeps, and by the scheme it was reached over, which + * goes on as {@code X-Forwarded-Proto}, and takes a password only where that scheme is HTTPS, through Floci with its + * TLS on. A cluster whose Trino is not running yet has its primary node started, as an application UI link does, and + * the request answered with a {@code 503}, which Trino's clients try again on. */ @ApplicationScoped public class EmrTrinoRoutes implements AppUiRoutes { diff --git a/src/main/java/io/floci/aws/services/lambdaweb/LambdaWebEnvironmentManager.java b/src/main/java/io/floci/aws/services/lambdaweb/LambdaWebEnvironmentManager.java index fef4ed38c5..ba4c4f28fc 100644 --- a/src/main/java/io/floci/aws/services/lambdaweb/LambdaWebEnvironmentManager.java +++ b/src/main/java/io/floci/aws/services/lambdaweb/LambdaWebEnvironmentManager.java @@ -13,6 +13,7 @@ import io.floci.aws.core.common.ContainerTeardown; import io.floci.aws.core.common.FileTrees; import io.floci.aws.core.common.docker.ContainerBuilder; import io.floci.aws.core.common.docker.ContainerExec; +import io.floci.aws.core.common.docker.ContainerFiles; import io.floci.aws.core.common.docker.ContainerLifecycleManager; import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo; import io.floci.aws.core.common.docker.ContainerLifecycleManager.EndpointInfo; @@ -32,7 +33,6 @@ import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; -import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.jboss.logging.Logger; @@ -807,15 +807,11 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown { /** The page for an app that ended with an error before it listened. The container has stopped but still exists. */ private LambdaWebErrorPages.Page initErrorPage(String containerId) { String errorType = ""; - try (InputStream archive = lifecycleManager.getDockerClient() - .copyArchiveFromContainerCmd(containerId, INIT_ERROR_FILE).exec(); - TarArchiveInputStream tar = new TarArchiveInputStream(archive)) { - if (tar.getNextEntry() != null) { - errorType = new String(tar.readNBytes(INIT_ERROR_MAX_BYTES), StandardCharsets.UTF_8); - } - } catch (NotFoundException expected) { - // The app exited on its own, so index.mjs wrote no error type. - } catch (IOException | RuntimeException e) { + try { + // None where the app exited on its own, so index.mjs wrote no error type. + errorType = ContainerFiles.read(lifecycleManager.getDockerClient(), containerId, INIT_ERROR_FILE, + INIT_ERROR_MAX_BYTES).map(bytes -> new String(bytes, StandardCharsets.UTF_8)).orElse(""); + } catch (RuntimeException e) { LOG.warnv(e, "Could not read the init error of the Lambda Web environment {0}", containerId); } return switch (errorType) { diff --git a/src/test/java/io/floci/aws/core/common/docker/ContainerFilesTest.java b/src/test/java/io/floci/aws/core/common/docker/ContainerFilesTest.java new file mode 100644 index 0000000000..0c5e957b36 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/docker/ContainerFilesTest.java @@ -0,0 +1,90 @@ +package io.floci.aws.core.common.docker; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.CopyArchiveFromContainerCmd; +import com.github.dockerjava.api.exception.NotFoundException; +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.util.Optional; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class ContainerFilesTest { + + private final DockerClient docker = mock(DockerClient.class); + + @Test + void aFileIsWhatItsArchiveHoldsWholeOrItsFirstBytes() throws IOException { + archives("/etc/app/settings.conf", tar("settings.conf", "name=value\n")); + + assertEquals("name=value\n", new String(ContainerFiles.read(docker, "c-1", "/etc/app/settings.conf") + .orElseThrow(), UTF_8)); + assertEquals("name", new String(ContainerFiles.read(docker, "c-1", "/etc/app/settings.conf", 4) + .orElseThrow(), UTF_8)); + } + + @Test + void aPathTheContainerDoesNotHoldOrThatIsAFolderIsNoFile() throws IOException { + CopyArchiveFromContainerCmd missing = mock(CopyArchiveFromContainerCmd.class); + when(missing.exec()).thenThrow(new NotFoundException("Could not find the file /etc/missing in container c-1")); + when(docker.copyArchiveFromContainerCmd("c-1", "/etc/missing")).thenReturn(missing); + ByteArrayOutputStream folder = new ByteArrayOutputStream(); + try (TarArchiveOutputStream out = new TarArchiveOutputStream(folder)) { + out.putArchiveEntry(new TarArchiveEntry("app/")); + out.closeArchiveEntry(); + } + archives("/etc/app", folder.toByteArray()); + + assertEquals(Optional.empty(), ContainerFiles.read(docker, "c-1", "/etc/missing")); + assertEquals(Optional.empty(), ContainerFiles.read(docker, "c-1", "/etc/app")); + } + + @Test + void anArchiveThatCannotBeReadIsAFailure() { + // Docker's connection, gone while the archive comes. + InputStream broken = new InputStream() { + @Override + public int read() throws IOException { + throw new IOException("connection reset"); + } + }; + CopyArchiveFromContainerCmd copy = mock(CopyArchiveFromContainerCmd.class); + when(copy.exec()).thenReturn(broken); + when(docker.copyArchiveFromContainerCmd("c-1", "/etc/app/settings.conf")).thenReturn(copy); + + UncheckedIOException failure = assertThrows(UncheckedIOException.class, + () -> ContainerFiles.read(docker, "c-1", "/etc/app/settings.conf")); + assertTrue(failure.getMessage().contains("connection reset"), failure.getMessage()); + } + + private void archives(String path, byte[] tar) { + CopyArchiveFromContainerCmd copy = mock(CopyArchiveFromContainerCmd.class); + when(copy.exec()).thenAnswer(reading -> new ByteArrayInputStream(tar)); + when(docker.copyArchiveFromContainerCmd("c-1", path)).thenReturn(copy); + } + + private static byte[] tar(String name, String content) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (TarArchiveOutputStream out = new TarArchiveOutputStream(bytes)) { + byte[] data = content.getBytes(UTF_8); + TarArchiveEntry entry = new TarArchiveEntry(name); + entry.setSize(data.length); + out.putArchiveEntry(entry); + out.write(data); + out.closeArchiveEntry(); + } + return bytes.toByteArray(); + } +} diff --git a/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java b/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java index 107f03d16e..e02810e266 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java @@ -2,6 +2,9 @@ package io.floci.aws.services.emr; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.CopyArchiveFromContainerCmd; +import com.github.dockerjava.api.command.CopyArchiveToContainerCmd; +import com.github.dockerjava.api.command.CreateContainerCmd; +import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.ExecCreateCmd; import com.github.dockerjava.api.command.InspectContainerCmd; import com.github.dockerjava.api.command.InspectContainerResponse; @@ -12,6 +15,7 @@ import com.github.dockerjava.api.command.ListContainersCmd; import com.github.dockerjava.api.command.ListNetworksCmd; import com.github.dockerjava.api.command.ListVolumesCmd; import com.github.dockerjava.api.command.ListVolumesResponse; +import com.github.dockerjava.api.command.RemoveContainerCmd; import com.github.dockerjava.api.exception.ConflictException; import com.github.dockerjava.api.exception.DockerException; import com.github.dockerjava.api.exception.NotFoundException; @@ -43,6 +47,7 @@ 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.TarArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -76,6 +81,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BooleanSupplier; +import java.util.function.Consumer; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; @@ -128,7 +134,7 @@ class EmrClusterStorageTest { 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(), Map.of(), Map.of(), Map.of(), - Map.of(), null)); + Map.of(), null, Map.of(), null)); private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); private final DockerClient docker = mock(DockerClient.class); @@ -2017,9 +2023,10 @@ class EmrClusterStorageTest { 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 query = List.of("/usr/bin/trino", "--server", "localhost:8889", "--execute", "SELECT 1"); - assertEquals(List.of(query, query, query, query), asked); + // Waited for, until its image's health check has passed for ten seconds: the first fails, the next three + // pass. + assertEquals(List.of(EmrTrino.READY_CHECK, EmrTrino.READY_CHECK, EmrTrino.READY_CHECK, EmrTrino.READY_CHECK), + asked); ticking.remove("j-1"); @@ -2065,10 +2072,14 @@ class EmrClusterStorageTest { when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-6", Map.of()), new ContainerLifecycleManager.ContainerInfo("t-1", Map.of())); ContainerBuilder.Builder trinoSpec = trinoStarts(trinoName).spec(); + Map authenticator = new LinkedHashMap<>(); + authenticator.put("password-authenticator.name", "file"); + authenticator.put("file.password-file", "/etc/trino/password.db"); ClusterStorage.HiveMetastore metastore = new ClusterStorage.HiveMetastore("arn:aws:iam::123456789012:role/r", Map.of(), new ClusterStorage.Trino("trinodb/trino:446", 2048, Map.of(), Map.of(), Map.of("node.environment", "production"), Map.of("io.trino", "DEBUG"), - Map.of("DB_PASSWORD", "s3cret"), Map.of("exchange.base-directories", "s3://spool/exchange"))); + Map.of("DB_PASSWORD", "s3cret"), Map.of("exchange.base-directories", "s3://spool/exchange"), + authenticator, null)); ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", metastore, null, NOT_STOPPED); @@ -2080,6 +2091,11 @@ class EmrClusterStorageTest { order.verify(trinoSpec).withEnv(EmrTrino.CONFIG_VARIABLE, EmrTrino.properties(EmrTrino.config(Map.of()))); order.verify(trinoSpec).withEnv(EmrTrino.NODE_VARIABLE, "node.environment=production"); order.verify(trinoSpec).withEnv(EmrTrino.LOG_VARIABLE, "io.trino=DEBUG"); + order.verify(trinoSpec).withEnv(EmrTrino.PASSWORD_AUTHENTICATOR_VARIABLE, + "password-authenticator.name=file\nfile.password-file=/etc/trino/password.db"); + // With no image the cluster's bootstrap actions left, nothing to copy its password file from: Trino's own + // image may hold it. + verify(lifecycle, never()).createAndStart(any(), any(Consumer.class)); // Its exchange manager's spool in Floci's S3. verify(trinoSpec).withEnv(EmrTrino.EXCHANGE_VARIABLE, "exchange-manager.name=filesystem\n" + "exchange.base-directories=s3://spool/exchange\n" @@ -2088,7 +2104,65 @@ class EmrClusterStorageTest { } @Test - void trinoIsReadyOnceItHasRunAQueryForTenSecondsAFailureBetweenStartingThemAgain() { + void theFilesTrinosPasswordAuthenticatorNamesComeFromTheBootstrapImageBeforeItStarts() throws IOException { + String trinoName = ContainerStorageHelper.dockerName(config, "emr-j-1-trino"); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-6", Map.of())); + List copiedBeforeStart = new ArrayList<>(); + when(lifecycle.createAndStart(any(), any(Consumer.class))).thenAnswer(starting -> { + starting.>getArgument(1).accept("t-1"); + copiedBeforeStart.add("t-1"); + return new ContainerLifecycleManager.ContainerInfo("t-1", Map.of()); + }); + trinoStarts(trinoName); + // The image the cluster's bootstrap actions left, read in a container made from it, which holds the trust + // store they wrote and no key store. + CreateContainerCmd create = mock(CreateContainerCmd.class, RETURNS_SELF); + CreateContainerResponse created = mock(CreateContainerResponse.class); + when(created.getId()).thenReturn("source-1"); + when(create.exec()).thenReturn(created); + when(docker.createContainerCmd("sha256:bootstrapped")).thenReturn(create); + CopyArchiveFromContainerCmd truststore = mock(CopyArchiveFromContainerCmd.class); + when(truststore.exec()).thenAnswer(reading -> new ByteArrayInputStream(tar(Map.of("truststore.pem", + "-----BEGIN CERTIFICATE-----")))); + when(docker.copyArchiveFromContainerCmd("source-1", "/home/hadoop/ldap/truststore.pem")).thenReturn(truststore); + when(docker.copyArchiveFromContainerCmd("source-1", "/home/hadoop/ldap/keystore.pem")) + .thenThrow(new NotFoundException("none")); + CopyArchiveToContainerCmd copy = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF); + ArgumentCaptor archive = ArgumentCaptor.forClass(InputStream.class); + when(docker.copyArchiveToContainerCmd("t-1")).thenReturn(copy); + RemoveContainerCmd remove = mock(RemoveContainerCmd.class, RETURNS_SELF); + when(docker.removeContainerCmd("source-1")).thenReturn(remove); + Map ldap = new LinkedHashMap<>(); + ldap.put("password-authenticator.name", "ldap"); + ldap.put("ldap.url", "ldaps://ldap.example.com:636"); + ldap.put("ldap.ssl.truststore.path", "/home/hadoop/ldap/truststore.pem"); + ldap.put("ldap.ssl.keystore.path", "/home/hadoop/ldap/keystore.pem"); + ClusterStorage.HiveMetastore metastore = new ClusterStorage.HiveMetastore("arn:aws:iam::123456789012:role/r", + Map.of(), new ClusterStorage.Trino("trinodb/trino:446", 2048, Map.of(), Map.of(), Map.of(), Map.of(), + Map.of(), null, ldap, "sha256:bootstrapped")); + + ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", metastore, null, NOT_STOPPED); + + assertEquals(List.of("t-1"), copiedBeforeStart); + // The cluster's Trino's labels, so that a sweep finds it with that Trino. + verify(create).withLabels(argThat(labels -> EmrTrino.COMPONENT.equals( + labels.get(ContainerStorageHelper.COMPONENT_LABEL)))); + // At its path, readable by the user Trino runs as; the key store it does not hold is left to Trino's image. + verify(copy).withRemotePath("/"); + verify(copy).withTarInputStream(archive.capture()); + try (TarArchiveInputStream entries = new TarArchiveInputStream(archive.getValue())) { + TarArchiveEntry entry = entries.getNextEntry(); + assertEquals("home/hadoop/ldap/truststore.pem", entry.getName()); + assertEquals(0644, entry.getMode() & 0777); + assertEquals("-----BEGIN CERTIFICATE-----", new String(entries.readAllBytes(), UTF_8)); + assertNull(entries.getNextEntry()); + } + verify(docker, times(1)).copyArchiveToContainerCmd("t-1"); + verify(remove).exec(); + } + + @Test + void trinoIsReadyOnceItsHealthCheckHasPassedForTenSecondsAFailureBetweenStartingThemAgain() { 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())); @@ -2100,8 +2174,10 @@ class EmrClusterStorageTest { 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. + // Five seconds between each: ten seconds of answers only from the third. Each its image's health check, + // which takes no credentials. assertEquals(5, asked.size(), asked.toString()); + assertEquals(EmrTrino.READY_CHECK, asked.get(0)); } @Test diff --git a/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java b/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java index 21a9e84a83..6c752a02ff 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java @@ -1115,7 +1115,9 @@ class EmrServiceContainerStepsTest { + "{\"Classification\": \"trino-log\", \"Properties\": {\"io.trino\": \"DEBUG\"}}, " + "{\"Classification\": \"trino-env\", \"Configurations\": [{\"Classification\": \"export\", " + "\"Properties\": {\"DB_PASSWORD\": \"s3cret\"}}]}, " - + "{\"Classification\": \"trino-exchange-manager\"}]"); + + "{\"Classification\": \"trino-exchange-manager\"}, " + + "{\"Classification\": \"trino-password-authenticator\", \"Properties\": " + + "{\"password-authenticator.name\": \"ldap\", \"ldap.url\": \"ldaps://ldap.example.com:636\"}}]"); withTrino.runJobFlow(requested, REGION); fixture.runStepThread(); @@ -1129,7 +1131,8 @@ class EmrServiceContainerStepsTest { assertEquals(new ClusterStorage.Trino("trinodb/trino:446", 2048, Map.of("hive", Map.of("hive.metastore", "glue"), "tpch", Map.of()), Map.of("http-server.http.port", "8890"), Map.of("node.environment", "production"), Map.of("io.trino", "DEBUG"), - Map.of("DB_PASSWORD", "s3cret"), Map.of()), fixture.clusterStorage.metastores.get(0).trino()); + Map.of("DB_PASSWORD", "s3cret"), Map.of(), Map.of("password-authenticator.name", "ldap", "ldap.url", + "ldaps://ldap.example.com:636"), null), 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); @@ -1153,10 +1156,36 @@ class EmrServiceContainerStepsTest { fixture.runStepThread(); assertEquals(List.of("true"), runner.jobs.get(0).command()); assertEquals(new ClusterStorage.Trino("trinodb/trino:446", 2048, Map.of(), Map.of(), Map.of(), Map.of(), - Map.of(), null), fixture.clusterStorage.metastores.get(0).trino()); + Map.of(), null, Map.of(), null), fixture.clusterStorage.metastores.get(0).trino()); assertEquals(0, fixture.stepThreadsWaiting()); } + @Test + void aClustersTrinoCopiesTheFilesItsPasswordAuthenticatorNamesFromTheImageItsBootstrapActionsLeft() { + EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null); + bootstrapping.clusterStorage.ownNetwork = true; + bootstrap.outcomes = ran -> BootstrapRunner.Outcome.succeeded("sha256:" + ran.name()); + EmrService withTrino = bootstrapping.withTrino(); + EmrCluster requested = bootstrapped(cluster("trino", true)); + requested.setApplications(TRINO); + requested.setConfigurations(""" + [{"Classification": "trino-config", "Properties": {"http-server.authentication.type": "PASSWORD"}}, + {"Classification": "trino-password-authenticator", "Properties": { + "password-authenticator.name": "file", "file.password-file": "/home/hadoop/password.db"}}]"""); + String id = withTrino.runJobFlow(requested, REGION).getId(); + + // Its bootstrap, then its primary node and Trino, as it becomes ready. + while (bootstrapping.stepThreadsWaiting() > 0) { + bootstrapping.runStepThread(); + } + + // What the actions wrote is in the image they left, the primary node's. + assertEquals(new ClusterStorage.Trino("trinodb/trino:446", 2048, Map.of(), + Map.of("http-server.authentication.type", "PASSWORD"), Map.of(), Map.of(), Map.of(), null, + Map.of("password-authenticator.name", "file", "file.password-file", "/home/hadoop/password.db"), + "sha256:" + id), bootstrapping.clusterStorage.metastores.get(0).trino()); + } + @Test void aClusterWithoutFlocisTrinoStartsNothingAsItBecomesReady() { fixture.clusterStorage.ownNetwork = true; diff --git a/src/test/java/io/floci/aws/services/emr/EmrSparkStepsTest.java b/src/test/java/io/floci/aws/services/emr/EmrSparkStepsTest.java index 360eafb01a..0504e01de1 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrSparkStepsTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrSparkStepsTest.java @@ -271,6 +271,24 @@ class EmrSparkStepsTest { objectMapper)); } + @Test + void trinosPasswordAuthenticatorIsTheClustersTrinoPasswordAuthenticator() { + // The Release Guide's LDAP example, its trino-config apart. + String configurations = """ + [{"Classification": "trino-config", "Properties": {"http-server.authentication.type": "PASSWORD"}}, + {"Classification": "trino-password-authenticator", + "Properties": {"password-authenticator.name": "ldap", + "ldap.url": "ldaps://ip-xxx-xxx-xxx-xxx.ec2.internal:636", + "ldap.user-bind-pattern": "uid=${USER},ou=admins,dc=ec2,dc=internal"}}] + """; + + assertEquals(Map.of("password-authenticator.name", "ldap", "ldap.url", + "ldaps://ip-xxx-xxx-xxx-xxx.ec2.internal:636", "ldap.user-bind-pattern", + "uid=${USER},ou=admins,dc=ec2,dc=internal"), + EmrSparkSteps.trinoPasswordAuthenticator(configurations, objectMapper)); + assertEquals(Map.of(), EmrSparkSteps.trinoPasswordAuthenticator("[]", objectMapper)); + } + @Test void trinosCatalogsAreTheClustersTrinoConnectorsALaterConfigurationWinning() { String configurations = """ diff --git a/src/test/java/io/floci/aws/services/emr/EmrTrinoHttpsIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrTrinoHttpsIntegrationTest.java new file mode 100644 index 0000000000..1179e6c6b7 --- /dev/null +++ b/src/test/java/io/floci/aws/services/emr/EmrTrinoHttpsIntegrationTest.java @@ -0,0 +1,145 @@ +package io.floci.aws.services.emr; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import io.floci.aws.config.SelfSignedTlsProfile; +import io.floci.aws.core.common.docker.ContainerLifecycleManager; +import io.quarkus.test.junit.QuarkusMock; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.Response; +import org.eclipse.microprofile.config.inject.ConfigProperty; +import org.junit.jupiter.api.AfterAll; +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 java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.util.Base64; +import java.util.List; +import java.util.Locale; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; + +import static io.restassured.RestAssured.given; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * A password sent to a cluster's Trino through Floci's own HTTPS listener, as a client with Floci's TLS on sends it to + * the cluster's host: Floci takes the request over TLS, and its route to the cluster's Trino passes the password on + * with {@code X-Forwarded-Proto: https}, the one scheme Trino takes a password over. Trino here is a stand-in that + * answers as Trino 446 does with {@code PASSWORD} authentication (measured): {@code 403} to plain HTTP, {@code 401} + * to a wrong password or none, a query's first page to the right one. {@link EmrTrinoNightlyIntegrationTest} shows + * the real Trino of a cluster answering so to that header; here no Docker is needed, as the cluster is a mock. + */ +@QuarkusTest +@TestProfile(SelfSignedTlsProfile.class) +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class EmrTrinoHttpsIntegrationTest { + + private static final String CLUSTER = "j-2AXXXXXXGAPLF"; + private static final String RIGHT = "Basic " + Base64.getEncoder().encodeToString("alice:secret1".getBytes(UTF_8)); + private static final String WRONG = "Basic " + Base64.getEncoder().encodeToString("alice:secret2".getBytes(UTF_8)); + + @ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0") + int sslPort; + + @ConfigProperty(name = "quarkus.http.test-port", defaultValue = "0") + int httpPort; + + private HttpServer trino; + // The scheme each request reached the stand-in with, as X-Forwarded-Proto named it. + private final List schemes = new CopyOnWriteArrayList<>(); + + @BeforeAll + void startTrino() throws IOException { + trino = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + trino.createContext("/v1/statement", this::answer); + trino.start(); + } + + @AfterAll + void stopTrino() { + if (trino != null) { + trino.stop(0); + } + } + + // The cluster's Trino running, at the stand-in, as EmrService finds a cluster's once it answers. + @BeforeEach + void runningCluster() { + EmrService clusters = mock(EmrService.class); + when(clusters.trinoCluster(CLUSTER)).thenReturn(Optional.of(new EmrService.TrinoCluster("000000000000", + "us-east-1", CLUSTER, EmrClusterLifecycle.WAITING, EmrTrino.PORT))); + when(clusters.trinoInterface(CLUSTER, EmrTrino.PORT)).thenReturn(Optional.of( + new ContainerLifecycleManager.EndpointInfo("127.0.0.1", trino.getAddress().getPort()))); + QuarkusMock.installMockForType(clusters, EmrService.class); + schemes.clear(); + } + + @Test + void overFlocisHttpsTrinoChecksThePasswordAndAnswersAsItDoes() { + Response right = overHttps(RIGHT); + Response wrong = overHttps(WRONG); + + assertEquals(200, right.statusCode(), right.asString()); + assertEquals("{\"id\":\"20261129_000000_00000_floci\"}", right.asString()); + assertEquals(401, wrong.statusCode(), wrong.asString()); + // Trino's challenge, back to the client as Trino sent it. + assertEquals("Basic realm=\"Trino\"", wrong.header("WWW-Authenticate")); + assertEquals(List.of("https", "https"), schemes); + } + + @Test + void overPlainHttpTrinoRefusesThePasswordWhateverSchemeTheClientClaims() { + Response plain = given().baseUri("http://localhost:" + httpPort).header("Host", host(httpPort)) + .header("Authorization", RIGHT).header("X-Forwarded-Proto", "https").body("SELECT 1") + .post("/v1/statement"); + + // Floci names the scheme the client used, not the one it claims. + assertEquals(403, plain.statusCode(), plain.asString()); + assertEquals(List.of("http"), schemes); + } + + // A statement posted to the cluster's host over Floci's HTTPS, with authorization. + private Response overHttps(String authorization) { + return given().relaxedHTTPSValidation().baseUri("https://localhost:" + sslPort).header("Host", host(sslPort)) + .header("Authorization", authorization).body("SELECT 1").post("/v1/statement"); + } + + // The cluster's host under Floci's, on the port the request goes to. + private static String host(int port) { + return CLUSTER.toLowerCase(Locale.ROOT) + "." + EmrTrino.HOST_LABEL + ".localhost:" + port; + } + + // Trino 446 with PASSWORD authentication, as measured: plain HTTP refused whatever the password, a wrong + // password or none challenged, the right one given the query's first page. + private void answer(HttpExchange exchange) throws IOException { + String scheme = exchange.getRequestHeaders().getFirst("X-Forwarded-Proto"); + schemes.add(String.valueOf(scheme)); + exchange.getRequestBody().readAllBytes(); + if (!"https".equals(scheme)) { + respond(exchange, 403, "Authentication over HTTP is not enabled"); + } else if (!RIGHT.equals(exchange.getRequestHeaders().getFirst("Authorization"))) { + exchange.getResponseHeaders().add("WWW-Authenticate", "Basic realm=\"Trino\""); + respond(exchange, 401, "Access Denied: Invalid credentials"); + } else { + exchange.getResponseHeaders().add("Content-Type", "application/json"); + respond(exchange, 200, "{\"id\":\"20261129_000000_00000_floci\"}"); + } + } + + private static void respond(HttpExchange exchange, int status, String body) throws IOException { + byte[] bytes = body.getBytes(UTF_8); + exchange.sendResponseHeaders(status, bytes.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(bytes); + } + } +} diff --git a/src/test/java/io/floci/aws/services/emr/EmrTrinoNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrTrinoNightlyIntegrationTest.java index ae5f3279ba..4927bb2f85 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrTrinoNightlyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrTrinoNightlyIntegrationTest.java @@ -66,7 +66,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; * {@code trino-node}, {@code trino-log} and {@code trino-env} reach Trino's node, log and environment, and its * {@code trino-exchange-manager} spools a fault-tolerant query in the cluster's HDFS. A * cluster with no step starts its Trino as it becomes ready, and a client outside the cluster queries it through Floci - * on the cluster's own host. + * on the cluster's own host. With {@code trino-password-authenticator}, Trino checks passwords against a file a + * bootstrap action wrote, over HTTPS alone. * *

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. @@ -81,6 +82,9 @@ 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"; + // A password file for Trino's file authenticator: alice, with the bcrypt of secret1, as htpasswd -B -C 10 makes it. + private static final String PASSWORDS = "alice:$2y$10$jagJOlWnBjOHXbOPrR0n1u3LRDLX366Y4C23mRGPOjsRHokxYgchi"; + private static final String PASSWORD_FILE = "/home/hadoop/trino/password.db"; @RegisterExtension final PartitionCleanup cleanup = new PartitionCleanup(); @@ -237,6 +241,40 @@ class EmrTrinoNightlyIntegrationTest { .statusCode(200).extract().jsonPath().getString("Cluster.Status.State")); } + // Trino taking passwords, as the Release Guide's LDAP page has it with trino-config and + // trino-password-authenticator, here from a password file a bootstrap action wrote, which Trino's container gets + // from the image the actions left. Trino takes a password only over HTTPS, which Floci's TLS passes on as + // X-Forwarded-Proto: a step asks it as Floci does, the right password let in, a wrong one refused; over plain HTTP + // Trino refuses either, through Floci's host for the cluster too. That it answers at all means it started with the + // shared secret Floci gives it, and was found ready without credentials. + @Test + @Timeout(value = 7, unit = TimeUnit.MINUTES) + void trinoPasswordAuthenticatorChecksAPasswordFileABootstrapActionWroteOverHttpsAlone() { + s3.putObject(request -> request.bucket(bucket).key("bootstrap/passwords.sh"), RequestBody.fromString( + "#!/bin/bash\nmkdir -p /home/hadoop/trino\necho '" + PASSWORDS + "' > " + PASSWORD_FILE + "\n")); + startCluster(""" + [{"Classification": "trino-config", "Properties": {"http-server.authentication.type": "PASSWORD"}}, + {"Classification": "trino-password-authenticator", + "Properties": {"password-authenticator.name": "file", "file.password-file": "%s"}}]""" + .formatted(PASSWORD_FILE), "[{\"Name\": \"passwords\", \"ScriptBootstrapAction\": {\"Path\": \"" + + s3Uri("bootstrap/passwords.sh") + "\"}}]"); + + String step = EmrRequests.addStep(clusterId, "passwords", "command-runner.jar", "bash", "-c", """ + statement="$FLOCI_TRINO_SERVER/v1/statement" + ask() { curl -s -o /dev/null -w '%{http_code}' -X POST -d 'SELECT 1' "$@" "$statement"; } + echo "right $(ask -H 'X-Forwarded-Proto: https' -u alice:secret1)" + echo "wrong $(ask -H 'X-Forwarded-Proto: https' -u alice:secret2)" + echo "plain $(ask -u alice:secret1)" + """); + + assertEquals("COMPLETED", state(step), () -> logs(step)); + String logs = logs(step); + assertTrue(logs.contains("right 200\nwrong 401\nplain 403"), logs); + String host = clusterId.toLowerCase(Locale.ROOT) + "." + EmrTrino.HOST_LABEL + ".localhost:" + RestAssured.port; + given().header("Host", host).auth().preemptive().basic("alice", "secret1").body("SELECT 1") + .post("/v1/statement").then().statusCode(403); + } + // 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) { @@ -249,11 +287,20 @@ class EmrTrinoNightlyIntegrationTest { } private void startCluster(String configurations) { + startCluster(configurations, null); + } + + // A cluster with Trino and configurations, and bootstrapActions unless that is null. + + private void startCluster(String configurations, String bootstrapActions) { 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)); + if (bootstrapActions != null) { + request.set("BootstrapActions", JSON.readTree(bootstrapActions)); + } } catch (IOException e) { throw new UncheckedIOException(e); } diff --git a/src/test/java/io/floci/aws/services/emr/EmrTrinoTest.java b/src/test/java/io/floci/aws/services/emr/EmrTrinoTest.java index e36f80014f..a633a62331 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrTrinoTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrTrinoTest.java @@ -16,6 +16,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -29,6 +30,9 @@ class EmrTrinoTest { private static final String ENDPOINT = "http://floci:4566"; private static final String SERVER = "http://ip-10-0-0-1.ec2.internal:8889"; + // The line of a shared secret the entrypoint makes: 32 random bytes in Base64. + private static final Pattern SHARED_SECRET = + Pattern.compile("internal-communication\\.shared-secret=[A-Za-z0-9+/]{43}=\n"); @Test void theImageIsOfTheTrinoTheReleaseShips() { @@ -145,8 +149,24 @@ class EmrTrinoTest { assertEquals(8890, EmrTrino.port(moved)); assertEquals(8889, EmrTrino.port(Map.of("http-server.http.port", "eighty"))); assertEquals("http://ip-10-0-0-1.ec2.internal:8890", EmrTrino.server("ip-10-0-0-1.ec2.internal", 8890)); - assertEquals(List.of("/usr/bin/trino", "--server", "localhost:8890", "--execute", "SELECT 1"), - EmrTrino.readyQuery(8890)); + // Its image's own health check, which asks the port config.properties names, without credentials. + assertEquals(List.of("/usr/lib/trino/bin/health-check"), EmrTrino.READY_CHECK); + } + + @Test + void theFilesAPasswordAuthenticatorNamesAreItsAbsolutePathsEachOnce() { + Map ldap = new LinkedHashMap<>(); + ldap.put("password-authenticator.name", "ldap"); + ldap.put("ldap.url", "ldaps://ldap.example.com:636"); + ldap.put("ldap.ssl.truststore.path", " /etc/trino/ldap-truststore.pem "); + ldap.put("ldap.ssl-trust-certificate", "/etc/trino/ldap-truststore.pem"); + ldap.put("ldap.ssl.keystore.path", "keys/ldap-key.pem"); + + // The key store's path is relative, and the trust store named twice is one file. + assertEquals(List.of("/etc/trino/ldap-truststore.pem"), EmrTrino.authenticatorFiles(ldap)); + assertEquals(List.of("/home/hadoop/password.db"), EmrTrino.authenticatorFiles(Map.of( + "password-authenticator.name", "file", "file.password-file", "/home/hadoop/password.db"))); + assertEquals(List.of(), EmrTrino.authenticatorFiles(Map.of())); } @Test @@ -203,7 +223,10 @@ class EmrTrinoTest { runEntrypoint(etc, environment); - assertEquals(config + "\n", Files.readString(etc.resolve("config.properties"))); + // A shared secret for Trino's internal communication after Floci's configuration, which EMR configures too. + String written = Files.readString(etc.resolve("config.properties")); + assertTrue(written.startsWith(config + "\n"), written); + assertTrue(SHARED_SECRET.matcher(written.substring(config.length() + 1)).matches(), written); try (Stream catalogs = Files.list(etc.resolve("catalog"))) { assertEquals(List.of("hive.properties", "iceberg.properties"), catalogs.map(path -> path.getFileName().toString()).sorted().toList()); @@ -226,8 +249,39 @@ class EmrTrinoTest { assertEquals("node.environment=docker\nnode.data-dir=/data/trino\n\nnode.id=coordinator-1\n", Files.readString(etc.resolve("node.properties"))); - // No trino-exchange-manager, no exchange manager. + // No trino-exchange-manager, no exchange manager, and no trino-password-authenticator, no password + // authenticator. assertFalse(Files.exists(etc.resolve("exchange-manager.properties"))); + assertFalse(Files.exists(etc.resolve("password-authenticator.properties"))); + } + + @Test + void aSharedSecretTheClusterGivesIsTrinosOwnElseTrinoGetsANewOneEachStart(@TempDir Path first, + @TempDir Path second) throws Exception { + // "you can override the configuration with your own secret key" + Path own = first.resolve("own"); + Files.createDirectories(own); + String config = EmrTrino.properties(EmrTrino.config(Map.of("internal-communication.shared-secret", "mine"))); + + runEntrypoint(own, Map.of(EmrTrino.CONFIG_VARIABLE, config)); + runEntrypoint(first, Map.of(EmrTrino.CONFIG_VARIABLE, "")); + runEntrypoint(second, Map.of(EmrTrino.CONFIG_VARIABLE, "")); + + assertEquals(config + "\n", Files.readString(own.resolve("config.properties"))); + String once = Files.readString(first.resolve("config.properties")); + String again = Files.readString(second.resolve("config.properties")); + assertTrue(SHARED_SECRET.matcher(once.substring(1)).matches(), once); + assertTrue(SHARED_SECRET.matcher(again.substring(1)).matches(), again); + assertFalse(once.equals(again), once); + } + + @Test + void theEntrypointWritesThePasswordAuthenticatorTheClusterGives(@TempDir Path etc) throws Exception { + String authenticator = "password-authenticator.name=file\nfile.password-file=/home/hadoop/password.db"; + + runEntrypoint(etc, Map.of(EmrTrino.PASSWORD_AUTHENTICATOR_VARIABLE, authenticator)); + + assertEquals(authenticator + "\n", Files.readString(etc.resolve("password-authenticator.properties"))); } @Test @@ -248,13 +302,17 @@ class EmrTrinoTest { // trino.image may name an image whose files differ from the Trino project's. Files.writeString(etc.resolve("node.properties"), "node.environment=staging\nnode.data-dir=/var/lib/trino"); Files.writeString(etc.resolve("log.properties"), "io.trino=WARN\n"); + Files.writeString(etc.resolve("password-authenticator.properties"), "password-authenticator.name=ldap\n"); - runEntrypoint(etc, Map.of(EmrTrino.NODE_VARIABLE, "", EmrTrino.LOG_VARIABLE, "")); + runEntrypoint(etc, Map.of(EmrTrino.NODE_VARIABLE, "", EmrTrino.LOG_VARIABLE, "", + EmrTrino.PASSWORD_AUTHENTICATOR_VARIABLE, "")); // Its last line had no newline of its own. assertEquals("node.environment=staging\nnode.data-dir=/var/lib/trino\nnode.id=ip-10-0-0-1-ec2-internal\n", Files.readString(etc.resolve("node.properties"))); assertEquals("io.trino=WARN\n", Files.readString(etc.resolve("log.properties"))); + assertEquals("password-authenticator.name=ldap\n", + Files.readString(etc.resolve("password-authenticator.properties"))); } // Runs the Trino container's entrypoint with environment, over an /etc/trino here as the Trino project's image