diff --git a/docs/services/emr.md b/docs/services/emr.md index 1735f1fa84..0fb165a4d5 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -869,6 +869,9 @@ holding the driver and its executors, or a command or a script. The cluster itse `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 + reads each into its memory, so one larger than the `trino.memory-mb` its container gets, or than the Docker host's + memory where a `trino.memory-mb` of 0 sets no limit, is refused, and Trino does not start, before Floci reads any of + 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 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 index ff0ac773b2..6f17d1c95f 100644 --- a/src/main/java/io/floci/aws/core/common/docker/ContainerFiles.java +++ b/src/main/java/io/floci/aws/core/common/docker/ContainerFiles.java @@ -4,18 +4,26 @@ 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 org.jboss.logging.Logger; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; 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. + * sends a path as a tar whose first entry is the path itself. It is read into memory, or copied into another + * container without being held there. */ public final class ContainerFiles { + private static final Logger LOG = Logger.getLogger(ContainerFiles.class); + private static final String SPOOL_PREFIX = "floci-container-file"; + private ContainerFiles() { } @@ -38,4 +46,59 @@ public final class ContainerFiles { + e.getMessage(), e); } } + + /** + * Copies the file at {@code path}, an absolute one, in container {@code from} to the same path in container + * {@code to}, the folders it is in made where missing, with {@code mode}. Whether {@code from} held a file there; + * where it holds none, nothing is copied. A file of more than {@code maxBytes} is refused, by the size its archive + * gives before any of it is read, so neither memory nor disk holds it. The file goes through a temporary file of + * this process's, readable by it alone, so no more of it is in memory than a copy's buffer, and the two requests to + * Docker run one after the other, as a pool of one connection lets them. + */ + public static boolean copy(DockerClient docker, String from, String path, String to, int mode, long maxBytes) { + return copy(docker, from, path, to, mode, maxBytes, null); + } + + // As copy above, its temporary file in spoolFolder, or in the default temporary folder where that is null. + static boolean copy(DockerClient docker, String from, String path, String to, int mode, long maxBytes, + Path spoolFolder) { + Path spool; + try { + spool = spoolFolder == null ? Files.createTempFile(SPOOL_PREFIX, null) + : Files.createTempFile(spoolFolder, SPOOL_PREFIX, null); + } catch (IOException e) { + throw new UncheckedIOException("Could not make a file to copy " + path + " through: " + e.getMessage(), e); + } + try { + try (InputStream archive = docker.copyArchiveFromContainerCmd(from, path).exec(); + TarArchiveInputStream entries = new TarArchiveInputStream(archive)) { + TarArchiveEntry entry = entries.getNextEntry(); + if (entry == null || !entry.isFile()) { + return false; + } + if (entry.getSize() > maxBytes) { + throw new IllegalArgumentException(path + " in container " + from + " is " + entry.getSize() + + " bytes, more than the " + maxBytes + " it may be"); + } + // Into the file made for it, which keeps the owner-only permissions it was made with. + try (OutputStream out = Files.newOutputStream(spool)) { + entries.transferTo(out); + } + } catch (NotFoundException expected) { + // Docker's answer for a path the container does not hold: no file there to copy. + return false; + } + RetryingTarCopier.copyFile(docker, to, "/", path.substring(1), spool, mode); + return true; + } catch (IOException e) { + throw new UncheckedIOException("Could not copy " + path + " from container " + from + ": " + + e.getMessage(), e); + } finally { + try { + Files.deleteIfExists(spool); + } catch (IOException e) { + LOG.warnv("Could not remove {0}, a copy of {1}: {2}", spool, path, e.getMessage()); + } + } + } } 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 717d88e8bb..9a671d54f9 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java +++ b/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java @@ -21,7 +21,6 @@ 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; @@ -1636,7 +1635,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { lifecycleManager.createAndStart(spec.build()); } else { lifecycleManager.createAndStart(spec.build(), container -> copyAuthenticatorFiles(clusterId, - accountId, region, container, trino.bootstrapImage(), files)); + accountId, region, container, trino.bootstrapImage(), files, trino.memoryMb())); } } catch (RuntimeException e) { releaseSession(name); @@ -1653,17 +1652,31 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // 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. + // own image, and Trino says so where neither holds it. Each goes through a temporary file, never held in Floci's + // memory, as the cluster makes it as large as it likes (ContainerFiles.copy), but none larger than the memory + // Trino's container gets (trinoMemoryBytes): Trino reads the password file and the key and trust stores into its + // memory, so a larger one could never serve it, and it is refused before Floci reads any of it, failing Trino's + // start. 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) { + String image, List files, int memoryMb) { DockerClient docker = lifecycleManager.getDockerClient(); String source = docker.createContainerCmd(image) .withLabels(labels(clusterId, accountId, region, EmrTrino.COMPONENT)).exec().getId(); try { + long maxBytes = trinoMemoryBytes(docker, memoryMb); for (String file : files) { - ContainerFiles.read(docker, source, file).ifPresent(content -> - RetryingTarCopier.copyBytes(docker, container, "/", file.substring(1), content, 0644)); + boolean copied; + try { + copied = ContainerFiles.copy(docker, source, file, container, 0644, maxBytes); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("The Trino of EMR cluster " + clusterId + " cannot read " + file + + " into the memory its container gets (trino.memory-mb): " + e.getMessage(), e); + } + if (!copied) { + LOG.infov("The image the bootstrap actions of EMR cluster {0} left holds no {1}, which its" + + " password authenticator names: Trino's own image may", clusterId, file); + } } } finally { try { @@ -1675,6 +1688,16 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { } } + // The memory Trino's container gets: memoryMb, or, where that is not positive and its container has no limit, the + // Docker host's, all of which it then has; none where Docker does not say how much that is. + private static long trinoMemoryBytes(DockerClient docker, int memoryMb) { + if (memoryMb > 0) { + return memoryMb * 1024L * 1024L; + } + Long host = docker.infoCmd().exec().getMemTotal(); + return host != null && host > 0 ? host : 0; + } + // 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) { 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 index 0c5e957b36..00aa649612 100644 --- a/src/test/java/io/floci/aws/core/common/docker/ContainerFilesTest.java +++ b/src/test/java/io/floci/aws/core/common/docker/ContainerFilesTest.java @@ -2,22 +2,36 @@ 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.command.CopyArchiveToContainerCmd; import com.github.dockerjava.api.exception.NotFoundException; 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.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; +import java.util.ArrayList; +import java.util.List; import java.util.Optional; +import java.util.Set; +import java.util.stream.Stream; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.RETURNS_SELF; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -69,6 +83,118 @@ class ContainerFilesTest { assertTrue(failure.getMessage().contains("connection reset"), failure.getMessage()); } + @Test + void aFileIsCopiedToTheSamePathInAnotherContainerWithTheModeGiven() throws IOException { + archives("/etc/app/settings.conf", tar("settings.conf", "name=value\n")); + List copied = copiedInto("c-2"); + + assertTrue(ContainerFiles.copy(docker, "c-1", "/etc/app/settings.conf", "c-2", 0644, 1024)); + + assertEquals(1, copied.size()); + try (TarArchiveInputStream entries = new TarArchiveInputStream(new ByteArrayInputStream(copied.get(0)))) { + TarArchiveEntry entry = entries.getNextEntry(); + assertEquals("etc/app/settings.conf", entry.getName()); + assertEquals(0644, entry.getMode() & 0777); + assertEquals("name=value\n", new String(entries.readAllBytes(), UTF_8)); + assertNull(entries.getNextEntry()); + } + } + + @Test + void aPathTheContainerDoesNotHoldCopiesNothing() 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); + List copied = copiedInto("c-2"); + + assertFalse(ContainerFiles.copy(docker, "c-1", "/etc/missing", "c-2", 0644, 1024)); + + assertEquals(List.of(), copied); + } + + @Test + void aCopyHasReadTheWholeFileBeforeItSendsItSoOneDockerConnectionServesBoth() throws IOException { + // The order of the two requests: the source's archive closed, then the copy into the other container. + List events = new ArrayList<>(); + byte[] archive = tar("settings.conf", "name=value\n"); + CopyArchiveFromContainerCmd read = mock(CopyArchiveFromContainerCmd.class); + // Closed by the tar reader and by its own try, so recorded the first time alone. + when(read.exec()).thenAnswer(reading -> new ByteArrayInputStream(archive) { + @Override + public void close() throws IOException { + if (!events.contains("read")) { + events.add("read"); + } + super.close(); + } + }); + when(docker.copyArchiveFromContainerCmd("c-1", "/etc/app/settings.conf")).thenReturn(read); + CopyArchiveToContainerCmd copy = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF); + when(copy.withTarInputStream(any())).thenAnswer(streaming -> { + events.add("sent"); + streaming.getArgument(0).readAllBytes(); + return copy; + }); + when(docker.copyArchiveToContainerCmd("c-2")).thenReturn(copy); + + assertTrue(ContainerFiles.copy(docker, "c-1", "/etc/app/settings.conf", "c-2", 0644, 1024)); + + assertEquals(List.of("read", "sent"), events); + } + + @Test + void aFileLargerThanTheCopyTakesIsRefusedBeforeAnyOfItIsWritten(@TempDir Path spool) throws IOException { + archives("/etc/app/settings.conf", tar("settings.conf", "name=value\n")); + List copied = copiedInto("c-2"); + + IllegalArgumentException refused = assertThrows(IllegalArgumentException.class, () -> ContainerFiles.copy( + docker, "c-1", "/etc/app/settings.conf", "c-2", 0644, 4, spool)); + + assertEquals("/etc/app/settings.conf in container c-1 is 11 bytes, more than the 4 it may be", + refused.getMessage()); + assertEquals(List.of(), copied); + try (Stream left = Files.list(spool)) { + assertEquals(List.of(), left.toList()); + } + } + + @Test + void theFileACopyGoesThroughIsReadableByThisProcessAloneAndGoesWithIt(@TempDir Path spool) throws IOException { + archives("/etc/app/settings.conf", tar("settings.conf", "name=value\n")); + List> seen = new ArrayList<>(); + CopyArchiveToContainerCmd copy = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF); + when(copy.withTarInputStream(any())).thenAnswer(streaming -> { + try (Stream files = Files.list(spool)) { + for (Path file : files.toList()) { + seen.add(Files.getPosixFilePermissions(file)); + } + } + streaming.getArgument(0).readAllBytes(); + return copy; + }); + when(docker.copyArchiveToContainerCmd("c-2")).thenReturn(copy); + + assertTrue(ContainerFiles.copy(docker, "c-1", "/etc/app/settings.conf", "c-2", 0644, 1024, spool)); + + // Owner-only while it holds the file, which may be a password file or a private key, and gone after. + assertEquals(List.of(Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)), seen); + try (Stream left = Files.list(spool)) { + assertEquals(List.of(), left.toList()); + } + } + + // What each archive copied into container holds, read as Docker would read it while it streams. + private List copiedInto(String container) { + List copied = new ArrayList<>(); + CopyArchiveToContainerCmd copy = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF); + when(copy.withTarInputStream(any())).thenAnswer(streaming -> { + copied.add(streaming.getArgument(0).readAllBytes()); + return copy; + }); + when(docker.copyArchiveToContainerCmd(container)).thenReturn(copy); + return copied; + } + private void archives(String path, byte[] tar) { CopyArchiveFromContainerCmd copy = mock(CopyArchiveFromContainerCmd.class); when(copy.exec()).thenAnswer(reading -> new ByteArrayInputStream(tar)); 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 e02810e266..0e9a2800b9 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java @@ -6,6 +6,7 @@ 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.InfoCmd; import com.github.dockerjava.api.command.InspectContainerCmd; import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.command.InspectNetworkCmd; @@ -24,6 +25,7 @@ import com.github.dockerjava.api.model.ContainerHostConfig; import com.github.dockerjava.api.model.ContainerNetwork; import com.github.dockerjava.api.model.ContainerNetworkSettings; import com.github.dockerjava.api.model.HostConfig; +import com.github.dockerjava.api.model.Info; import com.github.dockerjava.api.model.Network; import com.github.dockerjava.api.model.NetworkSettings; import io.floci.aws.config.EmulatorConfig; @@ -65,6 +67,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; import java.util.ArrayList; +import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -2105,6 +2108,92 @@ class EmrClusterStorageTest { @Test void theFilesTrinosPasswordAuthenticatorNamesComeFromTheBootstrapImageBeforeItStarts() throws IOException { + BootstrapImageStubs image = trinoCopiesFromTheBootstrapImage(); + // It holds the trust store the cluster's bootstrap actions wrote, and no key store. + 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); + // Each archive as Docker would read it, while it streams. + List archives = new ArrayList<>(); + when(copy.withTarInputStream(any())).thenAnswer(streaming -> { + archives.add(streaming.getArgument(0).readAllBytes()); + return copy; + }); + when(docker.copyArchiveToContainerCmd("t-1")).thenReturn(copy); + + ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", ldapMetastore(2048), null, + NOT_STOPPED); + + assertEquals(List.of("t-1"), image.copiedBeforeStart()); + // The cluster's Trino's labels, so that a sweep finds it with that Trino. + verify(image.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 the image does not hold is left to Trino's + // image, nothing copied for it. + verify(copy).withRemotePath("/"); + assertEquals(1, archives.size()); + try (TarArchiveInputStream entries = new TarArchiveInputStream(new ByteArrayInputStream(archives.get(0)))) { + 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(image.remove()).exec(); + } + + @Test + void anAuthenticatorFileLargerThanTrinosMemoryFailsItsStartWithNoneOfItRead() { + BootstrapImageStubs image = trinoCopiesFromTheBootstrapImage(); + // A trust store of 3 GB, as its archive's header says before any of it comes, where Trino's container gets + // 2048 MB, which Trino would read it into. + CopyArchiveFromContainerCmd truststore = mock(CopyArchiveFromContainerCmd.class); + when(truststore.exec()).thenAnswer(reading -> new ByteArrayInputStream(headerOnly("truststore.pem", 3L << 30))); + 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")); + + IllegalArgumentException refused = assertThrows(IllegalArgumentException.class, () -> ticking.hdfs("j-1", + "123456789012", "us-east-1", HOST, IMAGE, "floci-network", ldapMetastore(2048), null, NOT_STOPPED)); + + assertEquals("The Trino of EMR cluster j-1 cannot read /home/hadoop/ldap/truststore.pem into the memory its" + + " container gets (trino.memory-mb): /home/hadoop/ldap/truststore.pem in container source-1 is" + + " 3221225472 bytes, more than the 2147483648 it may be", refused.getMessage()); + verify(docker, never()).copyArchiveToContainerCmd("t-1"); + verify(image.remove()).exec(); + } + + @Test + void whereTrinosContainerHasNoMemoryLimitItsFilesAreBoundByTheDockerHostsMemory() { + BootstrapImageStubs image = trinoCopiesFromTheBootstrapImage(); + CopyArchiveFromContainerCmd truststore = mock(CopyArchiveFromContainerCmd.class); + when(truststore.exec()).thenAnswer(reading -> new ByteArrayInputStream(headerOnly("truststore.pem", 64))); + 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")); + // A memory of 0 sets no limit, so the container has the host's, 32 bytes here. + InfoCmd info = mock(InfoCmd.class); + Info host = mock(Info.class); + when(host.getMemTotal()).thenReturn(32L); + when(info.exec()).thenReturn(host); + when(docker.infoCmd()).thenReturn(info); + + IllegalArgumentException refused = assertThrows(IllegalArgumentException.class, () -> ticking.hdfs("j-1", + "123456789012", "us-east-1", HOST, IMAGE, "floci-network", ldapMetastore(0), null, NOT_STOPPED)); + + assertTrue(refused.getMessage().endsWith("is 64 bytes, more than the 32 it may be"), refused.getMessage()); + verify(docker, never()).copyArchiveToContainerCmd("t-1"); + verify(image.remove()).exec(); + } + + // Trino started with the files its password authenticator names copied in first, from the image the cluster's + // bootstrap actions left, sha256:bootstrapped, read in a container made from it, source-1. + private BootstrapImageStubs trinoCopiesFromTheBootstrapImage() { 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<>(); @@ -2114,51 +2203,40 @@ class EmrClusterStorageTest { 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); + return new BootstrapImageStubs(create, remove, copiedBeforeStart); + } + + private record BootstrapImageStubs(CreateContainerCmd create, RemoveContainerCmd remove, + List copiedBeforeStart) { + } + + // A cluster whose Trino, its container given memoryMb, has an LDAP authenticator naming a trust store and a key + // store, from its bootstrap image. + private static ClusterStorage.HiveMetastore ldapMetastore(int memoryMb) { 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(), + return new ClusterStorage.HiveMetastore("arn:aws:iam::123456789012:role/r", Map.of(), + new ClusterStorage.Trino("trinodb/trino:446", memoryMb, 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(); + // An archive whose one file's header says it is size bytes, with none of its content after it. + private static byte[] headerOnly(String name, long size) { + TarArchiveEntry entry = new TarArchiveEntry(name); + entry.setSize(size); + byte[] header = new byte[512]; + entry.writeEntryHeader(header); + return Arrays.copyOf(header, 512 * 3); } @Test