feat(emr): give each docker cluster a real HDFS on its primary node (#7496)

Every EMR cluster runs HDFS: its primary node "also runs the HDFS
NameNode service". In the docker runner mode a cluster's HDFS was a
folder of its /mnt volume behind a view of the hdfs scheme, so an
hdfs:// path naming a host was not served, hadoop fs -ls / failed, and
Hive, which looks up the encryption zone of any hdfs:// path, reached it
under viewfs, where a table at an hdfs:// location failed. Each cluster
now runs a NameNode and a DataNode.

- EmrClusterStorage starts them in a container of their own, from the
  release's EMR Serverless Hive image, which has HDFS's daemons where
  the release's image has only the client. It runs as root only to add
  the primary node's name to its hosts file and give its data volume to
  the hadoop user, then runs both daemons as that user, with one copy of
  each block and permissions off, and makes /tmp and /user/hadoop once
  the DataNode has joined. The data is in a volume of its own, so the
  first container to mount the cluster's /mnt volume is still a step's,
  which fills it with what the bootstrap actions left there. It is on a
  Docker network of the cluster's own, which only the cluster's steps
  join besides theirs, as its HDFS serves its files to any client that
  reaches it, so another cluster's steps, another account's too, do not.
- The AWS runtime for Apache Spark's releases, emr-spark-8.0.0 on,
  publish no Hive image, so their clusters run HDFS from emr-7.5.0's.
  Hadoop keeps its client-server protocols compatible across a major
  version's minor releases, so their newer client reaches its NameNode.
- A step's thread starts it after the cluster's volumes, from the id
  its image's pull, when it is missing, resolves, and waits up to two
  minutes from then, the
  NameNode on its port its own, the DataNode joined and the NameNode out
  of safe mode, as the NameNode's JMX says; a step that comes while
  it starts waits, and one that finds it running uses it. A failure
  fails the step ("The step could not start: ..."), and one whose
  container Docker cannot tell the state of leaves it as it is.
- The daemons log their warnings and errors to the container's output.
- When either daemon exits, the container ends and its readiness goes,
  so the next step starts it again on the data its volume keeps; one
  that finds it about to stop starts it again once.
- Steps reach it by the primary instance's PrivateDnsName, as
  ListInstances gives it, on port 8020: their containers resolve that
  name to the HDFS container's address, and fs.defaultFS names it, so
  hdfs:// paths without a host and paths without a scheme lead there.
  ListInstances numbers the MASTER group's instance first, so the name
  holds while other groups resize.
  In a namespace the steps share, the host's or another container's,
  which the HDFS container joins too, they reach it on its loopback, and
  its daemons listen there only, so no other interface serves its files,
  which any client could change; one cluster's HDFS runs there at a
  time, another's refused while it does. One a process with another
  docker-network left running, in another namespace than the steps', is
  started again in theirs on its data. With none, steps have no network,
  so the cluster runs no HDFS.
- Hadoop's local job runner copies a job's -files to
  /tmp/hadoop/mapred/staging on the local file system, then looks for
  them at that path of the default file system, as JobResourceUploader
  drops the folder's scheme. So in the hadoop command's configuration,
  which a custom JAR's MapReduce in the driver reads too, the hdfs
  scheme is a view of the cluster's HDFS in which that one folder is
  the container's own. Spark and Hive keep HDFS's own client, as Hive
  casts an hdfs:// file system to it to look up its encryption zone,
  so a Spark step writes a Hive table in HDFS too.
- A reset or a shutdown removes the HDFS containers this process
  started, found running or kept from an earlier process, after the
  drivers that use them are stopped, and a step or a bootstrap handed to
  its thread before it, however it then ends, starts no HDFS, driver or
  successor after it but is left as one whose driver was stopped, and
  none is handed to a thread until the reset is over; a container Docker
  refuses to remove stays known for the next; a cluster's next step
  starts its HDFS again on the data its volume keeps. The container and
  its network go with the cluster's storage, and the startup sweep
  removes those of clusters that are gone or have ended.

Every cluster now needs a Hive image, so the documentation of
image-template and hive-image-template says a mirror sets both.

The Docker-gated tests now cover a Hive table at an hdfs:// location, a
bootstrap action's file in /mnt, a structured streaming query keeping
its checkpoints in HDFS, a Spark step writing a Hive table there, hadoop
fs -ls /, and a DataNode that exits, after which the next step reads an
earlier step's file. The CI prefetch queues the Hive image for
EmrDockerRunnerDockerIntegrationTest's shard too.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-04 21:50:36 -06:00
1 parent a5291ca192
commit 3a64d2b761
23 files changed
+2300 -166

No files matched your search

@@ -1,8 +1,10 @@
package io.github.hectorvent.floci.core.common;
import jakarta.enterprise.inject.Instance;
import org.jboss.logging.Logger;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -16,11 +18,37 @@ import java.util.stream.IntStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ContainerTeardownsTest {
private static final Logger LOG = Logger.getLogger(ContainerTeardownsTest.class);
@Test
void stopAllRunsATeardownWhoseContainersOthersUseAfterTheirs() {
List<String> stopped = new ArrayList<>();
ContainerTeardown storage = new ContainerTeardown() {
@Override
public void stopManagedContainers() {
stopped.add("storage");
}
@Override
public int teardownOrder() {
return 1;
}
};
ContainerTeardown drivers = () -> stopped.add("drivers");
@SuppressWarnings("unchecked")
Instance<ContainerTeardown> teardowns = mock(Instance.class);
when(teardowns.iterator()).thenAnswer(invocation -> List.of(storage, drivers).iterator());
ContainerTeardowns.stopAll(teardowns, LOG);
assertEquals(List.of("drivers", "storage"), stopped);
}
@Test
void admitsEveryOwnedStopBeforeWaitingForOtherContainers() throws Exception {
List<Integer> resources = IntStream.range(0, 83).boxed().toList();
@@ -5,15 +5,20 @@ import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.ConnectToNetworkCmd;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.CreateNetworkCmd;
import com.github.dockerjava.api.command.DisconnectFromNetworkCmd;
import com.github.dockerjava.api.command.InspectContainerCmd;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.command.InspectNetworkCmd;
import com.github.dockerjava.api.command.RemoveContainerCmd;
import com.github.dockerjava.api.command.RemoveNetworkCmd;
import com.github.dockerjava.api.command.StartContainerCmd;
import com.github.dockerjava.api.exception.ConflictException;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.ContainerNetwork;
import com.github.dockerjava.api.model.ExposedPort;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.Network;
import com.github.dockerjava.api.model.NetworkSettings;
import com.github.dockerjava.api.model.Ports;
import io.github.hectorvent.floci.config.EmulatorConfig;
@@ -36,10 +41,12 @@ import java.util.Map;
import java.util.Optional;
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.ArgumentMatchers.argThat;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
@@ -415,6 +422,59 @@ class ContainerLifecycleManagerNetworkTest {
return hostConfig.getValue();
}
@Test
void ensureNetworkMakesALabelledBridgeOnlyWhenDockerHasNoNetworkOfThatName() {
InspectNetworkCmd inspect = mock(InspectNetworkCmd.class, RETURNS_SELF);
when(dockerClient.inspectNetworkCmd()).thenReturn(inspect);
when(inspect.exec()).thenThrow(new NotFoundException("missing"));
CreateNetworkCmd create = mock(CreateNetworkCmd.class, RETURNS_SELF);
when(dockerClient.createNetworkCmd()).thenReturn(create);
manager().ensureNetwork("emr-j-1-hdfs", Map.of("io.floci.service", "emr"));
verify(inspect).withNetworkId("emr-j-1-hdfs");
verify(create).withName("emr-j-1-hdfs");
verify(create).withDriver("bridge");
verify(create).withLabels(argThat(labels -> "emr".equals(labels.get("io.floci.service"))
&& "true".equals(labels.get("floci"))));
verify(create).exec();
}
@Test
void ensureNetworkUsesANetworkThatExistsAsItIs() {
InspectNetworkCmd inspect = mock(InspectNetworkCmd.class, RETURNS_SELF);
when(dockerClient.inspectNetworkCmd()).thenReturn(inspect);
when(inspect.exec()).thenReturn(new Network());
manager().ensureNetwork("emr-j-1-hdfs", Map.of());
verify(dockerClient, never()).createNetworkCmd();
}
@Test
void connectToNetworkJoinsACreatedContainerToTheNetwork() {
manager().connectToNetwork("container-id", "emr-j-1-hdfs");
verify(connectCmd).withContainerId("container-id");
verify(connectCmd).withNetworkId("emr-j-1-hdfs");
verify(connectCmd).exec();
}
@Test
void removeNetworkSaysWhetherTheNetworkIsGone() {
when(dockerClient.removeNetworkCmd("removed")).thenReturn(mock(RemoveNetworkCmd.class));
RemoveNetworkCmd missing = mock(RemoveNetworkCmd.class);
when(dockerClient.removeNetworkCmd("missing")).thenReturn(missing);
when(missing.exec()).thenThrow(new NotFoundException("missing"));
RemoveNetworkCmd inUse = mock(RemoveNetworkCmd.class);
when(dockerClient.removeNetworkCmd("in-use")).thenReturn(inUse);
when(inUse.exec()).thenThrow(new ConflictException("network has active endpoints"));
assertTrue(manager().removeNetwork("removed"));
assertTrue(manager().removeNetwork("missing"));
assertFalse(manager().removeNetwork("in-use"));
}
private ContainerLifecycleManager manager() {
return new ContainerLifecycleManager(dockerClient, imageCacheService, containerDetector, config);
}
@@ -0,0 +1,939 @@
package io.github.hectorvent.floci.services.emr;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.ExecCreateCmd;
import com.github.dockerjava.api.command.InspectContainerCmd;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.command.InspectVolumeResponse;
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.exception.ConflictException;
import com.github.dockerjava.api.exception.DockerException;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.ContainerHostConfig;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.Network;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.EmulatorConfig.EcsServiceConfig.ImagePullBehavior;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerExecStubs;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLiveness;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.services.emrserverless.SparkJobRunner;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BooleanSupplier;
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.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** A cluster's storage: Docker volumes, and its HDFS in a container of its own, on its primary node. */
class EmrClusterStorageTest {
private static final String IMAGE = "public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest";
private static final String HOST = "ip-10-0-0-1.ec2.internal";
private static final String READY = "test -f /tmp/floci-hdfs-ready";
private static final BooleanSupplier NOT_STOPPED = () -> false;
private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
private final DockerClient docker = mock(DockerClient.class);
private final ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
private final ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
private final ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
private final EmrClusterStorage storage = new EmrClusterStorage(lifecycle, containerBuilder, config);
private final String hdfsName = ContainerStorageHelper.dockerName(config, "emr-j-1-hdfs");
@BeforeEach
void docker() {
when(lifecycle.getDockerClient()).thenReturn(docker);
when(containerBuilder.resolveDockerNetwork(Optional.of("floci-network")))
.thenReturn(Optional.of("floci-network"));
when(containerBuilder.newContainer(IMAGE)).thenReturn(spec);
when(containerBuilder.resolveImage(IMAGE)).thenReturn(IMAGE);
when(lifecycle.resolveImageForLaunch(IMAGE, ImagePullBehavior.PREFER_CACHED, null))
.thenReturn(new ImageCacheService.LaunchImage(IMAGE, null));
when(spec.build()).thenReturn(new ContainerSpec(IMAGE));
// No other cluster's HDFS runs.
ListContainersCmd running = mock(ListContainersCmd.class, RETURNS_SELF);
when(docker.listContainersCmd()).thenReturn(running);
when(running.exec()).thenReturn(List.of());
}
@Test
void aClustersHdfsStartsAsRootFromTheReleasesImageOnAVolumeOfItsOwnAndAnswersAtItsAddressOnceReady() {
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-1", Map.of()));
when(lifecycle.probeContainer("c-1")).thenReturn(ContainerLiveness.RUNNING);
when(lifecycle.resolveContainerNetworkIp("c-1", hdfsName)).thenReturn("172.18.0.5");
// Not ready the first time it is looked at, then ready.
List<List<String>> looks = ContainerExecStubs.completeEveryExec(docker, "c-1", List.of(1L, 0L), "", "");
SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", NOT_STOPPED);
SparkJobRunner.Storage volumes = storage.volumes("j-1");
assertEquals(new SparkJobRunner.Storage(volumes.home(), volumes.mnt(), HOST, "172.18.0.5", hdfsName), started);
verify(spec).withName(hdfsName);
verify(spec).withUser("root");
verify(spec).withEnv("FLOCI_HDFS_HOST", HOST);
verify(spec).withEnv("FLOCI_HDFS_BIND", "0.0.0.0");
// Not the cluster's /mnt volume, which Docker fills from the image of the first container to mount it: a
// step's, so what the bootstrap left there comes with it.
verify(spec).withNamedVolume(hdfsName, "/mnt");
verify(lifecycle).ensureVolume(eq(hdfsName), argThat(labels ->
"emr-storage".equals(labels.get(ContainerStorageHelper.COMPONENT_LABEL))
&& "j-1".equals(labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL))));
// On a network of the cluster's own, which only its steps join, not the one they run on, where other
// clusters' steps would reach it.
verify(lifecycle).ensureNetwork(eq(hdfsName), argThat(labels ->
"emr-hdfs".equals(labels.get(ContainerStorageHelper.COMPONENT_LABEL))
&& "j-1".equals(labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL))));
verify(spec).withDockerNetwork(Optional.of(hdfsName));
verify(spec).withLabels(argThat(labels -> "emr-hdfs".equals(labels.get(ContainerStorageHelper.COMPONENT_LABEL))
&& "j-1".equals(labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL))));
// Its host name leads to the container's own address, where the DataNode registers, unless it listens on one
// address only, which its name then leads to.
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).startsWith(String.join("\n",
"address=$FLOCI_HDFS_BIND; [ \"$address\" != 0.0.0.0 ] || address=$(hostname -i | awk '{print $1}')",
"echo \"$address $FLOCI_HDFS_HOST\" >> /etc/hosts || exit\n"))));
// Every one of its daemons' listeners is on that address.
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(String.join(" ",
"\"<property><name>dfs.namenode.rpc-bind-host</name><value>$FLOCI_HDFS_BIND</value></property>\"",
"\"<property><name>dfs.namenode.http-address</name><value>$FLOCI_HDFS_BIND:9870</value></property>\"",
"\"<property><name>dfs.datanode.address</name><value>$FLOCI_HDFS_BIND:9866</value></property>\"",
"\"<property><name>dfs.datanode.http.address</name><value>$FLOCI_HDFS_BIND:9864</value></property>\"",
"\"<property><name>dfs.datanode.ipc.address</name>"
+ "<value>$FLOCI_HDFS_BIND:9867</value></property>\""))));
assertEquals(List.of(List.of(READY.split(" ")), List.of(READY.split(" "))), looks);
// Its daemons' warnings and errors in the container's output.
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(
"printf '%s\\n' 'log4j.rootLogger=WARN,console'"
+ " 'log4j.appender.console=org.apache.log4j.ConsoleAppender'")));
// The NameNode answering on its port is its own, the one its format gave the ClusterId, not another
// cluster's sharing its namespace.
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(String.join(" ",
"cid=$(sed -n \"s/^clusterID=//p\" /mnt/namenode/current/VERSION); hdfs namenode & hdfs datanode &",
"until curl -sf -m 5 \"http://127.0.0.1:9870/jmx?qry=Hadoop:service=NameNode,name=NameNodeInfo\"",
"| grep -q \"\\\"ClusterId\\\" : \\\"$cid\\\"\"; do",
"[ \"$(jobs -rp | wc -l)\" = 2 ] || exit 1; sleep 0.2; done;"))));
// The image is there before the start's deadline.
verify(lifecycle).resolveImageForLaunch(IMAGE, ImagePullBehavior.PREFER_CACHED, null);
// Ready once the DataNode has joined and the NameNode has left safe mode, as its JMX says; a daemon that
// exits ends it.
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(String.join(" ",
"until curl -sf -m 5 \"http://127.0.0.1:9870/jmx?qry=Hadoop:service=NameNode,name=FSNamesystemState\"",
"| grep -q \"\\\"NumLiveDataNodes\\\" : 1,\"; do",
"[ \"$(jobs -rp | wc -l)\" = 2 ] || exit 1; sleep 0.2; done;",
"until curl -sf -m 5 \"http://127.0.0.1:9870/jmx?qry=Hadoop:service=NameNode,name=NameNodeInfo\"",
"| grep -q \"\\\"Safemode\\\" : \\\"\\\"\"; do",
"[ \"$(jobs -rp | wc -l)\" = 2 ] || exit 1; sleep 0.2; done;",
"hdfs dfs -mkdir -p /tmp /user/hadoop || exit 1;",
"touch /tmp/floci-hdfs-ready;",
"wait -n; rm -f /tmp/floci-hdfs-ready; kill $(jobs -rp) 2>/dev/null; exit 1'"))));
// One left stopped by a restart goes first.
InOrder order = inOrder(lifecycle);
order.verify(lifecycle).removeIfExistsStrict(hdfsName);
order.verify(lifecycle).ensureVolume(eq(hdfsName), any());
order.verify(lifecycle).ensureNetwork(eq(hdfsName), any());
order.verify(lifecycle).createAndStart(any());
}
@Test
void onTheHostsNetworkAStepReachesItsClustersHdfsAtTheHostsLoopback() {
when(containerBuilder.resolveDockerNetwork(Optional.of("host"))).thenReturn(Optional.of("host"));
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING);
runningOn(hdfsName, "host");
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"host", NOT_STOPPED);
assertEquals("127.0.0.1", started.hdfsAddress());
// Steps share the host's network with it, so they join no other.
assertNull(started.hdfsNetwork());
verify(lifecycle, never()).createAndStart(any());
}
@Test
void onTheHostsNetworkAClustersHdfsListensOnlyOnTheHostsLoopback() {
when(containerBuilder.resolveDockerNetwork(Optional.of("host"))).thenReturn(Optional.of("host"));
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-1", Map.of()));
when(lifecycle.probeContainer("c-1")).thenReturn(ContainerLiveness.RUNNING);
ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", NOT_STOPPED);
// The host's other interfaces would otherwise serve its files, without permissions, to anyone reaching them.
verify(spec).withEnv("FLOCI_HDFS_BIND", "127.0.0.1");
verify(spec).withDockerNetwork(Optional.of("host"));
verify(lifecycle, never()).ensureNetwork(anyString(), any());
}
@Test
void inAContainersNamespaceItsClustersHdfsSharesItAndListensOnItsLoopback() {
when(containerBuilder.resolveDockerNetwork(Optional.empty())).thenReturn(Optional.of("container:floci"));
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-2", Map.of()));
when(lifecycle.probeContainer("c-2")).thenReturn(ContainerLiveness.RUNNING);
ContainerExecStubs.completeEveryExec(docker, "c-2", 0L, "", "");
SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, null,
NOT_STOPPED);
// Docker joins a container placed in another's namespace to no other network, so its steps reach it there.
assertEquals("127.0.0.1", started.hdfsAddress());
assertNull(started.hdfsNetwork());
verify(spec).withDockerNetwork(Optional.of("container:floci"));
verify(spec).withEnv("FLOCI_HDFS_BIND", "127.0.0.1");
verify(lifecycle, never()).ensureNetwork(anyString(), any());
}
@Test
void aClustersHdfsStartsFromTheImageIdItsPullResolvedWhichAnotherPullCannotMove() {
String id = "sha256:" + "a".repeat(64);
when(lifecycle.resolveImageForLaunch(IMAGE, ImagePullBehavior.PREFER_CACHED, null))
.thenReturn(new ImageCacheService.LaunchImage(id, null));
when(containerBuilder.newContainer(id)).thenReturn(spec);
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-1", Map.of()));
when(lifecycle.probeContainer("c-1")).thenReturn(ContainerLiveness.RUNNING);
when(lifecycle.resolveContainerNetworkIp("c-1", hdfsName)).thenReturn("172.18.0.5");
ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED);
verify(containerBuilder).newContainer(id);
verify(containerBuilder, never()).newContainer(IMAGE);
}
@Test
void anHdfsAnotherDockerNetworkLeftRunningStartsAgainInTheStepsNamespaceOnItsData() {
// A process on the cluster's own network left it there, running and ready; this one's steps run on the host's.
when(containerBuilder.resolveDockerNetwork(Optional.of("host"))).thenReturn(Optional.of("host"));
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING);
runningOn(hdfsName, hdfsName);
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-1", Map.of()));
when(lifecycle.probeContainer("c-1")).thenReturn(ContainerLiveness.RUNNING);
ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", "");
assertEquals("127.0.0.1", storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host",
NOT_STOPPED).hdfsAddress());
verify(lifecycle).removeIfExistsStrict(hdfsName);
verify(lifecycle).createAndStart(any());
verify(spec).withDockerNetwork(Optional.of("host"));
verify(spec).withNamedVolume(hdfsName, "/mnt");
}
@Test
void twoClustersStartingTheirHdfsOnTheHostsNetworkAtOnceStartOneOfThem() throws Exception {
when(containerBuilder.resolveDockerNetwork(Optional.of("host"))).thenReturn(Optional.of("host"));
String secondName = ContainerStorageHelper.dockerName(config, "emr-j-2-hdfs");
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
when(lifecycle.probeContainer(secondName)).thenReturn(ContainerLiveness.NOT_RUNNING);
// Once the first cluster's HDFS is created it is running, on the host's network.
List<Container> running = new CopyOnWriteArrayList<>();
ListContainersCmd list = mock(ListContainersCmd.class, RETURNS_SELF);
when(docker.listContainersCmd()).thenReturn(list);
when(list.exec()).thenAnswer(listing -> List.copyOf(running));
Container first = hdfsContainer("c-1", "j-1");
ContainerHostConfig hostNetwork = mock(ContainerHostConfig.class);
when(hostNetwork.getNetworkMode()).thenReturn("host");
when(first.getHostConfig()).thenReturn(hostNetwork);
when(lifecycle.createAndStart(any())).thenAnswer(creating -> {
running.add(first);
return new ContainerLifecycleManager.ContainerInfo("c-1", Map.of());
});
when(lifecycle.probeContainer("c-1")).thenReturn(ContainerLiveness.RUNNING);
ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", "");
// The first's start, past its look for another cluster's, waits until the second has looked too, or waits
// for it to look.
AtomicReference<Thread> second = new AtomicReference<>();
CountDownLatch firstLooked = new CountDownLatch(1);
ExecutorService steps = Executors.newFixedThreadPool(2);
try {
doAnswer(volume -> {
firstLooked.countDown();
awaitBlockedOrDone(second);
return null;
}).when(lifecycle).ensureVolume(eq(hdfsName), any());
Future<SparkJobRunner.Storage> starting = steps.submit(
() -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", NOT_STOPPED));
assertTrue(firstLooked.await(10, TimeUnit.SECONDS));
Future<SparkJobRunner.Storage> waiting = steps.submit(() -> {
second.set(Thread.currentThread());
return storage.hdfs("j-2", "123456789012", "us-east-1", HOST, IMAGE, "host", NOT_STOPPED);
});
assertEquals("127.0.0.1", starting.get(10, TimeUnit.SECONDS).hdfsAddress());
ExecutionException refused = assertThrows(ExecutionException.class,
() -> waiting.get(10, TimeUnit.SECONDS));
assertEquals("The HDFS of EMR cluster j-2 cannot start while that of EMR cluster j-1 runs in the network"
+ " namespace they share", refused.getCause().getMessage());
verify(lifecycle, times(1)).createAndStart(any());
} finally {
steps.shutdownNow();
}
}
@Test
void anotherClustersHdfsOnItsOwnNetworkDoesNotKeepOneFromStartingOnTheHosts() {
when(containerBuilder.resolveDockerNetwork(Optional.of("host"))).thenReturn(Optional.of("host"));
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
ListContainersCmd running = mock(ListContainersCmd.class, RETURNS_SELF);
when(docker.listContainersCmd()).thenReturn(running);
Container bridged = hdfsContainer("c-other", "j-2");
ContainerHostConfig ownNetwork = mock(ContainerHostConfig.class);
when(ownNetwork.getNetworkMode()).thenReturn("emr-j-2-hdfs");
when(bridged.getHostConfig()).thenReturn(ownNetwork);
when(running.exec()).thenReturn(List.of(bridged));
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-1", Map.of()));
when(lifecycle.probeContainer("c-1")).thenReturn(ContainerLiveness.RUNNING);
ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", NOT_STOPPED);
verify(lifecycle).createAndStart(any());
}
@Test
void aStaleHdfsContainerDockerWillNotRemoveFailsTheStartAsSuch() {
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
doThrow(new IllegalStateException("Failed to remove stale container " + hdfsName))
.when(lifecycle).removeIfExistsStrict(hdfsName);
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED));
// Not a name clash on the create that follows.
assertEquals("Failed to remove stale container " + hdfsName, failure.getMessage());
verify(lifecycle, never()).createAndStart(any());
}
@Test
void aClustersHdfsWithNoAddressOnItsNetworkFailsTheStep() {
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-1", Map.of()));
when(lifecycle.probeContainer("c-1")).thenReturn(ContainerLiveness.RUNNING);
when(lifecycle.resolveContainerNetworkIp("c-1", hdfsName)).thenReturn("");
ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", "");
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED));
assertEquals("The HDFS of EMR cluster j-1 has no address on Docker network " + hdfsName,
failure.getMessage());
}
@Test
void aClustersHdfsThatRunsIsUsedAsItIs() {
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING);
when(lifecycle.resolveContainerNetworkIp(hdfsName, hdfsName)).thenReturn("172.18.0.6");
runningOn(hdfsName, hdfsName);
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
assertEquals("172.18.0.6", storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", NOT_STOPPED).hdfsAddress());
verify(lifecycle, never()).createAndStart(any());
verify(lifecycle, never()).removeIfExists(anyString());
verify(lifecycle, never()).removeIfExistsStrict(anyString());
}
@Test
void aClustersHdfsThatDockerCannotTellTheStateOfIsLeftAsItIs() {
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.UNKNOWN);
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED));
assertEquals("Could not tell whether the HDFS of EMR cluster j-1 runs", failure.getMessage());
verify(lifecycle, never()).removeIfExists(anyString());
verify(lifecycle, never()).removeIfExistsStrict(anyString());
verify(lifecycle, never()).createAndStart(any());
}
@Test
void aClustersHdfsFoundRunningThatStopsBeforeItIsReadyIsStartedAgainOnItsData() {
// Found running, then stopped, as a container whose daemon has just exited is.
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING, ContainerLiveness.NOT_RUNNING);
runningOn(hdfsName, hdfsName);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-7", Map.of()));
when(lifecycle.probeContainer("c-7")).thenReturn(ContainerLiveness.RUNNING);
when(lifecycle.resolveContainerNetworkIp("c-7", hdfsName)).thenReturn("172.18.0.8");
ContainerExecStubs.completeEveryExec(docker, "c-7", 0L, "", "");
assertEquals("172.18.0.8", storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", NOT_STOPPED).hdfsAddress());
InOrder order = inOrder(lifecycle);
order.verify(lifecycle).removeIfExistsStrict(hdfsName);
order.verify(lifecycle).createAndStart(any());
verify(spec).withNamedVolume(hdfsName, "/mnt");
}
@Test
void aClustersHdfsThatStopsBeforeItIsReadyFailsWithoutAnExecDockerWouldRefuse() {
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-3", Map.of()));
when(lifecycle.probeContainer("c-3")).thenReturn(ContainerLiveness.NOT_RUNNING);
List<List<String>> looks = ContainerExecStubs.completeEveryExec(docker, "c-3", 1L, "", "");
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED));
assertEquals("The HDFS of EMR cluster j-1 stopped before it was ready", failure.getMessage());
assertEquals(List.of(), looks);
}
@Test
void aClustersHdfsThatIsNotReadyInTimeFailsToStart() {
EmrClusterStorage impatient = new EmrClusterStorage(lifecycle, containerBuilder, config, Duration.ZERO,
System::nanoTime);
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-4", Map.of()));
when(lifecycle.probeContainer("c-4")).thenReturn(ContainerLiveness.RUNNING);
ContainerExecStubs.completeEveryExec(docker, "c-4", 1L, "", "");
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> impatient.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED));
assertEquals("The HDFS of EMR cluster j-1 did not start within 0 seconds", failure.getMessage());
}
@Test
void aStepWaitingWhileAnotherStartsItsClustersHdfsHasOnlyWhatIsLeftOfTheStartTimeout() throws Exception {
AtomicLong clock = new AtomicLong();
long timeout = Duration.ofMinutes(2).toNanos();
EmrClusterStorage timed = new EmrClusterStorage(lifecycle, containerBuilder, config, Duration.ofMinutes(2),
clock::get);
// The first step starts it; the second, which waited for it, finds it running.
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING, ContainerLiveness.RUNNING);
runningOn(hdfsName, hdfsName);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-6", Map.of()));
when(lifecycle.probeContainer("c-6")).thenReturn(ContainerLiveness.RUNNING);
ContainerExecStubs.completeEveryExec(docker, "c-6", 1L, "", "");
List<List<String>> secondLooks = ContainerExecStubs.completeEveryExec(docker, hdfsName, 1L, "", "");
CountDownLatch firstLooks = new CountDownLatch(1);
AtomicReference<Thread> second = new AtomicReference<>();
// The first step's look lasts until the second waits for it, and past the timeout.
onEachExec("c-6", () -> {
firstLooks.countDown();
awaitBlocked(second);
clock.addAndGet(timeout + 1);
});
// Each of the second's looks takes a minute, which would leave it time for another from a deadline of its own.
onEachExec(hdfsName, () -> clock.addAndGet(Duration.ofMinutes(1).toNanos()));
ExecutorService steps = Executors.newFixedThreadPool(2);
try {
Future<SparkJobRunner.Storage> first = steps.submit(
() -> timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED));
assertTrue(firstLooks.await(10, TimeUnit.SECONDS));
Future<SparkJobRunner.Storage> waiting = steps.submit(() -> {
second.set(Thread.currentThread());
return timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED);
});
assertThrows(ExecutionException.class, () -> first.get(10, TimeUnit.SECONDS));
ExecutionException failure = assertThrows(ExecutionException.class,
() -> waiting.get(10, TimeUnit.SECONDS));
assertEquals("The HDFS of EMR cluster j-1 did not start within 120 seconds",
failure.getCause().getMessage());
assertEquals(1, secondLooks.size());
} finally {
steps.shutdownNow();
}
}
@Test
void aStepWaitingForItsClustersHdfsThroughATeardownStopsAsItsDriverWouldAndStartsItNoMore() {
AtomicLong clock = new AtomicLong();
EmrClusterStorage timed = new EmrClusterStorage(lifecycle, containerBuilder, config, Duration.ofMinutes(2),
clock::get);
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-5", Map.of()));
when(lifecycle.probeContainer("c-5")).thenReturn(ContainerLiveness.RUNNING);
ContainerExecStubs.completeEveryExec(docker, "c-5", 1L, "", "");
// A reset or a shutdown tears it down while it is being looked at; each look takes a minute.
onEachExec("c-5", () -> {
timed.stopManagedContainers();
clock.addAndGet(Duration.ofMinutes(1).toNanos());
});
assertThrows(ClusterStorage.Stopped.class,
() -> timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED));
verify(lifecycle, times(1)).createAndStart(any());
// As it starts, one left from before goes, and the teardown removes it; the step does again, in case it
// started it after the teardown looked.
verify(lifecycle, times(3)).removeIfExistsStrict(hdfsName);
verify(lifecycle, never()).removeIfExists(anyString());
}
@Test
void aStepPastStartingStartsNoHdfsAndRemovesNone() {
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
assertThrows(ClusterStorage.Stopped.class,
() -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", () -> true));
verify(lifecycle, never()).createAndStart(any());
verify(lifecycle, never()).removeIfExists(anyString());
verify(lifecycle, never()).removeIfExistsStrict(anyString());
verify(lifecycle, never()).resolveImageForLaunch(anyString(), any(), any());
}
@Test
void theFirstPullOfItsImageIsNoPartOfTheHdfsStartTimeout() {
AtomicLong clock = new AtomicLong();
EmrClusterStorage timed = new EmrClusterStorage(lifecycle, containerBuilder, config, Duration.ofMinutes(2),
clock::get);
// The Hive image is not there yet, and its pull takes five minutes.
when(lifecycle.resolveImageForLaunch(IMAGE, ImagePullBehavior.PREFER_CACHED, null)).thenAnswer(pull -> {
clock.addAndGet(Duration.ofMinutes(5).toNanos());
return new ImageCacheService.LaunchImage(IMAGE, null);
});
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-4", Map.of()));
when(lifecycle.probeContainer("c-4")).thenReturn(ContainerLiveness.RUNNING);
when(lifecycle.resolveContainerNetworkIp("c-4", hdfsName)).thenReturn("172.18.0.11");
// Not ready the first time it is looked at, then ready.
ContainerExecStubs.completeEveryExec(docker, "c-4", List.of(1L, 0L), "", "");
assertEquals("172.18.0.11", timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network",
NOT_STOPPED).hdfsAddress());
}
@Test
void inANamespaceAnotherClustersHdfsRunsInItsClustersHdfsDoesNotStart() {
when(containerBuilder.resolveDockerNetwork(Optional.of("host"))).thenReturn(Optional.of("host"));
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
ListContainersCmd running = mock(ListContainersCmd.class, RETURNS_SELF);
when(docker.listContainersCmd()).thenReturn(running);
Container other = hdfsContainer("c-other", "j-2");
ContainerHostConfig hostNetwork = mock(ContainerHostConfig.class);
when(hostNetwork.getNetworkMode()).thenReturn("host");
when(other.getHostConfig()).thenReturn(hostNetwork);
when(running.exec()).thenReturn(List.of(other));
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", NOT_STOPPED));
// Its daemons, on the ports j-2's hold, would never bind, and j-2's would answer for them.
assertEquals("The HDFS of EMR cluster j-1 cannot start while that of EMR cluster j-2 runs in the network"
+ " namespace they share", failure.getMessage());
verify(running).withLabelFilter(argThat((Map<String, String> filter) ->
"emr-hdfs".equals(filter.get(ContainerStorageHelper.COMPONENT_LABEL))));
verify(lifecycle, never()).createAndStart(any());
}
@Test
void aStepCancelledWhileItsClustersHdfsStartsStopsAndLeavesItToTheClustersOtherSteps() {
AtomicBoolean cancelled = new AtomicBoolean();
AtomicLong clock = new AtomicLong();
EmrClusterStorage timed = new EmrClusterStorage(lifecycle, containerBuilder, config, Duration.ofMinutes(2),
clock::get);
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-8", Map.of()));
when(lifecycle.probeContainer("c-8")).thenReturn(ContainerLiveness.RUNNING);
ContainerExecStubs.completeEveryExec(docker, "c-8", 1L, "", "");
// The step is cancelled while its HDFS is looked at; each look takes a minute.
onEachExec("c-8", () -> {
cancelled.set(true);
clock.addAndGet(Duration.ofMinutes(1).toNanos());
});
assertThrows(ClusterStorage.Stopped.class,
() -> timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", cancelled::get));
// Only one left from before went, as it started; the one it started is the next step's.
verify(lifecycle, times(1)).removeIfExistsStrict(hdfsName);
}
@Test
void aClustersHdfsThatStopsWhileItsReadinessIsLookedAtIsStartedAgainOnItsData() {
// Found running, still running when looked at, then stopped, so Docker refuses the exec.
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING, ContainerLiveness.RUNNING,
ContainerLiveness.NOT_RUNNING);
runningOn(hdfsName, hdfsName);
when(docker.execCreateCmd(hdfsName)).thenThrow(new ConflictException("Container is not running"));
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-9", Map.of()));
when(lifecycle.probeContainer("c-9")).thenReturn(ContainerLiveness.RUNNING);
when(lifecycle.resolveContainerNetworkIp("c-9", hdfsName)).thenReturn("172.18.0.10");
ContainerExecStubs.completeEveryExec(docker, "c-9", 0L, "", "");
assertEquals("172.18.0.10", storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", NOT_STOPPED).hdfsAddress());
verify(lifecycle).createAndStart(any());
}
@Test
void aClustersHdfsWhoseReadinessDockerCannotLookAtWhileItRunsFailsTheStepAndIsLeftAsItIs() {
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING);
runningOn(hdfsName, hdfsName);
when(docker.execCreateCmd(hdfsName)).thenThrow(new DockerException("The daemon is busy", 500));
assertThrows(DockerException.class,
() -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED));
verify(lifecycle, never()).createAndStart(any());
verify(lifecycle, never()).removeIfExists(anyString());
verify(lifecycle, never()).removeIfExistsStrict(anyString());
}
@Test
void aClustersHdfsIsTornDownAfterTheDriversThatUseIt() {
ContainerTeardown drivers = () -> { };
assertTrue(storage.teardownOrder() > drivers.teardownOrder());
}
@Test
void aClustersStorageGoesWithItsHdfsFirstAsItHoldsTheVolumeOfItsData() {
SparkJobRunner.Storage volumes = storage.volumes("j-1");
when(lifecycle.removeVolume(anyString())).thenReturn(true);
when(lifecycle.removeNetwork(hdfsName)).thenReturn(true);
assertTrue(storage.remove("j-1"));
InOrder order = inOrder(lifecycle);
order.verify(lifecycle).removeIfExistsStrict(hdfsName);
order.verify(lifecycle).removeNetwork(hdfsName);
order.verify(lifecycle).removeVolume(hdfsName);
verify(lifecycle).removeVolume(volumes.home());
verify(lifecycle).removeVolume(volumes.mnt());
}
@Test
void aClustersStorageThatDockerKeepsAnyOfIsNotGone() {
when(lifecycle.removeVolume(anyString())).thenReturn(true);
when(lifecycle.removeNetwork(hdfsName)).thenReturn(true);
when(lifecycle.removeVolume(hdfsName)).thenReturn(false);
assertFalse(storage.remove("j-1"));
// Nor is one whose network Docker keeps.
when(lifecycle.removeVolume(hdfsName)).thenReturn(true);
when(lifecycle.removeNetwork(hdfsName)).thenReturn(false);
assertFalse(storage.remove("j-1"));
}
@Test
void aClustersStorageWhoseHdfsDockerKeepsIsNotGoneAndItsHdfsStaysKnown() {
when(lifecycle.removeVolume(anyString())).thenReturn(true);
when(lifecycle.removeNetwork(hdfsName)).thenReturn(true);
doThrow(new IllegalStateException("Failed to remove stale container " + hdfsName)).doNothing()
.when(lifecycle).removeIfExistsStrict(hdfsName);
// Known from a step's start.
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING);
when(lifecycle.resolveContainerNetworkIp(hdfsName, hdfsName)).thenReturn("172.18.0.9");
runningOn(hdfsName, hdfsName);
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED);
assertFalse(storage.remove("j-1"));
// The next reset or shutdown removes it.
storage.stopManagedContainers();
verify(lifecycle, times(2)).removeIfExistsStrict(hdfsName);
}
@Test
void withNoNetworkItsStepsRunWithoutAnHdfs() {
when(containerBuilder.resolveDockerNetwork(Optional.of("none"))).thenReturn(Optional.of("none"));
SparkJobRunner.Storage storageOnly = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "none",
NOT_STOPPED);
// Docker joins a container placed there to no network, the HDFS's included.
assertEquals(storage.volumes("j-1"), storageOnly);
verify(lifecycle, never()).resolveImageForLaunch(anyString(), any(), any());
verify(lifecycle, never()).createAndStart(any());
}
@Test
void anHdfsLeftInAnotherContainersNamespaceStartsAgainInTheStepsOne() {
when(containerBuilder.resolveDockerNetwork(Optional.of("container:b"))).thenReturn(Optional.of("container:b"));
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING);
runningOn(hdfsName, "container:a");
containerIdOf("a", "1111");
containerIdOf("b", "2222");
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-1", Map.of()));
when(lifecycle.probeContainer("c-1")).thenReturn(ContainerLiveness.RUNNING);
ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "container:b", NOT_STOPPED);
verify(lifecycle).createAndStart(any());
verify(spec).withDockerNetwork(Optional.of("container:b"));
}
@Test
void anHdfsInTheSameContainersNamespaceByItsIdIsUsedAsItIs() {
// Docker records the namespace's container by its id; the steps name it.
when(containerBuilder.resolveDockerNetwork(Optional.of("container:floci")))
.thenReturn(Optional.of("container:floci"));
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING);
runningOn(hdfsName, "container:3333");
containerIdOf("floci", "3333");
containerIdOf("3333", "3333");
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
assertEquals("127.0.0.1", storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "container:floci",
NOT_STOPPED).hdfsAddress());
verify(lifecycle, never()).createAndStart(any());
}
@Test
void anotherClustersHdfsInAnotherNamespaceDoesNotKeepOneFromStarting() {
when(containerBuilder.resolveDockerNetwork(Optional.of("container:b"))).thenReturn(Optional.of("container:b"));
containerIdOf("b", "2222");
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
ListContainersCmd running = mock(ListContainersCmd.class, RETURNS_SELF);
when(docker.listContainersCmd()).thenReturn(running);
Container onHost = hdfsContainer("c-other", "j-2");
ContainerHostConfig hostNetwork = mock(ContainerHostConfig.class);
when(hostNetwork.getNetworkMode()).thenReturn("host");
when(onHost.getHostConfig()).thenReturn(hostNetwork);
when(running.exec()).thenReturn(List.of(onHost));
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-1", Map.of()));
when(lifecycle.probeContainer("c-1")).thenReturn(ContainerLiveness.RUNNING);
ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "container:b", NOT_STOPPED);
verify(lifecycle).createAndStart(any());
}
@Test
void aResetOrAShutdownRemovesTheHdfsItFoundRunningAndKeepsTheVolumeOfItsData() {
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING);
when(lifecycle.resolveContainerNetworkIp(hdfsName, hdfsName)).thenReturn("172.18.0.9");
runningOn(hdfsName, hdfsName);
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED);
storage.stopManagedContainers();
storage.stopManagedContainers();
verify(lifecycle).removeIfExistsStrict(hdfsName);
verify(lifecycle, never()).removeVolume(anyString());
verify(lifecycle, never()).removeNetwork(anyString());
}
@Test
void anHdfsDockerKeptThroughATeardownIsRemovedByTheNext() {
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING);
when(lifecycle.resolveContainerNetworkIp(hdfsName, hdfsName)).thenReturn("172.18.0.9");
runningOn(hdfsName, hdfsName);
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED);
doThrow(new IllegalStateException("Failed to remove container " + hdfsName)).doNothing()
.when(lifecycle).removeIfExistsStrict(hdfsName);
storage.stopManagedContainers();
storage.stopManagedContainers();
storage.stopManagedContainers();
// Refused the first time, so still known; removed the second; not asked for again the third.
verify(lifecycle, times(2)).removeIfExistsStrict(hdfsName);
}
@Test
void aResetOrAShutdownAsksDockerNothingWhenNoClustersHdfsRuns() {
storage.stopManagedContainers();
verify(lifecycle, never()).getDockerClient();
verify(lifecycle, never()).removeIfExistsStrict(anyString());
}
@Test
void theHdfsOfClustersThatAreGoneOrHaveEndedGoesWithTheirStorage() {
ListContainersCmd list = mock(ListContainersCmd.class, RETURNS_SELF);
when(docker.listContainersCmd()).thenReturn(list);
Container kept = hdfsContainer("c-kept", "j-up");
Container gone = hdfsContainer("c-gone", "j-ended");
when(list.exec()).thenReturn(List.of(kept, gone));
ListNetworksCmd networks = mock(ListNetworksCmd.class, RETURNS_SELF);
when(docker.listNetworksCmd()).thenReturn(networks);
Network keptNetwork = hdfsNetwork("emr-j-up-hdfs", "j-up");
Network goneNetwork = hdfsNetwork("emr-j-ended-hdfs", "j-ended");
when(networks.exec()).thenReturn(List.of(keptNetwork, goneNetwork));
ListVolumesCmd volumes = mock(ListVolumesCmd.class, RETURNS_SELF);
when(docker.listVolumesCmd()).thenReturn(volumes);
when(volumes.exec()).thenReturn(mock(ListVolumesResponse.class));
storage.removeAllBut(Set.of("j-up"));
verify(list).withLabelFilter(argThat((Map<String, String> filter) ->
"emr-hdfs".equals(filter.get(ContainerStorageHelper.COMPONENT_LABEL))));
verify(lifecycle).removeIfExistsStrict(ContainerStorageHelper.dockerName(config, "emr-j-ended-hdfs"));
verify(lifecycle, never()).removeIfExists(anyString());
verify(networks).withFilter(eq("label"), argThat((List<String> filter) ->
filter.contains(ContainerStorageHelper.COMPONENT_LABEL + "=emr-hdfs")));
verify(lifecycle).removeNetwork("emr-j-ended-hdfs");
verify(lifecycle, never()).removeNetwork("emr-j-up-hdfs");
// The one kept, which an earlier process left, goes with the next reset or shutdown.
storage.stopManagedContainers();
verify(lifecycle).removeIfExistsStrict(ContainerStorageHelper.dockerName(config, "emr-j-up-hdfs"));
}
@Test
void anEndedClustersHdfsDockerKeepsThroughTheSweepIsRemovedByTheNextTeardown() {
String ended = ContainerStorageHelper.dockerName(config, "emr-j-ended-hdfs");
ListContainersCmd list = mock(ListContainersCmd.class, RETURNS_SELF);
when(docker.listContainersCmd()).thenReturn(list);
Container gone = hdfsContainer("c-gone", "j-ended");
when(list.exec()).thenReturn(List.of(gone));
ListNetworksCmd networks = mock(ListNetworksCmd.class, RETURNS_SELF);
when(docker.listNetworksCmd()).thenReturn(networks);
when(networks.exec()).thenReturn(List.of());
ListVolumesCmd volumes = mock(ListVolumesCmd.class, RETURNS_SELF);
when(docker.listVolumesCmd()).thenReturn(volumes);
when(volumes.exec()).thenReturn(mock(ListVolumesResponse.class));
doThrow(new IllegalStateException("Failed to remove stale container " + ended)).doNothing()
.when(lifecycle).removeIfExistsStrict(ended);
storage.removeAllBut(Set.of());
storage.stopManagedContainers();
storage.stopManagedContainers();
// Refused in the sweep, so still known; removed by the next teardown; not asked for again after.
verify(lifecycle, times(2)).removeIfExistsStrict(ended);
}
// The container name runs with networkMode as its network mode, as Docker inspects it.
private void runningOn(String name, String networkMode) {
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
InspectContainerResponse response = mock(InspectContainerResponse.class);
when(docker.inspectContainerCmd(name)).thenReturn(inspect);
when(inspect.exec()).thenReturn(response);
when(response.getHostConfig()).thenReturn(HostConfig.newHostConfig().withNetworkMode(networkMode));
}
// Docker inspects the container nameOrId as the one of id.
private void containerIdOf(String nameOrId, String id) {
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
InspectContainerResponse response = mock(InspectContainerResponse.class);
when(docker.inspectContainerCmd(nameOrId)).thenReturn(inspect);
when(inspect.exec()).thenReturn(response);
when(response.getId()).thenReturn(id);
}
// Runs hook as each exec into containerId is made, which then answers as its stubs say.
private void onEachExec(String containerId, Runnable hook) {
ExecCreateCmd stubbed = docker.execCreateCmd(containerId);
when(docker.execCreateCmd(containerId)).thenAnswer(invocation -> {
hook.run();
return stubbed;
});
}
// Waits until the thread of thread waits for a lock another holds, or has ended, or a second has passed.
private static void awaitBlockedOrDone(AtomicReference<Thread> thread) {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(1);
while (System.nanoTime() < deadline) {
Thread waiting = thread.get();
if (waiting != null && (waiting.getState() == Thread.State.BLOCKED
|| waiting.getState() == Thread.State.TERMINATED || waiting.getState() == Thread.State.WAITING)) {
return;
}
Thread.onSpinWait();
}
}
// Waits until the thread of thread waits for a lock another holds.
private static void awaitBlocked(AtomicReference<Thread> thread) {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
while (thread.get() == null || thread.get().getState() != Thread.State.BLOCKED) {
if (System.nanoTime() > deadline) {
throw new IllegalStateException("The second step never waited for the first");
}
Thread.onSpinWait();
}
}
@Test
void aSweepThatDockerRefusesTheNetworksOfStillRemovesTheVolumes() {
ListContainersCmd list = mock(ListContainersCmd.class, RETURNS_SELF);
when(docker.listContainersCmd()).thenReturn(list);
when(list.exec()).thenReturn(List.of());
ListNetworksCmd networks = mock(ListNetworksCmd.class, RETURNS_SELF);
when(docker.listNetworksCmd()).thenReturn(networks);
when(networks.exec()).thenThrow(new DockerException("The daemon is busy", 500));
ListVolumesCmd volumes = mock(ListVolumesCmd.class, RETURNS_SELF);
when(docker.listVolumesCmd()).thenReturn(volumes);
ListVolumesResponse response = mock(ListVolumesResponse.class);
InspectVolumeResponse ended = mock(InspectVolumeResponse.class);
when(ended.getName()).thenReturn("emr-j-ended-mnt");
when(ended.getLabels()).thenReturn(Map.of(ContainerStorageHelper.RESOURCE_ID_LABEL, "j-ended"));
when(response.getVolumes()).thenReturn(List.of(ended));
when(volumes.exec()).thenReturn(response);
storage.removeAllBut(Set.of("j-up"));
verify(lifecycle).removeVolume("emr-j-ended-mnt");
}
private static Network hdfsNetwork(String name, String clusterId) {
Network network = mock(Network.class);
when(network.getName()).thenReturn(name);
when(network.getLabels()).thenReturn(Map.of(ContainerStorageHelper.RESOURCE_ID_LABEL, clusterId));
return network;
}
private static Container hdfsContainer(String id, String clusterId) {
Container container = mock(Container.class);
when(container.getId()).thenReturn(id);
when(container.getLabels()).thenReturn(Map.of(ContainerStorageHelper.RESOURCE_ID_LABEL, clusterId));
return container;
}
}
@@ -2,6 +2,11 @@ package io.github.hectorvent.floci.services.emr;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerExec;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLiveness;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.RetryingTarCopier;
import io.github.hectorvent.floci.testing.AwsTestClients;
import io.github.hectorvent.floci.testing.ContainerDataPlaneProfile;
@@ -12,6 +17,7 @@ import io.github.hectorvent.floci.testing.S3TestClients;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.Response;
import jakarta.inject.Inject;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
import org.junit.jupiter.api.BeforeAll;
@@ -27,6 +33,7 @@ import software.amazon.awssdk.services.s3.model.S3Object;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
@@ -40,6 +47,7 @@ import static io.github.hectorvent.floci.testing.EmrServerlessRequests.awaitJobR
import static io.github.hectorvent.floci.testing.EmrServerlessRequests.createSparkApplication;
import static io.github.hectorvent.floci.testing.EmrServerlessRequests.deleteApplication;
import static io.github.hectorvent.floci.testing.EmrServerlessRequests.startJobRun;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
@@ -76,6 +84,12 @@ class EmrDockerRunnerDockerIntegrationTest {
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Inject
ContainerLifecycleManager lifecycle;
@Inject
EmulatorConfig config;
private S3Client s3;
private String bucket;
private String clusterId;
@@ -130,6 +144,56 @@ class EmrDockerRunnerDockerIntegrationTest {
s3.getObjectAsBytes(request -> request.bucket(bucket).key("copied/words.txt")).asUtf8String());
}
@Test
void aSparkStepKeepsAHiveTableAndAStreamingQuerysCheckpointsInTheClustersHdfsWhichListsFromItsRoot() {
put("side/stream.py", """
import sys
from pyspark.sql import SparkSession
spark = SparkSession.builder.enableHiveSupport().getOrCreate()
# Hive, which Spark writes the table through, looks up the HDFS encryption zone of its folder.
spark.sql("create table words (w string) stored as textfile location 'hdfs:///hive-format/words'")
spark.sql("insert into words values ('a'), ('b')")
spark.table("words").write.text("/stream/in")
query = spark.readStream.text("/stream/in").writeStream.format("parquet") \\
.option("checkpointLocation", "hdfs:///stream/checkpoint").option("path", "hdfs:///stream/out") \\
.trigger(availableNow=True).start()
query.awaitTermination()
rows = sorted(row.value for row in spark.read.parquet("/stream/out").collect())
spark.createDataFrame([(" ".join(rows),)], ["value"]).coalesce(1).write.text(sys.argv[1])
""");
startCluster("[]");
// The checkpoint and the sink are hdfs:// paths without a host, as the Management Guide's
// "hdfs:///path-to-data", which Hadoop's FileContext, behind Spark's default checkpoint manager, refuses.
assertEquals("COMPLETED", runStep("command-runner.jar", "spark-submit",
s3Uri("side/stream.py"), s3Uri("stream-out/")));
assertEquals("a b\n", partFiles("stream-out/"));
assertEquals("COMPLETED", runStep("command-runner.jar", "hadoop", "fs", "-test", "-e",
"/stream/checkpoint/offsets/0"));
assertEquals("COMPLETED", runStep("command-runner.jar", "hadoop", "fs", "-ls", "/"));
}
@Test
void aClustersHdfsWhoseDataNodeExitsStartsAgainOnItsDataForTheNextStep() {
startCluster("[]");
assertEquals("COMPLETED", runStep("command-runner.jar", "s3-dist-cp",
"--src", s3Uri("in/"), "--dest", "hdfs:///kept/"));
String hdfs = ContainerStorageHelper.dockerName(config, "emr-" + clusterId + "-hdfs");
// The DataNode exits, as one the kernel stops for memory does, and its container ends with it.
ContainerExec.run(lifecycle.getDockerClient(), hdfs,
new String[]{"pkill", "-f", "org.apache.hadoop.hdfs.server.datanode.DataNode"}, 10);
await("the HDFS container of " + clusterId + " to stop").atMost(Duration.ofMinutes(1))
.pollInterval(Duration.ofMillis(200))
.until(() -> lifecycle.probeContainer(hdfs) == ContainerLiveness.NOT_RUNNING);
// The next step starts it again on its volume, once the NameNode has left safe mode, with the file there.
assertEquals("COMPLETED", runStep("command-runner.jar", "s3-dist-cp",
"--src", "hdfs:///kept/", "--dest", s3Uri("kept/")));
assertEquals(WORDS,
s3.getObjectAsBytes(request -> request.bucket(bucket).key("kept/words.txt")).asUtf8String());
}
@Test
void aClustersSparkEnvExportReachesItsSparkStepsDriver() {
put("side/env.py", """
@@ -83,6 +83,8 @@ class EmrHiveStepsDockerIntegrationTest {
create external table kv (k string, v int)
row format delimited fields terminated by ',' location '${INPUT}';
create table scaled as select k, v * 10 as v from kv;
create table pinned (k string) location 'hdfs:///floci/pinned';
insert into pinned select k from kv;
""");
put("queries/report.q", """
insert overwrite directory '${OUTPUT}' row format delimited fields terminated by ','
@@ -101,6 +103,10 @@ class EmrHiveStepsDockerIntegrationTest {
String cat = addStep("command-runner.jar", "hadoop", "fs", "-cat", "hdfs:///user/hive/warehouse/scaled/*");
assertEquals("COMPLETED", state(cat));
assertEquals("a\u000110\nb\u000120\nc\u000130\n", stepLog(cat, "stdout.gz"));
// An hdfs:// location is the cluster's HDFS too, whose NameNode answers Hive's encryption zone lookups.
String pinned = addStep("command-runner.jar", "hadoop", "fs", "-cat", "hdfs:///floci/pinned/*");
assertEquals("COMPLETED", state(pinned));
assertEquals("a\nb\nc\n", stepLog(pinned, "stdout.gz"));
// The metastore is the cluster's own, a database in its /mnt.
assertEquals("COMPLETED", state(addStep("command-runner.jar", "test", "-d", "/mnt/var/lib/hive/metastore_db")));
}
@@ -136,17 +142,19 @@ class EmrHiveStepsDockerIntegrationTest {
@Test
void whatABootstrapInstalledIsThereForTheClustersHiveAndOtherSteps() {
// One action, as the Management Guide's "Run custom bootstrap actions" has them: a file in the hadoop user's
// home, and a command installed with sudo.
// home, one in /mnt, and a command installed with sudo.
put("bootstrap/install.sh", String.join("\n", "#!/bin/bash",
"echo bootstrapped > /home/hadoop/marker.txt",
"echo mounted > /mnt/marker.txt",
"printf '%s\\n' '#!/bin/bash' 'echo installed' | sudo tee /usr/local/bin/floci-probe > /dev/null",
"sudo chmod +x /usr/local/bin/floci-probe", ""));
startCluster(HIVE_AND_SPARK, "[]", s3Uri("bootstrap/install.sh"));
String query = addStep("command-runner.jar", "hive-script", "--run-hive-script", "--args",
"-e", "!cat /home/hadoop/marker.txt; !/usr/local/bin/floci-probe;");
"-e", "!cat /home/hadoop/marker.txt /mnt/marker.txt; !/usr/local/bin/floci-probe;");
assertEquals("COMPLETED", state(query));
assertTrue(stepLog(query, "stdout.gz").contains("bootstrapped\ninstalled\n"));
// The cluster's HDFS, started before the step, keeps its data in a volume of its own, not in /mnt's.
assertTrue(stepLog(query, "stdout.gz").contains("bootstrapped\nmounted\ninstalled\n"));
String probe = addStep("command-runner.jar", "floci-probe");
assertEquals("COMPLETED", state(probe));
assertEquals("installed\n", stepLog(probe, "stdout.gz"));
@@ -177,4 +177,52 @@ class EmrResizeIntegrationTest {
+ "{\"InstanceFleetId\":\"" + coreFleetId + "\",\"TargetOnDemandCapacity\":1}}")
.then().statusCode(400).body("__type", equalTo("InvalidRequestException"));
}
@Test
@Order(8)
void thePrimaryNodeKeepsItsIdAndAddressWhileAGroupListedBeforeItResizes() {
String id = emr("RunJobFlow", "{\"Name\":\"core-first\",\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true,"
+ "\"InstanceGroups\":[{\"InstanceRole\":\"CORE\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":2},"
+ "{\"InstanceRole\":\"MASTER\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1}]}}")
.then().statusCode(200).extract().path("JobFlowId");
String master = emr("ListInstanceGroups", "{\"ClusterId\":\"" + id + "\"}").jsonPath()
.getString("InstanceGroups.find { it.InstanceGroupType == 'MASTER' }.Id");
String core = emr("ListInstanceGroups", "{\"ClusterId\":\"" + id + "\"}").jsonPath()
.getString("InstanceGroups.find { it.InstanceGroupType == 'CORE' }.Id");
String primary = "Instances.find { it.InstanceGroupId == '" + master + "' }";
// Listed after the core group's two, numbered first, as DescribeCluster's MasterPublicDnsName names it.
emr("ListInstances", "{\"ClusterId\":\"" + id + "\"}").then().statusCode(200)
.body("Instances[2].InstanceGroupId", equalTo(master))
.body(primary + ".Ec2InstanceId", equalTo("i-00000000000000001"))
.body(primary + ".PrivateIpAddress", equalTo("10.0.0.1"));
emr("ModifyInstanceGroups", "{\"ClusterId\":\"" + id + "\",\"InstanceGroups\":["
+ "{\"InstanceGroupId\":\"" + core + "\",\"InstanceCount\":3}]}").then().statusCode(200);
emr("ListInstances", "{\"ClusterId\":\"" + id + "\"}").then().statusCode(200)
.body("Instances", hasSize(4))
.body(primary + ".Ec2InstanceId", equalTo("i-00000000000000001"))
.body(primary + ".PrivateDnsName", equalTo("ip-10-0-0-1.ec2.internal"))
.body("Instances.findAll { it.InstanceGroupId == '" + core + "' }.PrivateIpAddress",
equalTo(List.of("10.0.0.2", "10.0.0.3", "10.0.0.4")));
emr("DescribeCluster", "{\"ClusterId\":\"" + id + "\"}").then().statusCode(200)
.body("Cluster.MasterPublicDnsName", equalTo("ip-10-0-0-1.ec2.internal"));
emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + id + "\"]}").then().statusCode(200);
}
@Test
@Order(9)
void aSecondMasterGroupsInstanceIsNumberedAfterThePrimaryNodeAsAnyOtherGroupsIs() {
String id = emr("RunJobFlow", "{\"Name\":\"two-masters\",\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true,"
+ "\"InstanceGroups\":[{\"InstanceRole\":\"CORE\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1},"
+ "{\"InstanceRole\":\"MASTER\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1},"
+ "{\"InstanceRole\":\"MASTER\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1}]}}")
.then().statusCode(200).extract().path("JobFlowId");
emr("ListInstances", "{\"ClusterId\":\"" + id + "\"}").then().statusCode(200)
.body("Instances.Ec2InstanceId", equalTo(List.of("i-00000000000000002", "i-00000000000000001",
"i-00000000000000003")))
.body("Instances.PrivateIpAddress", equalTo(List.of("10.0.0.2", "10.0.0.1", "10.0.0.3")));
emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + id + "\"]}").then().statusCode(200);
}
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.emr;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.emr.model.EmrCluster;
import io.github.hectorvent.floci.services.emr.model.EmrInstanceGroup;
@@ -19,6 +20,7 @@ import org.mockito.InOrder;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -100,7 +102,7 @@ class EmrServiceContainerStepsTest {
assertNull(job.logFolder());
assertNull(job.cloudWatchLogs());
assertEquals(Map.of("PYSPARK_PYTHON", "/usr/bin/python3.11"), job.environment());
assertEquals(new SparkJobRunner.Storage(cluster.getId() + "-home", cluster.getId() + "-mnt"), job.storage());
assertEquals(hdfsStorage(cluster), job.storage());
assertEquals(List.of(cluster.getId()), fixture.clusterStorage.created);
}
@@ -315,6 +317,188 @@ class EmrServiceContainerStepsTest {
assertEquals("COMPLETED", service.describeStep(cluster.getId(), cluster.getSteps().get(0).getId()).getState());
}
@Test
void aStepStartsItsClustersHdfsOnItsPrimaryNodeFromTheReleasesHiveImage() {
EmrCluster requested = cluster("hdfs", true, sparkStep("report", "CONTINUE"), sparkStep("next", "CONTINUE"));
// ListInstances lists the core group's two instances before the master's, which it numbers first.
requested.setInstanceGroups(new ArrayList<>(List.of(group("CORE", 2), group("MASTER", 1))));
EmrCluster cluster = service.runJobFlow(requested, REGION);
fixture.runStepThread();
// The core group grows, which leaves the primary node as it is, and its HDFS's name with it.
String core = cluster.getInstanceGroups().get(0).getId();
service.modifyInstanceGroups(cluster.getId(), REGION,
List.of(new EmrService.InstanceGroupModification(core, 3, null)));
fixture.pass(Duration.ofMinutes(5));
assertEquals(3, service.listInstanceGroups(cluster.getId()).get(0).getRunningInstanceCount());
fixture.runStepThread();
List<String> started = Arrays.asList(cluster.getId(), "ip-10-0-0-1.ec2.internal",
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", null);
assertEquals(List.of(started, started), fixture.clusterStorage.hdfs);
assertEquals(new SparkJobRunner.Storage(cluster.getId() + "-home", cluster.getId() + "-mnt",
"ip-10-0-0-1.ec2.internal", EmrServiceFixture.RecordingStorage.HDFS_ADDRESS,
EmrServiceFixture.RecordingStorage.HDFS_NETWORK), runner.jobs.get(0).storage());
}
@Test
void aClusterOfTheAwsRuntimeForSparkWhichHasNoHiveImageRunsItsHdfsInTheHiveImageOfEmr750() {
EmrCluster requested = cluster("spark-runtime", true, sparkStep("report", "CONTINUE"));
requested.setReleaseLabel("emr-spark-8.0.0");
service.runJobFlow(requested, REGION);
EmrService templated = fixture.withHiveImageTemplate("registry.internal/emr-serverless/hive/%s:20250425");
EmrCluster mirrored = cluster("mirrored", true, sparkStep("report", "CONTINUE"));
mirrored.setReleaseLabel("emr-spark-8.1.0");
templated.runJobFlow(mirrored, REGION);
fixture.runStepThread();
fixture.runStepThread();
assertEquals(List.of("public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest",
"registry.internal/emr-serverless/hive/emr-7.5.0:20250425"),
fixture.clusterStorage.hdfs.stream().map(hdfs -> hdfs.get(2)).toList());
// Its steps still run in the release's own image.
SparkJobRunner.Job job = runner.jobs.get(0);
assertEquals("public.ecr.aws/emr-serverless/spark4/emr-spark-8.0.0:latest",
EmrServerlessSparkRunner.image(job.imageTemplate(), job.releaseLabel(), job.engine()));
}
@Test
void aClustersHdfsThatCannotStartFailsTheStep() {
fixture.clusterStorage.hdfsFailure = new IllegalStateException(
"The HDFS of EMR cluster j-1 did not start within 120 seconds");
EmrCluster cluster = service.runJobFlow(cluster("no-hdfs", true, sparkStep("report", "CONTINUE")), REGION);
fixture.runStepThread();
EmrStep failed = service.describeStep(cluster.getId(), cluster.getSteps().get(0).getId());
assertEquals("FAILED", failed.getState());
assertEquals("The step could not start: The HDFS of EMR cluster j-1 did not start within 120 seconds",
failed.getFailureMessage());
assertEquals(List.of(), runner.jobs);
}
@Test
void aStepWhoseHdfsATeardownStoppedBeforeItsDriverStartedIsLeftAsADriverFlociStoppedIs() {
// A reset's or a shutdown's teardown stops the HDFS the step was waiting for.
fixture.clusterStorage.hdfsFailure = new ClusterStorage.Stopped("Floci stopped the HDFS of EMR cluster j-1");
EmrCluster cluster = service.runJobFlow(
cluster("torn-down", true, sparkStep("cut", "CONTINUE"), sparkStep("next", "CONTINUE")), REGION);
String stepId = cluster.getSteps().get(0).getId();
fixture.runStepThread();
// Taking CONTINUE now would start the next step after the teardown has passed.
assertEquals("RUNNING", service.describeStep(cluster.getId(), stepId).getState());
assertEquals(0, fixture.stepThreadsWaiting());
assertEquals(List.of(), runner.jobs);
}
@Test
void aTeardownWhileAStepsHdfsStartsStopsTheStepBeforeItsDriverStarts() {
List<Boolean> stoppedAsHdfsStarts = new ArrayList<>();
fixture.clusterStorage.whileStartingHdfs = stopped -> {
stoppedAsHdfsStarts.add(stopped.getAsBoolean());
// A reset's or a shutdown's teardown begins as the HDFS starts, before the runner knows of the driver.
service.stopManagedContainers();
stoppedAsHdfsStarts.add(stopped.getAsBoolean());
};
EmrCluster cluster = service.runJobFlow(
cluster("torn-down", true, sparkStep("cut", "CONTINUE"), sparkStep("next", "CONTINUE")), REGION);
String stepId = cluster.getSteps().get(0).getId();
fixture.runStepThread();
assertEquals(List.of(false, true), stoppedAsHdfsStarts);
assertEquals(List.of(), runner.driversStarted);
assertEquals("RUNNING", service.describeStep(cluster.getId(), stepId).getState());
assertEquals(0, fixture.stepThreadsWaiting());
}
@Test
void aStepWhoseStartATeardownCutShortIsLeftAsADriverFlociStoppedIs() {
// The teardown removes the HDFS as it starts, which Docker then refuses to start.
fixture.clusterStorage.whileStartingHdfs = stopped -> service.stopManagedContainers();
fixture.clusterStorage.hdfsFailure = new IllegalStateException("No such container: emr-j-1-hdfs");
EmrCluster cluster = service.runJobFlow(
cluster("cut-short", true, sparkStep("cut", "CONTINUE"), sparkStep("next", "CONTINUE")), REGION);
String stepId = cluster.getSteps().get(0).getId();
fixture.runStepThread();
// Taking CONTINUE now would start the next step after the teardown has passed.
assertEquals("RUNNING", service.describeStep(cluster.getId(), stepId).getState());
assertEquals(0, fixture.stepThreadsWaiting());
}
@Test
void aStepWhoseThreadIsInterruptedAsItStartsIsLeftAsADriverFlociStoppedIs() {
// Floci's shutdown interrupts the step's thread while it waits for its HDFS.
fixture.clusterStorage.whileStartingHdfs = stopped -> Thread.currentThread().interrupt();
fixture.clusterStorage.hdfsFailure = new IllegalStateException(
"Stopped waiting for the HDFS of EMR cluster j-1");
EmrCluster cluster = service.runJobFlow(
cluster("interrupted", true, sparkStep("cut", "CONTINUE"), sparkStep("next", "CONTINUE")), REGION);
String stepId = cluster.getSteps().get(0).getId();
try {
fixture.runStepThread();
} finally {
Thread.interrupted();
}
assertEquals("RUNNING", service.describeStep(cluster.getId(), stepId).getState());
assertEquals(0, fixture.stepThreadsWaiting());
}
@Test
void aStepHandedToItsThreadBeforeATeardownStartsNoHdfsAndNoDriver() {
EmrCluster cluster = service.runJobFlow(
cluster("torn-down", true, sparkStep("cut", "CONTINUE"), sparkStep("next", "CONTINUE")), REGION);
String stepId = cluster.getSteps().get(0).getId();
service.stopManagedContainers();
fixture.runStepThread();
assertEquals(List.of(), fixture.clusterStorage.hdfs);
assertEquals(List.of(), runner.driversStarted);
assertEquals("RUNNING", service.describeStep(cluster.getId(), stepId).getState());
assertEquals(0, fixture.stepThreadsWaiting());
}
@Test
void aStepFlociDoesNotRunHandedOffBeforeATeardownEndsAsAStoppedDriverAndStartsNoOther() {
EmrStep pig = sparkStep("query", "CONTINUE");
pig.setArgs(List.of("pig-script", "--run-pig-script", "--args", "-f", "s3://bucket/query.pig"));
EmrCluster cluster = service.runJobFlow(cluster("pig", true, pig, sparkStep("next", "CONTINUE")), REGION);
service.stopManagedContainers();
fixture.runStepThread();
assertEquals("RUNNING", service.describeStep(cluster.getId(), cluster.getSteps().get(0).getId()).getState());
assertEquals(0, fixture.stepThreadsWaiting());
}
@Test
void aDriverThatEndsAfterATeardownBeganEndsAsAStoppedOneAndStartsNoOtherStep() {
// The driver exits on its own as the teardown begins, so its run says it ended.
runner.whileRunning = service::stopManagedContainers;
EmrCluster cluster = service.runJobFlow(
cluster("ending", true, sparkStep("cut", "CONTINUE"), sparkStep("next", "CONTINUE")), REGION);
fixture.runStepThread();
assertEquals("RUNNING", service.describeStep(cluster.getId(), cluster.getSteps().get(0).getId()).getState());
assertEquals(0, fixture.stepThreadsWaiting());
}
@Test
void theServicesTeardownRunsBeforeThoseThatStopContainers() {
ContainerTeardown drivers = () -> { };
assertTrue(service.teardownOrder() < drivers.teardownOrder());
}
@Test
void aStepFlociDoesNotRunFailsWithoutRunning() {
EmrStep pig = sparkStep("query", "CONTINUE");
@@ -342,7 +526,7 @@ class EmrServiceContainerStepsTest {
assertEquals("COMPLETED", service.describeStep(cluster.getId(), cluster.getSteps().get(0).getId()).getState());
SparkJobRunner.Job job = runner.jobs.get(0);
assertEquals(args, job.command());
assertEquals(new SparkJobRunner.Storage(cluster.getId() + "-home", cluster.getId() + "-mnt"), job.storage());
assertEquals(hdfsStorage(cluster), job.storage());
}
@Test
@@ -359,7 +543,7 @@ class EmrServiceContainerStepsTest {
assertEquals(List.of("s3-dist-cp", "--src=s3://bucket/logs/", "--dest=hdfs:///output"),
job.command().subList(3, job.command().size()));
assertEquals(List.of(), job.application());
assertEquals(new SparkJobRunner.Storage(cluster.getId() + "-home", cluster.getId() + "-mnt"), job.storage());
assertEquals(hdfsStorage(cluster), job.storage());
}
@Test
@@ -581,7 +765,7 @@ class EmrServiceContainerStepsTest {
"arn:aws:iam::" + ACCOUNT + ":role/emr-ec2", List.of(
new BootstrapRunner.Action("pandas", INSTALL, List.of("pandas", "2.2")),
new BootstrapRunner.Action("jars", "s3://bucket/bootstrap/jars.sh", List.of())),
"s3://logs/emr/" + cluster.getId() + "/node/i-00000000000000003/bootstrap-actions/"),
"s3://logs/emr/" + cluster.getId() + "/node/i-00000000000000001/bootstrap-actions/"),
bootstrap.bootstraps.get(0));
assertEquals("RUNNING", bootstrapping.service.describeCluster(cluster.getId()).getState());
assertEquals("RUNNING", bootstrapping.service.describeStep(cluster.getId(), stepId).getState());
@@ -640,7 +824,7 @@ class EmrServiceContainerStepsTest {
// Its cluster's Spark settings are not Hive's.
assertEquals(Map.of(), job.sparkDefaults());
assertEquals(Map.of("HADOOP_HEAPSIZE", "2048"), job.environment());
assertEquals(new SparkJobRunner.Storage(cluster.getId() + "-home", cluster.getId() + "-mnt"), job.storage());
assertEquals(hdfsStorage(cluster), job.storage());
assertEquals("s3://logs/emr/" + cluster.getId() + "/steps/" + stepId + "/", job.logFolder());
assertEquals(List.of(cluster.getId()), fixture.clusterStorage.created);
assertEquals("COMPLETED", service.describeStep(cluster.getId(), stepId).getState());
@@ -769,6 +953,62 @@ class EmrServiceContainerStepsTest {
});
}
@Test
void aBootstrapHandedOffBeforeATeardownLeavesItsClusterBootstrappingAndStartsNoStep() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
EmrCluster cluster = bootstrapping.service.runJobFlow(
bootstrapped(cluster("torn-down", true, sparkStep("report", "CONTINUE"))), REGION);
List<String> ran = new ArrayList<>();
bootstrap.whileRunning = () -> ran.add("actions");
bootstrapping.service.stopManagedContainers();
bootstrapping.runStepThread();
// Its actions' container would start after the bootstrap runner's teardown had passed.
assertEquals(List.of(), ran);
assertEquals("BOOTSTRAPPING", bootstrapping.service.describeCluster(cluster.getId()).getState());
assertEquals(0, bootstrapping.stepThreadsWaiting());
assertTrue(runner.jobs.isEmpty());
}
@Test
void aBootstrapThatEndsAfterATeardownBeganLeavesItsClusterBootstrappingAndStartsNoStep() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
EmrCluster cluster = bootstrapping.service.runJobFlow(
bootstrapped(cluster("ending", true, sparkStep("report", "CONTINUE"))), REGION);
// Its actions succeed as the teardown begins, so its run says it ended, with the image it committed.
bootstrap.whileRunning = bootstrapping.service::stopManagedContainers;
bootstrapping.runStepThread();
assertEquals("BOOTSTRAPPING", bootstrapping.service.describeCluster(cluster.getId()).getState());
assertEquals(0, bootstrapping.stepThreadsWaiting());
assertTrue(runner.jobs.isEmpty());
// No cluster starts from that image, so it goes.
assertEquals(List.of(IMAGE), bootstrap.removed);
}
@Test
void fromATeardownUntilItsResetIsOverNoStepOrBootstrapIsHandedToAThread() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
bootstrapping.service.stopManagedContainers();
// A cluster moved on after the teardowns, as a wakeup of a delayed one would.
EmrCluster stepping = bootstrapping.service.runJobFlow(
cluster("after", true, sparkStep("report", "CONTINUE")), REGION);
EmrCluster bootstrapped = bootstrapping.service.runJobFlow(
bootstrapped(cluster("bootstrapped-after", true, sparkStep("report", "CONTINUE"))), REGION);
assertEquals(0, bootstrapping.stepThreadsWaiting());
assertEquals("BOOTSTRAPPING", bootstrapping.service.describeCluster(bootstrapped.getId()).getState());
assertEquals("RUNNING", bootstrapping.service.describeStep(stepping.getId(),
stepping.getSteps().get(0).getId()).getState());
// Once the reset is over, they are again.
bootstrapping.service.afterReset();
bootstrapping.service.runJobFlow(cluster("reset-over", true, sparkStep("report", "CONTINUE")), REGION);
assertEquals(1, bootstrapping.stepThreadsWaiting());
}
@Test
void aClusterTerminatedWhileBootstrappingStopsItsBootstrapAndTheImageItLeftGoes() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
@@ -852,8 +1092,7 @@ class EmrServiceContainerStepsTest {
assertTrue(service.describeCluster(cluster.getId()).isStorageCreated());
fixture.runStepThread();
SparkJobRunner.Storage storage = new SparkJobRunner.Storage(cluster.getId() + "-home",
cluster.getId() + "-mnt");
SparkJobRunner.Storage storage = hdfsStorage(cluster);
assertEquals(List.of(storage, storage), runner.jobs.stream().map(SparkJobRunner.Job::storage).toList());
assertEquals(List.of(cluster.getId()), fixture.clusterStorage.removed);
assertFalse(service.describeCluster(cluster.getId()).isStorageCreated());
@@ -986,6 +1225,13 @@ class EmrServiceContainerStepsTest {
}
// A spark-submit step through command-runner.jar, written for a cluster with YARN.
// A cluster's storage as a step gets it, its HDFS on the primary node of a cluster with no instance groups.
private static SparkJobRunner.Storage hdfsStorage(EmrCluster cluster) {
return new SparkJobRunner.Storage(cluster.getId() + "-home", cluster.getId() + "-mnt",
"ip-10-0-0-1.ec2.internal", EmrServiceFixture.RecordingStorage.HDFS_ADDRESS,
EmrServiceFixture.RecordingStorage.HDFS_NETWORK);
}
// The AWS CLI's Hive step: command-runner.jar running hive-script with the step's arguments after its --args.
private static EmrStep hiveStep(String name, String... args) {
EmrStep step = new EmrStep();
@@ -15,9 +15,12 @@ import io.github.hectorvent.floci.testing.MutableClock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.ArgumentMatchers.anyString;
@@ -53,7 +56,16 @@ final class EmrServiceFixture {
* {@link #whileCreating} run as each is made.
*/
static final class RecordingStorage implements ClusterStorage {
// The address each cluster's HDFS answers at.
static final String HDFS_ADDRESS = "172.18.0.5";
// The Docker network of a cluster's own each cluster's HDFS is on.
static final String HDFS_NETWORK = "floci-aws-emr-hdfs";
final List<String> created = new ArrayList<>();
// Each HDFS started: its cluster, primary node's host name, image and Docker network.
final List<List<String>> hdfs = new ArrayList<>();
RuntimeException hdfsFailure;
// Runs as each HDFS starts, with what tells it the step is past starting.
Consumer<BooleanSupplier> whileStartingHdfs = stopped -> { };
final List<String> removed = new ArrayList<>();
final List<Set<String>> kept = new ArrayList<>();
boolean refuse;
@@ -70,6 +82,17 @@ final class EmrServiceFixture {
whileCreating.run();
}
@Override
public SparkJobRunner.Storage hdfs(String clusterId, String accountId, String region, String host,
String image, String dockerNetwork, BooleanSupplier stopped) {
hdfs.add(Arrays.asList(clusterId, host, image, dockerNetwork));
whileStartingHdfs.accept(stopped);
if (hdfsFailure != null) {
throw hdfsFailure;
}
return volumes(clusterId).withHdfs(host, HDFS_ADDRESS, HDFS_NETWORK);
}
@Override
public boolean remove(String clusterId) {
removed.add(clusterId);
@@ -80,8 +80,10 @@ import static org.mockito.Mockito.when;
class EmrServerlessSparkRunnerTest {
private static final String ENDPOINT = "http://floci:4566";
// A cluster's storage, its HDFS running on its primary node.
private static final SparkJobRunner.Storage STORAGE = new SparkJobRunner.Storage(
"floci-aws-emr-j-2AXXXXXXGAPLF-home", "floci-aws-emr-j-2AXXXXXXGAPLF-mnt");
"floci-aws-emr-j-2AXXXXXXGAPLF-home", "floci-aws-emr-j-2AXXXXXXGAPLF-mnt", "ip-10-0-0-1.ec2.internal",
"172.18.0.5", "floci-aws-emr-j-2AXXXXXXGAPLF-hdfs");
private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
private final ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
@@ -247,17 +249,14 @@ class EmrServerlessSparkRunnerTest {
}
@Test
void anEmrHiveStepsHiveReachesItsClustersHdfsAsViewfsAndKeepsItsMetastoreInItsMnt() {
void anEmrHiveStepsHiveReachesItsClustersHdfsAndKeepsItsMetastoreInItsMnt() {
List<String> arguments = EmrServerlessSparkRunner.hiveArguments(
hiveStep(List.of("--hiveconf", "hive.exec.reducers.max=8", "-f", "s3://bucket/queries/report.q")),
ENDPOINT);
int tez = arguments.indexOf("tez.am.client.am.port-range=40000-40100");
assertEquals(List.of(
"--hiveconf", "fs.defaultFS=hdfs:///",
"--hiveconf", "fs.hdfs.impl=org.apache.hadoop.fs.viewfs.ViewFileSystemOverloadScheme",
"--hiveconf", "fs.viewfs.mounttable.default.linkFallback=file:///mnt/hdfs",
"--hiveconf", "fs.defaultFS=viewfs:///",
"--hiveconf", "fs.defaultFS=hdfs://ip-10-0-0-1.ec2.internal:8020",
"--hiveconf", "hive.metastore.client.factory.class="
+ "org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClientFactory",
"--hiveconf", "javax.jdo.option.ConnectionURL="
@@ -331,8 +330,9 @@ class EmrServerlessSparkRunnerTest {
verify(lifecycle, never()).copyJavaTrustStore(anyString());
// The release's image is not in an ECR repository, so it is pulled once, as the container is created.
verify(lifecycle, never()).resolveImageForLaunch(anyString(), any(), any());
// An EMR Serverless run has no cluster, nor its storage.
// An EMR Serverless run has no cluster, nor its storage or network.
verify(spec, never()).withNamedVolume(anyString(), anyString());
verify(lifecycle, never()).connectToNetwork(anyString(), anyString());
}
@Test
@@ -562,7 +562,7 @@ class EmrServerlessSparkRunnerTest {
}
@Test
void aStepMountsItsClustersStorageWhoseHdfsIsWherePathsWithoutASchemeLead() {
void aStepMountsItsClustersStorageWhoseHdfsOnItsPrimaryNodeIsWherePathsWithoutASchemeLead() {
ContainerBuilder builder = mock(ContainerBuilder.class);
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(builder.newContainer(anyString())).thenReturn(spec);
@@ -573,12 +573,19 @@ class EmrServerlessSparkRunnerTest {
verify(spec).withNamedVolume(STORAGE.home(), "/home/hadoop");
verify(spec).withNamedVolume(STORAGE.mnt(), "/mnt");
// The primary node's name leads to its HDFS, as the cluster's DNS resolves it, on the cluster's own network,
// which the driver joins before it starts.
verify(spec).withExtraHost("ip-10-0-0-1.ec2.internal", "172.18.0.5");
InOrder order = inOrder(lifecycle);
order.verify(lifecycle).create(any());
order.verify(lifecycle).connectToNetwork("driver", "floci-aws-emr-j-2AXXXXXXGAPLF-hdfs");
order.verify(lifecycle).startCreated(eq("driver"), any());
// After Floci's S3 settings, before the cluster's spark-defaults, which win.
assertEquals("spark.hadoop.aws.region=eu-west-1", arguments.get(19));
// HDFS's own client, in place of the core-site.xml's view, which Hive in Spark could not write a table with.
assertEquals(List.of(
"--conf", "spark.hadoop.fs.defaultFS=hdfs:///",
"--conf", "spark.hadoop.fs.hdfs.impl=org.apache.hadoop.fs.viewfs.ViewFileSystemOverloadScheme",
"--conf", "spark.hadoop.fs.viewfs.mounttable.default.linkFallback=file:///mnt/hdfs",
"--conf", "spark.hadoop.fs.defaultFS=hdfs://ip-10-0-0-1.ec2.internal:8020",
"--conf", "spark.hadoop.fs.hdfs.impl=org.apache.hadoop.hdfs.DistributedFileSystem",
"--conf", "spark.sql.streaming.checkpointFileManagerClass="
+ "org.apache.spark.sql.execution.streaming.FileSystemBasedCheckpointFileManager",
"--conf", "spark.hadoop.fs.defaultFS=file:///",
@@ -596,14 +603,13 @@ class EmrServerlessSparkRunnerTest {
verify(spec).withNamedVolume(STORAGE.home(), "/home/hadoop");
verify(spec).withNamedVolume(STORAGE.mnt(), "/mnt");
verify(spec).withEnv(eq("FLOCI_HADOOP_SITE"), argThat(site -> site.endsWith(String.join("\n",
"<property><name>fs.defaultFS</name><value>hdfs:///</value></property>",
"<property><name>fs.hdfs.impl</name><value>org.apache.hadoop.fs.viewfs.ViewFileSystemOverloadScheme"
+ "</value></property>",
"<property><name>fs.viewfs.mounttable.default.linkFallback</name><value>file:///mnt/hdfs</value>"
+ "</property>"))));
verify(spec).withEnv(eq("FLOCI_HADOOP_SITE"), argThat(site -> site.contains(
"<property><name>fs.defaultFS</name><value>hdfs://ip-10-0-0-1.ec2.internal:8020</value></property>")
&& site.endsWith("<property><name>fs.viewfs.mounttable.ip-10-0-0-1.ec2.internal.linkFallback</name>"
+ "<value>hdfs://ip-10-0-0-1.ec2.internal:8020</value></property>")));
verify(spec).withEnv(eq("FLOCI_SPARK_DEFAULTS"), argThat(file -> file.contains(
"\nspark.hadoop.fs.defaultFS hdfs:///\n")));
"\nspark.hadoop.fs.defaultFS hdfs://ip-10-0-0-1.ec2.internal:8020\n")));
verify(spec).withExtraHost("ip-10-0-0-1.ec2.internal", "172.18.0.5");
// A copy of the Hadoop configuration a spark-env export of HADOOP_CONF_DIR names, else of the image's, links
// followed, its core-site.xml taking in the original's whole, whatever its XML, then the cluster's HDFS.
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(
@@ -640,11 +646,8 @@ class EmrServerlessSparkRunnerTest {
verify(spec).withEnv("FLOCI_MAPRED_SITE", "<property><name>mapreduce.framework.name</name><value>local"
+ "</value></property><property><name>mapreduce.jobtracker.staging.root.dir</name>"
+ "<value>/tmp/hadoop/mapred/staging</value></property>");
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(String.join("\n",
" site mapred-site.xml \"$FLOCI_MAPRED_SITE\"",
// The local job runner names a job's files by their path alone, which leads to the cluster's HDFS.
" mkdir -p \"/mnt/hdfs/tmp/hadoop/mapred/staging\" \"$(dirname /tmp/hadoop/mapred/staging)\"",
" ln -sfn \"/mnt/hdfs/tmp/hadoop/mapred/staging\" /tmp/hadoop/mapred/staging\n"))
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(
"\n site mapred-site.xml \"$FLOCI_MAPRED_SITE\"\n")
// MapReduce from Spark's shaded Hadoop client, and S3A's AWS SDK, in a MapReduce home of Floci's,
// which a command's own HADOOP_CLASSPATH does not take off the hadoop command's class path.
&& entrypoint.get(2).contains("\n mkdir -p \"$hadoop_conf\" /tmp/floci-bin /tmp/floci-mapreduce\n")
@@ -734,11 +737,15 @@ class EmrServerlessSparkRunnerTest {
"<property><name>aws.glue.endpoint</name><value>http://floci:4566</value></property>",
"<property><name>hive.metastore.glue.catalogid</name><value>123456789012</value></property>",
"<property><name>aws.region</name><value>eu-west-1</value></property>",
"<property><name>fs.defaultFS</name><value>hdfs:///</value></property>",
"<property><name>fs.defaultFS</name><value>hdfs://ip-10-0-0-1.ec2.internal:8020</value></property>",
"<property><name>fs.hdfs.impl</name><value>org.apache.hadoop.fs.viewfs.ViewFileSystemOverloadScheme"
+ "</value></property>",
"<property><name>fs.viewfs.mounttable.default.linkFallback</name><value>file:///mnt/hdfs</value>"
+ "</property>",
"<property><name>fs.viewfs.overload.scheme.target.hdfs.impl</name>"
+ "<value>org.apache.hadoop.hdfs.DistributedFileSystem</value></property>",
"<property><name>fs.viewfs.mounttable.ip-10-0-0-1.ec2.internal.link./tmp/hadoop/mapred/staging</name>"
+ "<value>file:///tmp/hadoop/mapred/staging</value></property>",
"<property><name>fs.viewfs.mounttable.ip-10-0-0-1.ec2.internal.linkFallback</name>"
+ "<value>hdfs://ip-10-0-0-1.ec2.internal:8020</value></property>",
"<property><name>fs.permissions.umask-mode</name><value>077</value></property>",
"<property><name>floci.note</name><value>a&lt;b &amp; &quot;c&quot; &apos;d&apos;</value></property>"),
EmrServerlessSparkRunner.hadoopSite(
@@ -1286,6 +1293,27 @@ class EmrServerlessSparkRunnerTest {
verify(lifecycle, never()).removeIfExists("another-deployments");
}
@Test
void theHdfsOfALiveClusterIsNoDriverTheSweepRemoves() {
EmrServerlessSparkRunner runner = runner();
when(config.port()).thenReturn(4566);
Container hdfs = mock(Container.class);
when(hdfs.getId()).thenReturn("hdfs");
when(hdfs.getLabels()).thenReturn(Map.of(ContainerStorageHelper.SERVICE_LABEL, "emr",
ContainerStorageHelper.OWNER_LABEL, "4566", ContainerStorageHelper.COMPONENT_LABEL, "emr-hdfs"));
Container driver = mock(Container.class);
when(driver.getId()).thenReturn("left-behind");
when(driver.getLabels()).thenReturn(Map.of(ContainerStorageHelper.SERVICE_LABEL, "emr",
ContainerStorageHelper.OWNER_LABEL, "4566"));
when(docker.listContainersCmd().withShowAll(true).withLabelFilter(anyMap()).exec())
.thenReturn(List.of(hdfs, driver));
runner.removeLeftoverDrivers("emr");
verify(lifecycle).removeIfExists("left-behind");
verify(lifecycle, never()).removeIfExists("hdfs");
}
// A runner whose driver container, "driver", starts at once and exits with code 0 unless a test says otherwise.
private EmrServerlessSparkRunner runner() {
return runner(mock(ContainerBuilder.class, RETURNS_DEEP_STUBS));
@@ -1410,7 +1438,8 @@ class EmrServerlessSparkRunnerTest {
return new SparkJobRunner.Job("emr", "s-1", "123456789012", "eu-west-1", "emr-7.5.0", HIVE, null, null,
"floci-network", "arn:aws:iam::123456789012:role/emr-ec2", Map.of(), application,
List.of("hive-script", "--run-hive-script", "--args"), Duration.ZERO, null, null, Map.of(), List.of(),
new SparkJobRunner.Storage("j-1-home", "j-1-mnt"), Map.of(), Map.of(), Map.of(), Map.of(), Map.of());
new SparkJobRunner.Storage("j-1-home", "j-1-mnt", "ip-10-0-0-1.ec2.internal", "172.18.0.5",
"j-1-hdfs"), Map.of(), Map.of(), Map.of(), Map.of(), Map.of());
}
private static SparkJobRunner.Job customImageJob(String customImage) {