diff --git a/.github/ci/prefetch-images.sh b/.github/ci/prefetch-images.sh index 7118cf4c0c..466752df0b 100755 --- a/.github/ci/prefetch-images.sh +++ b/.github/ci/prefetch-images.sh @@ -100,8 +100,9 @@ starts ElbV2LambdaTargetDataPlaneIntegrationTest && ecr public.ecr.aws/lambda/py starts EmrDockerRunnerDockerIntegrationTest EmrHiveStepsDockerIntegrationTest \ && ecr public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest # EmrServerlessHiveDockerIntegrationTest runs EMR Serverless Hive job runs, and EmrHiveStepsDockerIntegrationTest EMR -# Hive steps, in the emr-7.5.0 Hive image the runner's default Hive template names, 2.7 GB. -starts EmrServerlessHiveDockerIntegrationTest EmrHiveStepsDockerIntegrationTest \ +# Hive steps, in the emr-7.5.0 Hive image the runner's default Hive template names, 2.7 GB; every EMR cluster runs its +# HDFS in it, EmrDockerRunnerDockerIntegrationTest's included. +starts EmrServerlessHiveDockerIntegrationTest EmrHiveStepsDockerIntegrationTest EmrDockerRunnerDockerIntegrationTest \ && ecr public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest # package token in shard.txt -> images its tests are known to launch diff --git a/docs/services/emr.md b/docs/services/emr.md index 2d09392b16..7941802c0e 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -82,8 +82,10 @@ termination status, and answers an unknown cluster with `ValidationException` "S does not exist.", as AWS does. Instance groups and fleets report `RUNNING` from the cluster's creation until it is `TERMINATED`. Then they report `TERMINATED` with zero running or provisioned capacity; their requested and target -capacities remain recorded. `ListInstances` retains each group's instances with their original -synthetic IDs and `TERMINATED` status for 30 days after termination. New groups or fleets are rejected +capacities remain recorded. `ListInstances` numbers the synthetic IDs and addresses of the `MASTER` +group's instance first, so the primary node keeps `i-00000000000000001` and `10.0.0.1`, as +`DescribeCluster`'s `MasterPublicDnsName` says, while the other groups resize; it retains each group's +instances with their original synthetic IDs and `TERMINATED` status for 30 days after termination. New groups or fleets are rejected on terminated clusters. As on AWS, `ModifyInstanceGroups` answers `ValidationException` "An instance group may only be modified when the cluster is running or waiting." for a cluster in any other state, and `ModifyInstanceFleet` answers `InvalidRequestException` "A job flow that is shutting down, @@ -139,25 +141,42 @@ but for its bootstrap actions and its storage. configuration of its own, a copy of the folder a `spark-env` export of `SPARK_CONF_DIR` names, else of the image's, ahead of the image's EMR Serverless master; its own `--master yarn` or `--deploy-mode cluster` fails, as there is no YARN. -* **Storage**: a cluster's primary node keeps its disks while the cluster lives, and so does Floci: each - step's container mounts the cluster's two Docker volumes, one at `/home/hadoop` and one at `/mnt`, so what - a step leaves there is there for the steps after it, and for steps running at the same time. HDFS, "best - used for caching the results produced by intermediate job-flow steps", as the Management Guide puts it, - is the `hdfs` folder of `/mnt`. In Spark, `hdfs://` paths, and paths without a scheme ("hdfs:// (or no - prefix)"), lead there through Hadoop's `ViewFileSystemOverloadScheme`, a relative path under - `/user/hadoop` as in HDFS, and a structured streaming query keeps its checkpoints through Spark's file - system checkpoint manager; the cluster's `spark-defaults` and `core-site` can set any of these otherwise. - A command's `hadoop fs` gets the same, through a copy of the image's Hadoop configuration, or of the - folder a `spark-env` export of `HADOOP_CONF_DIR` names, with the cluster's `core-site` after it, which - wins; the image's `hdfs` command cannot run, so `hdfs dfs` runs - as `hadoop fs`, and its other commands fail. What the bootstrap actions left in `/home/hadoop` or `/mnt` - comes with the image the steps run in, and Docker copies it into the - volumes when the first step starts. The volumes go once the cluster has ended and its last step is done - ("HDFS is ephemeral storage that is reclaimed when you terminate a cluster"), on a state reset, and, for - clusters that are gone or have ended, when the EMR service starts, unless - `reconcile-containers-on-startup` is off. HDFS is a folder, without a NameNode or replication: an - `hdfs://` path naming a host is not served, and `hadoop fs -ls /` fails ("URI scheme is not "file""), - where `-ls -d /` and a folder below it do not. `/tmp` is each container's own. +* **Storage**: a cluster's primary node keeps its disks while the cluster lives, and so does Floci: each step's + container mounts the cluster's two Docker volumes, one at `/home/hadoop` and one at `/mnt`, so what a step leaves + there is there for the steps after it, and for steps running at the same time. What the bootstrap actions left in + `/home/hadoop` or `/mnt` comes with the image the steps run in, and Docker copies it into the volumes when the + first step starts. Every cluster runs HDFS, "best used for caching the results produced by intermediate job-flow + steps", as the Management Guide puts it: a NameNode and a DataNode on its primary node, which Floci runs in a + container of their own, `emr--hdfs`, from the release's EMR Serverless Hive image, which has HDFS + where the release's image has only its client (`hive-image-template` names another), or, for an `emr-spark-*` + release, which has no Hive image, from `emr-7.5.0`'s, with their data in a third volume, one copy of each block, + and permissions off. The container is on a Docker network of the cluster's own, also `emr--hdfs`, + which the cluster's steps join besides their own, so the steps of other clusters, another account's included, + cannot reach its files; each cluster whose HDFS runs takes one network from the Docker daemon's address pools. + The cluster's first step starts it, and waits for it: a step whose cluster's HDFS is not ready within two minutes + fails ("The step could not start: The HDFS of EMR cluster ... did not start within 120 seconds"). If its NameNode or DataNode exits, its container ends with it, and the + cluster's next step starts it again on its data. Their warnings and errors are the container's output, which + `docker logs` shows. With `docker-network` set to `host`, steps reach it on the host's loopback, and its daemons + listen there only, as anyone reaching them could change its files, on the host's own ports (8020, 9870, 9866, + 9864, 9867), so only one cluster's HDFS runs at a time. With `container:`, its container joins that + namespace as the steps do, and listens on its loopback in the same way; the primary node's name goes in the hosts + file that namespace's containers share, ``'s own included. With `none`, steps have no network, so the + cluster runs no HDFS, and its steps run as without one. Steps reach + it by the primary node's `PrivateDnsName`, as `ListInstances` gives it (`ip-10-0-0-1.ec2.internal`, say), on port + 8020: `hdfs://` paths without a host, and paths without a scheme ("hdfs:// (or no prefix)"), lead there through + `fs.defaultFS`, a relative path under `/user/hadoop`, and the cluster's `spark-defaults` and `core-site` can set + it otherwise. A command's `hadoop fs` gets the same, through a copy of the image's Hadoop configuration, or of the + folder a `spark-env` export of `HADOOP_CONF_DIR` names, with the cluster's `core-site` after it, which wins; the + image's `hdfs` command cannot run, so `hdfs dfs` runs as `hadoop fs`, and its other commands fail. A structured + streaming query keeps its checkpoints through Spark's file system checkpoint manager, as its default one refuses + an `hdfs://` path without a host. In a command's Hadoop configuration, which a custom JAR's MapReduce in the + driver reads too, the `hdfs` scheme is a view of that HDFS in which one folder, `/tmp/hadoop/mapred/staging`, is + the container's own, for MapReduce in local mode (see **Hadoop streaming and MapReduce**); Spark and Hive keep + HDFS's own client, so a Spark step can write a Hive table there. The HDFS container, its network and the volumes + go once the cluster has ended and its last step is done ("HDFS is ephemeral storage that is reclaimed when you terminate a + cluster"), on a state reset, and, for clusters that are gone or have ended, when the EMR service starts, unless + `reconcile-containers-on-startup` is off. A shutdown of Floci removes the HDFS containers of the clusters that are + still up, and their next step starts them again, on the data their volume keeps. `/tmp` is each container's own. * **Hadoop streaming and MapReduce**: a step's `hadoop` command runs MapReduce in local mode, in its own JVM, as there is no YARN: the image has MapReduce only in Spark's shaded Hadoop client, which Floci makes the command's MapReduce home (`HADOOP_MAPRED_HOME`, unless a `spark-env` export names one), so it is on the @@ -169,9 +188,11 @@ but for its bootstrap actions and its storage. program. In the console and some SDKs, this is a streaming step", as the Release Guide's tools table puts it (the AWS CLI's `Type=STREAMING` becomes one), runs the image's `hadoop-streaming.jar` with the step's other arguments: its mapper and reducer can come from Floci's S3 through `-files`, `-cacheFile` or - `-cacheArchive`, and its `-input` and `-output` can be in Floci's S3 or the cluster's HDFS, where a job's - staging folder, `/tmp/hadoop/mapred/staging`, is too. A `hadoop-lzo` step runs the image's LZO indexer the - same way, as does a `hadoop jar` a command or script runs. `s3://` and `s3a://` paths reach Floci's S3 + `-cacheArchive`, and its `-input` and `-output` can be in Floci's S3 or the cluster's HDFS. A job stages its + files in `/tmp/hadoop/mapred/staging`, a folder of the step's container, then looks for them at that path + of the default file system, the cluster's HDFS, so there the `hdfs` scheme leads to that folder. A + `hadoop-lzo` step runs the image's LZO indexer the same way, as does a `hadoop jar` a command or script + runs. `s3://` and `s3a://` paths reach Floci's S3 through S3A, with the AWS SDK Spark's own S3A finds, in place of the image's EMRFS, which is not pointed at Floci. The image's `log4j.properties` for Hadoop is empty, so Hadoop logs to the step's standard error, from `INFO` up, in the layout of the Management Guide's step log lines, and `stderr.gz` holds a failed job's @@ -216,13 +237,10 @@ but for its bootstrap actions and its storage. Derby database in the cluster's `/mnt`, so a table one Hive step makes is there for the next, until the cluster ends. The `hive-site` setting of `hive.metastore.client.factory.class` the Release Guide gives for the Glue Data Catalog uses Floci's Glue instead, with the cluster's account as its `hive.metastore.glue.catalogid`, which a - `hive-site` one replaces. A table without a `LOCATION` is in the cluster's HDFS, `/user/hive/warehouse` ("By - default, this is a location in HDFS"). Hive reaches that HDFS folder under the `viewfs` scheme: it looks up the - HDFS encryption zone of every `hdfs://` path it writes or reads a table at, which only an HDFS NameNode can - answer. So a table's location reads `viewfs:/user/hive/warehouse/`, the folder other steps name - `hdfs:///user/hive/warehouse/
`, and a Hive statement on an `hdfs://` path fails ("Unable to determine if - hdfs:... is encrypted"). Spark steps do not use the cluster's Hive metastore, so they see a Hive step's tables - only through the Glue Data Catalog. Only one Hive step at a time can use the cluster's metastore: with + `hive-site` one replaces. A table without a `LOCATION` is in the cluster's HDFS, under `/user/hive/warehouse` ("By + default, this is a location in HDFS"), which other steps read as `hdfs:///user/hive/warehouse/
`, and an + `hdfs://` `LOCATION` is there too. Spark steps do not use the cluster's Hive metastore, so they see a Hive step's + tables only through the Glue Data Catalog. Only one Hive step at a time can use the cluster's metastore: with `StepConcurrencyLevel` above 1, a Hive step that starts while another runs fails ("Another instance of Derby may have already booted the database"). What the bootstrap actions installed is there for every step, Hive's included. A script or command that starts `hive` itself gets none of these settings: only a Hive step runs Hive. @@ -252,8 +270,8 @@ but for its bootstrap actions and its storage. `--multipartUploadChunkSize` set S3A's matching settings; `--s3Endpoint` is ignored, as S3 is Floci's. A bucket name with an underscore fails the step, as S3DistCp "does not support" one, and so does a copy Hadoop fails, leaving what was copied, as S3DistCp does. `--appendToLastFile` puts the new data after - what a destination file holds, through a copy renamed over it, as neither S3 nor the cluster's HDFS, a - folder, appends in place. The copy has a name of its own and goes if the writing fails; the file steps + what a destination file holds, through a copy renamed over it, on every file system, as S3 cannot append + in place. The copy has a name of its own and goes if the writing fails; the file steps aside, under a name of its own too, until the copy has taken its place, and comes back if it cannot, so a failed append leaves it as it was. A copy that would write two files to the same path, the manifest included (`a.log` and `a.log.gz` with `--outputCodec=gzip`, say), a file over one of its own sources, as with the @@ -308,7 +326,8 @@ but for its bootstrap actions and its storage. * **Cancelling**: `CancelSteps` on a `RUNNING` step, and `TerminateJobFlows`, stop its driver at once; a cancelled step takes no `ActionOnFailure`. A step Floci was running when it stopped is `FAILED` once Floci is back, and its `ActionOnFailure` is taken then. Floci's shutdown and a state reset stop every - driver, and start no other step; a driver a hard stop left running is removed when the EMR service + driver, then the clusters' HDFS, a step not yet at its driver as if its driver were stopped, and start no other + step; a driver a hard stop left running is removed when the EMR service starts, before any step can start, unless `reconcile-containers-on-startup` is off. * **What `spark-submit` gets**: the step's arguments, after the `spark-defaults` properties of the cluster's `Configurations` and its `core-site` and `spark-hive-site` ones as `spark.hadoop.` settings, @@ -354,8 +373,10 @@ but for its bootstrap actions and its storage. every five minutes), and `FailureDetails` has no `LogFile`. * **Image**: `image-template` names another image, such as a mirror or a dated tag of the release's image: `registry.internal/emr-serverless/spark/%s:20250425`, and `hive-image-template` another Hive image: - `registry.internal/emr-serverless/hive/%s:20250425`. A release with no EMR Serverless image - fails its steps with "The step could not start: Could not pull image". + `registry.internal/emr-serverless/hive/%s:20250425`. Every cluster's steps need both, the Hive image for the + cluster's HDFS (see **Storage**), so a mirror sets both, and carries `emr-7.5.0`'s Hive image for an `emr-spark-*` + release. A release with no EMR Serverless image, or another with no EMR Serverless Hive image, fails its steps + with "The step could not start: Could not pull image". ## EventBridge events @@ -406,8 +427,8 @@ its `STARTING` event, has its events sent after the rest of that call's. | `FLOCI_SERVICES_EMR_CLUSTER_TERMINATION_DELAY_SECONDS` | `0` | Seconds a cluster stays `TERMINATING` before it is `TERMINATED`; `0` ends it at once | | `FLOCI_SERVICES_EMR_RUNNER_MODE` | `immediate` | `immediate` completes steps by time without running anything; `docker` runs each step in a container, after the cluster's bootstrap actions (see [Running steps](#running-steps)) | | `FLOCI_SERVICES_EMR_DOCKER_NETWORK` | the global default | Docker network for step containers | -| `FLOCI_SERVICES_EMR_IMAGE_TEMPLATE` | `public.ecr.aws/emr-serverless/spark/%s:latest`, or `spark4/` in place of `spark/` for an `emr-spark-*` release | Image for a `docker` step, `%s` standing for the cluster's release label | -| `FLOCI_SERVICES_EMR_HIVE_IMAGE_TEMPLATE` | `public.ecr.aws/emr-serverless/hive/%s:latest` | The EMR Serverless Hive image a `docker` cluster with Hive takes Hive from, `%s` standing for the cluster's release label; see [Hive steps](#running-steps) | +| `FLOCI_SERVICES_EMR_IMAGE_TEMPLATE` | `public.ecr.aws/emr-serverless/spark/%s:latest`, or `spark4/` in place of `spark/` for an `emr-spark-*` release | Image for a `docker` step, `%s` standing for the cluster's release label; a mirror sets `FLOCI_SERVICES_EMR_HIVE_IMAGE_TEMPLATE` too | +| `FLOCI_SERVICES_EMR_HIVE_IMAGE_TEMPLATE` | `public.ecr.aws/emr-serverless/hive/%s:latest` | The EMR Serverless Hive image every `docker` cluster runs its HDFS in, and a cluster with Hive takes Hive from, `%s` standing for the cluster's release label, or `emr-7.5.0` for the HDFS of an `emr-spark-*` release; see [Storage and Hive steps](#running-steps) | | `FLOCI_SERVICES_EMR_RECONCILE_CONTAINERS_ON_STARTUP` | `true` | Remove the step drivers and bootstrap containers a previous run of this Floci left on the Docker daemon, and the images bootstrap actions left for clusters that are gone or have ended, when the EMR service starts; turn it off when two Floci instances share a daemon with the same port and no resource namespace | ## Release catalogue diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index ef8af5bc82..02e6f8df1f 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -2060,15 +2060,17 @@ public interface EmulatorConfig { /** * The image a {@code docker} step uses, with {@code %s} standing for the cluster's release label, * for example "registry.internal/emr-serverless/spark/%s:20250425". If omitted, Floci uses the - * release's public EMR Serverless image on Amazon ECR Public. + * release's public EMR Serverless image on Amazon ECR Public. Every cluster also runs its HDFS in + * {@link #hiveImageTemplate()}'s image, so a mirror names both. */ Optional imageTemplate(); /** - * The EMR Serverless Hive image a {@code docker} cluster with Hive takes Hive from, into the image its - * bootstrap and steps run in, as {@link #imageTemplate()} names the image Hive is added to, for example - * "registry.internal/emr-serverless/hive/%s:20250425". If omitted, Floci uses the release's public EMR - * Serverless Hive image on Amazon ECR Public. + * The EMR Serverless Hive image every {@code docker} cluster runs its HDFS in, and a cluster with Hive takes + * Hive from, into the image its bootstrap and steps run in, as {@link #imageTemplate()} names the image Hive + * is added to, for example "registry.internal/emr-serverless/hive/%s:20250425". If omitted, Floci uses the + * release's public EMR Serverless Hive image on Amazon ECR Public. An emr-spark-* release has none, so its + * clusters run their HDFS in emr-7.5.0's. */ Optional hiveImageTemplate(); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ContainerTeardown.java b/src/main/java/io/github/hectorvent/floci/core/common/ContainerTeardown.java index 07013c9c86..d441d598b3 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ContainerTeardown.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ContainerTeardown.java @@ -24,4 +24,13 @@ package io.github.hectorvent.floci.core.common; public interface ContainerTeardown { void stopManagedContainers(); + + /** + * Where this teardown runs among the others: {@link ContainerTeardowns#stopAll} runs them in ascending order, + * those of one order as CDI lists them. One whose containers others' containers use, as an EMR cluster's HDFS its + * steps' drivers, runs after them, so theirs are stopped first and do not fail against it. + */ + default int teardownOrder() { + return 0; + } } diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ContainerTeardowns.java b/src/main/java/io/github/hectorvent/floci/core/common/ContainerTeardowns.java index af3a82c7c3..ec9db58f6b 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ContainerTeardowns.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ContainerTeardowns.java @@ -4,6 +4,7 @@ import jakarta.enterprise.inject.Instance; import org.jboss.logging.Logger; import java.util.ArrayList; +import java.util.Comparator; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; @@ -25,7 +26,12 @@ public final class ContainerTeardowns { } public static void stopAll(Instance teardowns, Logger log) { + List ordered = new ArrayList<>(); for (ContainerTeardown teardown : teardowns) { + ordered.add(teardown); + } + ordered.sort(Comparator.comparingInt(ContainerTeardown::teardownOrder)); + for (ContainerTeardown teardown : ordered) { try { teardown.stopManagedContainers(); } catch (Exception e) { diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java index 55c212fd9d..157e2ed7f9 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java @@ -1003,6 +1003,51 @@ public class ContainerLifecycleManager { } } + /** + * Creates the bridge network {@code networkName} with {@code labels}, as {@link #ensureVolume(String, Map)} does a + * volume, when Docker has no network of that name; one that exists is used as it is. Containers on it reach each + * other, and containers on no other network reach them through it. + */ + public void ensureNetwork(String networkName, Map labels) { + try { + dockerClient.inspectNetworkCmd().withNetworkId(networkName).exec(); + return; + } catch (NotFoundException e) { + // Made below. + } + dockerClient.createNetworkCmd() + .withName(networkName) + .withDriver("bridge") + .withLabels(mergedLabels(labels)) + .exec(); + LOG.debugv("Created network {0}", networkName); + } + + /** Connects the created container {@code containerId} to {@code networkName} too, before it starts. */ + public void connectToNetwork(String containerId, String networkName) { + dockerClient.connectToNetworkCmd() + .withContainerId(containerId) + .withNetworkId(networkName) + .exec(); + } + + /** + * Removes the network {@code networkName}: true once it is gone, false when Docker kept it, as + * {@link #removeVolume} says of a volume. + */ + public boolean removeNetwork(String networkName) { + try { + dockerClient.removeNetworkCmd(networkName).exec(); + LOG.debugv("Removed network {0}", networkName); + return true; + } catch (NotFoundException e) { + return true; + } catch (Exception e) { + LOG.warnv("Error removing network {0}: {1}", networkName, e.getMessage()); + return false; + } + } + /** * Finds an existing container by name. * diff --git a/src/main/java/io/github/hectorvent/floci/services/emr/ClusterStorage.java b/src/main/java/io/github/hectorvent/floci/services/emr/ClusterStorage.java index dd74c4ab33..46a9b68dbf 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emr/ClusterStorage.java +++ b/src/main/java/io/github/hectorvent/floci/services/emr/ClusterStorage.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.emr; import io.github.hectorvent.floci.services.emrserverless.SparkJobRunner; import java.util.Set; +import java.util.function.BooleanSupplier; /** * A cluster's storage in the EMR {@code docker} runner mode: the disks of its primary node, which every one of @@ -19,8 +20,18 @@ public interface ClusterStorage { void create(String clusterId, String accountId, String region); /** - * Removes the volumes of {@code clusterId}'s storage once it no longer needs them: true when they are gone, - * false when Docker refused, so the caller can try again. + * Starts {@code clusterId}'s HDFS, a NameNode and a DataNode keeping their data in a volume of their own, in a + * container of {@code image} on a Docker network of the cluster's own, or on the host's when its steps run there, + * unless it is running, and returns the cluster's storage with it: its primary node's {@code host} name, which a + * step's container resolves to the address given, on the network given. A failure to start it is thrown, and + * {@link Stopped} once {@code stopped} says the step is past starting, or a teardown has stopped the HDFS. + */ + SparkJobRunner.Storage hdfs(String clusterId, String accountId, String region, String host, String image, + String dockerNetwork, BooleanSupplier stopped); + + /** + * Removes {@code clusterId}'s HDFS and the volumes of its storage once it no longer needs them: true when the + * volumes are gone, false when Docker refused, so the caller can try again. */ boolean remove(String clusterId); @@ -29,4 +40,12 @@ public interface ClusterStorage { * restart, the storage of the clusters that are gone or have ended, and on a reset all of it. */ void removeAllBut(Set kept); + + /** A step stopped while it waited for its cluster's HDFS, by a cancel, its cluster's end or a teardown. */ + final class Stopped extends RuntimeException { + + public Stopped(String message) { + super(message); + } + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/emr/EmrClusterStorage.java b/src/main/java/io/github/hectorvent/floci/services/emr/EmrClusterStorage.java index dd706d1c85..9c4eb11166 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emr/EmrClusterStorage.java +++ b/src/main/java/io/github/hectorvent/floci/services/emr/EmrClusterStorage.java @@ -2,39 +2,148 @@ package io.github.hectorvent.floci.services.emr; import com.github.dockerjava.api.command.InspectVolumeResponse; import com.github.dockerjava.api.command.ListVolumesResponse; +import com.github.dockerjava.api.model.Container; +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.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.ContainerSpec; import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper; import io.github.hectorvent.floci.services.emrserverless.SparkJobRunner; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.time.Duration; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.Optional; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.BooleanSupplier; +import java.util.function.LongSupplier; /** - * Keeps each EMR cluster's storage in two Docker volumes, one for its primary node's {@code /home/hadoop} and one - * for its {@code /mnt}, where its HDFS is. Both paths belong to the image's {@code hadoop} user, and Docker gives - * an empty volume what the image has at the path it is first mounted on, owner included, so the steps, which - * run as that user, can write to both, and what the cluster's bootstrap left there comes with them. + * Keeps each EMR cluster's storage in Docker volumes, one for its primary node's {@code /home/hadoop} and one for its + * {@code /mnt}. Both paths belong to the image's {@code hadoop} user, and Docker gives an empty volume what the image + * has at the path it is first mounted on, owner included, so the steps, which run as that user, can write to both, + * and what the cluster's bootstrap left there comes with them. Its HDFS, which every EMR cluster runs (from + * emr-7.14.0 on, "When you select Trino as the only application at launch, Amazon EMR no longer starts YARN and + * HDFS", a cluster Floci does not run), is a NameNode and a DataNode in a container of their own, the cluster's + * primary node's, with their data in a third volume, so that the first container to mount the {@code /mnt} one is a + * step's, which fills it from the step's image. */ @ApplicationScoped -public class EmrClusterStorage implements ClusterStorage { +public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { private static final Logger LOG = Logger.getLogger(EmrClusterStorage.class); private static final String SERVICE = "emr"; private static final String COMPONENT = "emr-storage"; + private static final String HDFS_COMPONENT = SparkJobRunner.Storage.HDFS_COMPONENT; + private static final String HDFS_CONF = "/tmp/floci-hdfs-conf"; + private static final String HDFS_READY = "/tmp/floci-hdfs-ready"; + private static final String HOST_NETWORK = "host"; + private static final String CONTAINER_NETWORK_PREFIX = "container:"; + private static final String NO_NETWORK = "none"; + private static final String LOOPBACK = "127.0.0.1"; + // The NameNode's JMX on its web port, which says when the DataNode has joined and safe mode has ended without + // starting a JVM of hdfs's own each time it is asked; each look is given five seconds, so one the NameNode does not + // answer while it starts is asked again. + private static final String NAMENODE_JMX = "http://127.0.0.1:9870/jmx?qry=Hadoop:service=NameNode,name="; + // How long a cluster's HDFS may take to start, its NameNode formatted the first time, before a step gives up. + private static final Duration HDFS_START_TIMEOUT = Duration.ofSeconds(120); + private static final Duration HDFS_POLL_INTERVAL = Duration.ofMillis(500); + // The primary node's HDFS, started as root: its daemons log their warnings and errors to the container's output, + // which docker logs shows; its host name, FLOCI_HDFS_HOST, leads to this container's address, where the DataNode + // registers, so steps reach both by it; /mnt, its data's volume, becomes the image's user's, which runs a NameNode + // and a DataNode with their data in it, the NameNode formatted the first time, with one copy of each block and + // without permissions, listening on FLOCI_HDFS_BIND: every address of the container, on the cluster's own network, + // or, in a namespace the steps share, the host's or a container's, only its loopback, which its name leads to, so + // no other interface serves files anyone could change; in a container's, the hosts file the name goes in is the + // one the namespace's containers share, the steps' too. Once the NameNode on its port is this container's own, + // its ClusterId the one its format gave it, rather than another cluster's in that namespace, the DataNode has + // joined and the NameNode has left safe mode, which on a restart waits for the blocks the volume holds, the + // folders EMR's HDFS has for steps, /tmp and the hadoop user's home, are made, and HDFS_READY says it is ready. A + // daemon that exits, before or after, ends the container, its readiness gone, so the next step starts it again on + // its data. + private static final String HDFS_SCRIPT = 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", + "chown hadoop:hadoop /mnt || exit", + "mkdir -p " + HDFS_CONF + " || exit", + "printf '%s\\n' ''" + + " \"fs.defaultFShdfs://$FLOCI_HDFS_HOST:8020\"" + + " '' > " + HDFS_CONF + "/core-site.xml", + "printf '%s\\n' ''" + + " 'dfs.namenode.name.dirfile:///mnt/namenode'" + + " 'dfs.datanode.data.dirfile:///mnt/datanode'" + + " 'dfs.replication1'" + + " 'dfs.permissions.enabledfalse'" + + " \"dfs.namenode.rpc-bind-host$FLOCI_HDFS_BIND\"" + + " \"dfs.namenode.http-address" + + "$FLOCI_HDFS_BIND:9870\"" + + " \"dfs.datanode.address$FLOCI_HDFS_BIND:9866\"" + + " \"dfs.datanode.http.address" + + "$FLOCI_HDFS_BIND:9864\"" + + " \"dfs.datanode.ipc.address" + + "$FLOCI_HDFS_BIND:9867\"" + + " '' > " + HDFS_CONF + "/hdfs-site.xml", + "printf '%s\\n' 'log4j.rootLogger=WARN,console' 'log4j.appender.console=org.apache.log4j.ConsoleAppender'" + + " 'log4j.appender.console.layout=org.apache.log4j.PatternLayout'" + + " 'log4j.appender.console.layout.ConversionPattern=%d %p %c: %m%n'" + + " > " + HDFS_CONF + "/log4j.properties", + "exec setpriv --reuid=hadoop --regid=hadoop --clear-groups bash -c '" + + "[ -d /mnt/namenode/current ] || hdfs namenode -format -nonInteractive || exit; " + + "cid=$(sed -n \"s/^clusterID=//p\" /mnt/namenode/current/VERSION); " + + "hdfs namenode & hdfs datanode & " + + "until curl -sf -m 5 \"" + NAMENODE_JMX + "NameNodeInfo\"" + + " | grep -q \"\\\"ClusterId\\\" : \\\"$cid\\\"\"; do " + + "[ \"$(jobs -rp | wc -l)\" = 2 ] || exit 1; sleep 0.2; done; " + + "until curl -sf -m 5 \"" + NAMENODE_JMX + "FSNamesystemState\"" + + " | grep -q \"\\\"NumLiveDataNodes\\\" : 1,\"; do " + + "[ \"$(jobs -rp | wc -l)\" = 2 ] || exit 1; sleep 0.2; done; " + + "until curl -sf -m 5 \"" + NAMENODE_JMX + "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 " + HDFS_READY + "; " + + "wait -n; rm -f " + HDFS_READY + "; kill $(jobs -rp) 2>/dev/null; exit 1'"); + // One start at a time in a namespace the steps share, whatever the cluster, as it holds one HDFS. + private final Object sharedNamespaceStarts = new Object(); + // One start at a time for each cluster's HDFS; a step coming while it starts waits, then finds it running. + private final Map starting = new ConcurrentHashMap<>(); + // The HDFS containers this process has started or found running, by name, which a reset or a shutdown removes. + private final Set running = ConcurrentHashMap.newKeySet(); private final ContainerLifecycleManager lifecycleManager; + private final ContainerBuilder containerBuilder; private final EmulatorConfig config; + private final Duration hdfsStartTimeout; + private final LongSupplier nanoTime; + // How many teardowns, by a reset or a shutdown, have run: a step waiting for its cluster's HDFS through one stops. + private final AtomicLong teardowns = new AtomicLong(); @Inject - public EmrClusterStorage(ContainerLifecycleManager lifecycleManager, EmulatorConfig config) { + public EmrClusterStorage(ContainerLifecycleManager lifecycleManager, ContainerBuilder containerBuilder, + EmulatorConfig config) { + this(lifecycleManager, containerBuilder, config, HDFS_START_TIMEOUT, System::nanoTime); + } + + EmrClusterStorage(ContainerLifecycleManager lifecycleManager, ContainerBuilder containerBuilder, + EmulatorConfig config, Duration hdfsStartTimeout, LongSupplier nanoTime) { this.lifecycleManager = lifecycleManager; + this.containerBuilder = containerBuilder; this.config = config; + this.hdfsStartTimeout = hdfsStartTimeout; + this.nanoTime = nanoTime; } @Override @@ -46,25 +155,321 @@ public class EmrClusterStorage implements ClusterStorage { @Override public void create(String clusterId, String accountId, String region) { - Map labels = new LinkedHashMap<>(ContainerStorageHelper.resourceIdentityLabels(SERVICE, - clusterId, accountId, region)); - labels.put(ContainerStorageHelper.COMPONENT_LABEL, COMPONENT); - labels.put(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)); + Map labels = labels(clusterId, accountId, region, COMPONENT); SparkJobRunner.Storage storage = volumes(clusterId); lifecycleManager.ensureVolume(storage.home(), labels); lifecycleManager.ensureVolume(storage.mnt(), labels); } + @Override + public SparkJobRunner.Storage hdfs(String clusterId, String accountId, String region, String host, String image, + String dockerNetwork, BooleanSupplier stopped) { + String name = hdfsName(clusterId); + String network = network(dockerNetwork); + if (NO_NETWORK.equals(network)) { + // Its steps have no network, so no HDFS reaches them: they run as without one. + return volumes(clusterId); + } + long teardown = teardowns.get(); + stopIfStopped(clusterId, teardown, stopped); + // Its image is there first, pulled when missing: the first pull of the Hive image, 2.7 GB, is no part of the + // HDFS's start, which the deadline gives two minutes from then, a step waiting while another starts it too. + // It starts from the id that pull resolved, which another pull of the same tag cannot move. + String imageId = lifecycleManager.resolveImageForLaunch(containerBuilder.resolveImage(image), + ImagePullBehavior.PREFER_CACHED, null).imageId(); + boolean shared = sharesNamespace(network); + long deadline = nanoTime.getAsLong() + hdfsStartTimeout.toNanos(); + synchronized (starting.computeIfAbsent(clusterId, id -> new Object())) { + String containerId = null; + // One found running whose daemon has just exited stops before it is ready, and is started again, once. + for (int attempt = 0; containerId == null; attempt++) { + stopIfStopped(clusterId, teardown, stopped); + ContainerLiveness liveness = lifecycleManager.probeContainer(name); + if (liveness == ContainerLiveness.UNKNOWN) { + // Docker did not answer: one that may be serving the cluster's other steps is left as it is. + throw new IllegalStateException("Could not tell whether the HDFS of EMR cluster " + clusterId + + " runs"); + } + boolean found = liveness == ContainerLiveness.RUNNING && attempt == 0 + && inStepsNamespace(name, shared ? network : name); + // Known before it starts, so a teardown while it starts removes it. + running.add(name); + String candidate = found ? name : start(clusterId, accountId, region, host, imageId, dockerNetwork); + if (awaitReady(clusterId, candidate, deadline, teardown, stopped)) { + containerId = candidate; + } else if (!found) { + stopIfStopped(clusterId, teardown, stopped); + throw new IllegalStateException("The HDFS of EMR cluster " + clusterId + + " stopped before it was ready"); + } + } + if (shared) { + return volumes(clusterId).withHdfs(host, LOOPBACK, null); + } + return volumes(clusterId).withHdfs(host, address(clusterId, containerId), name); + } + } + + // Where a step reaches the cluster's HDFS: its container's address on the cluster's own Docker network. + private String address(String clusterId, String containerId) { + String address = lifecycleManager.resolveContainerNetworkIp(containerId, hdfsName(clusterId)); + if (address == null || address.isBlank()) { + throw new IllegalStateException("The HDFS of EMR cluster " + clusterId + + " has no address on Docker network " + hdfsName(clusterId)); + } + return address; + } + + // Whether the HDFS container found running is in the namespace the steps run in, as its network mode says: the + // cluster's own network, the host's, or the same container's; one a process with another docker-network left + // goes, and starts again on its data. + private boolean inStepsNamespace(String name, String stepsNetwork) { + HostConfig hostConfig = lifecycleManager.getDockerClient().inspectContainerCmd(name).exec().getHostConfig(); + String networkMode = hostConfig != null ? hostConfig.getNetworkMode() : null; + return Objects.equals(namespaceOf(networkMode), namespaceOf(stepsNetwork)); + } + + // The namespace a network mode puts a container in, the same for a container's name and its id: the network, + // the host's, or the id of the container whose namespace it shares. + private String namespaceOf(String networkMode) { + if (networkMode == null || !networkMode.startsWith(CONTAINER_NETWORK_PREFIX)) { + return networkMode; + } + String owner = networkMode.substring(CONTAINER_NETWORK_PREFIX.length()); + try { + return CONTAINER_NETWORK_PREFIX + + lifecycleManager.getDockerClient().inspectContainerCmd(owner).exec().getId(); + } catch (RuntimeException e) { + return networkMode; + } + } + + // The network steps run on: docker-network's, else the global one, else Floci's own. + private String network(String dockerNetwork) { + return containerBuilder.resolveDockerNetwork(Optional.ofNullable(dockerNetwork)).orElse(null); + } + + // Whether the steps run in a network namespace they share, the host's or a container's, which the HDFS shares + // too, as Docker joins a container placed there to no other network. + private static boolean sharesNamespace(String network) { + return HOST_NETWORK.equals(network) || network != null && network.startsWith(CONTAINER_NETWORK_PREFIX); + } + + // A cluster's HDFS container, started anew on the HDFS data its volume holds, which goes with the cluster's other + // two; one a restart, a stop or a daemon's exit left goes first. It runs on a Docker network of the cluster's own, + // which only the cluster's steps join, as its HDFS serves its files to any client that reaches it: the steps of + // other clusters, of other accounts too, do not. In a namespace the steps share it listens on the loopback alone. + private String start(String clusterId, String accountId, String region, String host, String imageId, + String dockerNetwork) { + String network = network(dockerNetwork); + if (!sharesNamespace(network)) { + return createContainer(clusterId, accountId, region, host, imageId, network, false); + } + // One namespace holds one HDFS's ports, whose daemons would answer this one's readiness and its steps: the look + // for another cluster's and this one's start go together, so two clusters' steps cannot both pass it. + synchronized (sharedNamespaceStarts) { + String other = otherRunningHdfs(clusterId, network); + if (other != null) { + throw new IllegalStateException("The HDFS of EMR cluster " + clusterId + " cannot start while that of" + + " EMR cluster " + other + " runs in the network namespace they share"); + } + return createContainer(clusterId, accountId, region, host, imageId, network, true); + } + } + + // Creates and starts the container start() decided on, in the namespace the steps share or on a network of its + // cluster's own. + private String createContainer(String clusterId, String accountId, String region, String host, String imageId, + String network, boolean shared) { + String name = hdfsName(clusterId); + // One left stopped goes first, and a removal Docker refuses fails the start as it is, not as a name clash. + lifecycleManager.removeIfExistsStrict(name); + lifecycleManager.ensureVolume(name, labels(clusterId, accountId, region, COMPONENT)); + if (!shared) { + lifecycleManager.ensureNetwork(name, labels(clusterId, accountId, region, HDFS_COMPONENT)); + } + ContainerSpec spec = containerBuilder.newContainer(imageId) + .withName(name) + .withUser("root") + .withEntrypoint(List.of("/bin/bash", "-c", HDFS_SCRIPT)) + .withEnv("FLOCI_HDFS_HOST", host) + .withEnv("FLOCI_HDFS_BIND", shared ? LOOPBACK : "0.0.0.0") + .withEnv("HADOOP_CONF_DIR", HDFS_CONF) + .withEnv("HADOOP_LOG_DIR", "/tmp/floci-hdfs-logs") + .withNamedVolume(name, "/mnt") + .withDockerNetwork(Optional.of(shared ? network : name)) + .withLogRotation() + .withLabels(labels(clusterId, accountId, region, HDFS_COMPONENT)) + .build(); + String containerId = lifecycleManager.createAndStart(spec).containerId(); + LOG.infov("Started the HDFS of EMR cluster {0} as {1}", clusterId, host); + return containerId; + } + + // The cluster of another HDFS container of this deployment running in the namespace network gives, or null. + private String otherRunningHdfs(String clusterId, String network) { + for (Container container : lifecycleManager.getDockerClient().listContainersCmd() + .withLabelFilter(Map.of(ContainerStorageHelper.COMPONENT_LABEL, HDFS_COMPONENT, + ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config))) + .exec()) { + String other = container.getLabels() != null + ? container.getLabels().get(ContainerStorageHelper.RESOURCE_ID_LABEL) : null; + // Only one in this very namespace holds its ports, not one on its own network or in another namespace. + String networkMode = container.getHostConfig() != null ? container.getHostConfig().getNetworkMode() : null; + if (other != null && !other.equals(clusterId) + && Objects.equals(namespaceOf(networkMode), namespaceOf(network))) { + return other; + } + } + return null; + } + + // Whether the container became ready by the deadline, false when it stopped first, or the step did, or a teardown + // has run since it asked; a failure to become ready in time is thrown. + private boolean awaitReady(String clusterId, String containerId, long deadline, long teardown, + BooleanSupplier stopped) { + while (teardowns.get() == teardown && !stopped.getAsBoolean()) { + // Docker refuses an exec into a container that has stopped, so that is looked at first. + if (lifecycleManager.probeContainer(containerId) == ContainerLiveness.NOT_RUNNING) { + return false; + } + long exitCode; + try { + exitCode = ContainerExec.run(lifecycleManager.getDockerClient(), containerId, + new String[]{"test", "-f", HDFS_READY}, 10).exitCode(); + } catch (RuntimeException e) { + // It may have stopped after it was looked at, which makes Docker refuse the exec. + if (lifecycleManager.probeContainer(containerId) == ContainerLiveness.NOT_RUNNING) { + return false; + } + throw e; + } + if (exitCode == 0) { + return true; + } + if (nanoTime.getAsLong() >= deadline) { + throw new IllegalStateException("The HDFS of EMR cluster " + clusterId + " did not start within " + + hdfsStartTimeout.toSeconds() + " seconds"); + } + try { + Thread.sleep(HDFS_POLL_INTERVAL.toMillis()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Stopped waiting for the HDFS of EMR cluster " + clusterId, e); + } + } + return false; + } + + // A teardown since the step asked for its cluster's HDFS stops the step as it would its driver, and the container + // goes, one the step started after the teardown looked too; a step past starting otherwise, by a cancel, its + // cluster's end or a teardown that has not reached the HDFS yet, stops and leaves it to the cluster's other steps. + private void stopIfStopped(String clusterId, long teardown, BooleanSupplier stopped) { + if (teardowns.get() != teardown) { + removeKnown(hdfsName(clusterId)); + throw new ClusterStorage.Stopped("Floci stopped the HDFS of EMR cluster " + clusterId); + } + if (stopped.getAsBoolean()) { + throw new ClusterStorage.Stopped("A step of EMR cluster " + clusterId + " stopped while its HDFS started"); + } + } + + // The name of a cluster's HDFS container, of the volume its data is in, and of the Docker network it is on. + private String hdfsName(String clusterId) { + return ContainerStorageHelper.dockerName(config, SERVICE + "-" + clusterId + "-hdfs"); + } + + private Map labels(String clusterId, String accountId, String region, String component) { + Map labels = new LinkedHashMap<>(ContainerStorageHelper.resourceIdentityLabels(SERVICE, + clusterId, accountId, region)); + labels.put(ContainerStorageHelper.COMPONENT_LABEL, component); + labels.put(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)); + return labels; + } + @Override public boolean remove(String clusterId) { + // Its HDFS goes first, as its container holds the volume of its data and its network, and its lock with it, so + // the clusters that have ended leave none behind. + starting.remove(clusterId); + boolean containerGone = removeKnown(hdfsName(clusterId)); SparkJobRunner.Storage storage = volumes(clusterId); - // Both are tried, so one Docker refused does not keep the other. + // Each is tried, so one Docker refused does not keep the others. + boolean networkGone = lifecycleManager.removeNetwork(hdfsName(clusterId)); boolean homeGone = lifecycleManager.removeVolume(storage.home()); - return lifecycleManager.removeVolume(storage.mnt()) && homeGone; + boolean mntGone = lifecycleManager.removeVolume(storage.mnt()); + return lifecycleManager.removeVolume(hdfsName(clusterId)) && mntGone && homeGone && networkGone + && containerGone; + } + + /** + * Removes the HDFS containers this process has started or found running, so a reset or a shutdown leaves none + * running; a cluster's next step starts its HDFS again, on the data its volume keeps. A step waiting for one + * stops, as its driver would, and removes one it started since. This runs after the teardowns of the drivers, + * which use the HDFS, so theirs stop first. + */ + @Override + public void stopManagedContainers() { + teardowns.incrementAndGet(); + for (String name : List.copyOf(running)) { + removeKnown(name); + } + } + + // Removes an HDFS container, forgetting it only once Docker says it is gone: one Docker keeps stays known, so the + // next reset or shutdown tries again. Whether it is gone. + private boolean removeKnown(String name) { + try { + lifecycleManager.removeIfExistsStrict(name); + running.remove(name); + return true; + } catch (RuntimeException e) { + LOG.warnv(e, "Could not remove the HDFS container {0}: {1}", name, e.getMessage()); + return false; + } + } + + @Override + public int teardownOrder() { + return 1; } @Override public void removeAllBut(Set kept) { + // Each sweep on its own, so Docker refusing one list does not keep the others from going. + try { + for (Container container : lifecycleManager.getDockerClient().listContainersCmd().withShowAll(true) + .withLabelFilter(Map.of(ContainerStorageHelper.COMPONENT_LABEL, HDFS_COMPONENT, + ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config))) + .exec()) { + Map labels = container.getLabels() != null ? container.getLabels() : Map.of(); + String clusterId = labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL); + if (!kept.contains(clusterId)) { + // Known first, so one Docker refuses to remove stays for the next reset or shutdown to remove. + String name = clusterId != null ? hdfsName(clusterId) : container.getId(); + running.add(name); + removeKnown(name); + } else { + // A cluster still up keeps the HDFS an earlier process left, which a reset or a shutdown removes. + running.add(hdfsName(clusterId)); + } + } + } catch (RuntimeException e) { + LOG.warnv(e, "Could not remove the HDFS of EMR clusters that have ended: {0}", e.getMessage()); + } + try { + for (Network network : lifecycleManager.getDockerClient().listNetworksCmd() + .withFilter("label", List.of(ContainerStorageHelper.COMPONENT_LABEL + "=" + HDFS_COMPONENT, + ContainerStorageHelper.OWNER_LABEL + "=" + ContainerStorageHelper.ownerIdentity(config))) + .exec()) { + Map labels = network.getLabels() != null ? network.getLabels() : Map.of(); + if (!kept.contains(labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL))) { + lifecycleManager.removeNetwork(network.getName()); + } + } + } catch (RuntimeException e) { + LOG.warnv(e, "Could not remove the HDFS networks of EMR clusters that have ended: {0}", e.getMessage()); + } try { ListVolumesResponse response = lifecycleManager.getDockerClient().listVolumesCmd() .withFilter("label", List.of(ContainerStorageHelper.COMPONENT_LABEL + "=" + COMPONENT, @@ -79,7 +484,7 @@ public class EmrClusterStorage implements ClusterStorage { } } } catch (RuntimeException e) { - LOG.warnv("Could not remove the storage of EMR clusters that have ended: {0}", e.getMessage()); + LOG.warnv(e, "Could not remove the storage of EMR clusters that have ended: {0}", e.getMessage()); } } } diff --git a/src/main/java/io/github/hectorvent/floci/services/emr/EmrHandler.java b/src/main/java/io/github/hectorvent/floci/services/emr/EmrHandler.java index 07ce1948be..49d80f754c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emr/EmrHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/emr/EmrHandler.java @@ -323,11 +323,20 @@ public class EmrHandler { || (terminated && !withinTerminatedInstanceRetention(cluster.getEndDateTime(), Instant.now()))) { return Response.ok(response).build(); } - int n = 1; + // Listed in their groups' order, the first MASTER group's instances numbered first, so the primary node keeps + // its id and address, DescribeCluster's MasterPublicDnsName, while the other groups resize, as an instance + // does; any other group's follow, each after those before it. + EmrInstanceGroup primary = cluster.getInstanceGroups().stream().filter(EmrService::isMasterGroup) + .findFirst().orElse(null); + int next = primary == null ? 1 : 1 + listedInstanceCount(primary, terminated); for (EmrInstanceGroup group : cluster.getInstanceGroups()) { int count = listedInstanceCount(group, terminated); + int first = group == primary ? 1 : next; for (int i = 0; i < count; i++) { - arr.add(syntheticInstanceNode(cluster, group, n++, terminated)); + arr.add(syntheticInstanceNode(cluster, group, first + i, terminated)); + } + if (group != primary) { + next += count; } } return Response.ok(response).build(); @@ -749,7 +758,7 @@ public class EmrHandler { node.put("Id", "ci-" + index + cluster.getId()); node.put("Ec2InstanceId", EmrService.ec2InstanceId(index)); node.put("PublicDnsName", AwsEndpoints.ec2PublicDns("203.0.113." + index, cluster.getRegion())); - String privateIp = "10.0.0." + index; + String privateIp = EmrService.privateIpAddress(index); node.put("PrivateDnsName", AwsRegions.ec2PrivateIpDnsName(privateIp, cluster.getRegion())); node.put("PrivateIpAddress", privateIp); node.put("InstanceGroupId", group.getId()); diff --git a/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java b/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java index 31b0cb1a1b..047d44babc 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java +++ b/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java @@ -8,6 +8,7 @@ import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.AwsRegions; +import io.github.hectorvent.floci.core.common.ContainerTeardown; import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.core.common.Pagination; import io.github.hectorvent.floci.core.common.RegionResolver; @@ -55,6 +56,8 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.Function; @@ -76,7 +79,7 @@ import java.util.function.Supplier; * BOOTSTRAPPING, and leave the image its steps then run in. */ @ApplicationScoped -public class EmrService implements Resettable, StoredResourceArns { +public class EmrService implements Resettable, StoredResourceArns, ContainerTeardown { private static final Logger LOG = Logger.getLogger(EmrService.class); private static final String UPPER_ALNUM = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; @@ -98,6 +101,10 @@ public class EmrService implements Resettable, StoredResourceArns { "On the master instance (%s), bootstrap action %d could not be read from %s: %s"; private static final String BOOTSTRAP_NOT_RUN = "Floci could not run the bootstrap actions: %s"; static final String BOOTSTRAP_INTERRUPTED = "Floci stopped while the cluster's bootstrap actions were running."; + // The release whose EMR Serverless Hive image runs the HDFS of a cluster of the AWS runtime for Apache Spark, + // which publishes none. Hadoop keeps its wire protocols compatible across a major version's minor releases, so + // a newer client, such as the runtime's, reaches its NameNode. + static final String SPARK_RUNTIME_HDFS_RELEASE = "emr-7.5.0"; private final AccountAwareStorageBackend clusterStore; private final StorageBackend secConfigStore; @@ -133,6 +140,12 @@ public class EmrService implements Resettable, StoredResourceArns { private final Set storageBeingRemoved = new HashSet<>(); // Raised by each reset, so a step's thread from before it writes nothing back after the wipe. private long generation; + // How many teardowns, by a reset or a shutdown, have begun: a step handed to its thread before one starts no HDFS + // and no driver after it. + private final AtomicLong teardowns = new AtomicLong(); + // From a teardown until its reset is over, no step or bootstrap is handed to a thread: a cluster a wakeup moves on + // meanwhile would start containers after the teardowns that remove them. After a shutdown's, never again. + private volatile boolean tornDown; private static final Set COMPUTE_LIMITS_UNIT_TYPES = Set.of("InstanceFleetUnits", "Instances", "VCPU"); private static final Set SCALING_STRATEGIES = Set.of("DEFAULT", "ADVANCED"); @@ -295,6 +308,28 @@ public class EmrService implements Resettable, StoredResourceArns { } } + /** + * A reset's or a shutdown's teardown has begun: a step handed to its thread before it, whose driver the runner's + * teardown cannot stop yet, starts no HDFS and no driver after it, as its progress reads it, but stops as a + * stopped driver does. This runs before the teardowns that stop containers. + */ + @Override + public synchronized void stopManagedContainers() { + teardowns.incrementAndGet(); + tornDown = true; + } + + /** A reset is over: steps and bootstraps are handed to threads again. */ + @Override + public synchronized void afterReset() { + tornDown = false; + } + + @Override + public int teardownOrder() { + return -1; + } + /** * A reset has begun: the steps' and bootstraps' threads from before it write nothing more, so the storage * wipe that follows leaves none of their clusters behind, and the images bootstrap left, and the clusters' @@ -1406,7 +1441,8 @@ public class EmrService implements Resettable, StoredResourceArns { } /** A step handed to a thread: whose it is, where, and under which reset. */ - private record StepLaunch(String accountId, String region, String clusterId, String stepId, long launchedIn) {} + private record StepLaunch(String accountId, String region, String clusterId, String stepId, long launchedIn, + long teardownsBefore) {} /** Starts each step a cluster runs on a thread of its own, which ends the step once it is done. */ private final class ContainerSteps implements EmrClusterLifecycle.StepExecution { @@ -1414,6 +1450,12 @@ public class EmrService implements Resettable, StoredResourceArns { @Override public void start(EmrCluster cluster, EmrStep step, String region) { String accountId = regionResolver.getAccountId(); + if (tornDown) { + // Left RUNNING and counted as running, as a step whose driver the teardown stopped: the reset wipes it, + // a restart fails it. + executing.add(stepKey(accountId, step.getId())); + return; + } EmrSparkSteps.HiveCommand hive = EmrSparkSteps.hive(step, cluster.getApplications(), cluster.getConfigurations(), SNAPSHOT_MAPPER); List application = hive == null ? EmrSparkSteps.application(step) : null; @@ -1427,6 +1469,14 @@ public class EmrService implements Resettable, StoredResourceArns { // which the step's thread makes, or the release's. String image = cluster.getBootstrapImage() != null ? cluster.getBootstrapImage() : imageTemplate; Supplier releaseImage = cluster.getBootstrapImage() == null ? releaseImage(cluster) : null; + // Every EMR cluster runs HDFS on its primary node, which the step's thread starts when it is not running: + // a NameNode and a DataNode, in a container of the release's Hive image, the one with HDFS's daemons. + String clusterId = cluster.getId(); + String hdfsHost = masterPrivateDnsName(cluster); + String hdfsImage = hdfsImage(cluster.getReleaseLabel()); + Function hdfs = storage == null ? null + : stopped -> clusterStorage.hdfs(clusterId, accountId, region, hdfsHost, hdfsImage, dockerNetwork, + stopped); SparkJobRunner.Job job; if (hive != null) { job = new SparkJobRunner.Job(SERVICE, step.getId(), accountId, region, cluster.getReleaseLabel(), @@ -1451,9 +1501,10 @@ public class EmrService implements Resettable, StoredResourceArns { EmrSparkSteps.hadoopLog4j(cluster.getConfigurations(), SNAPSHOT_MAPPER), EmrSparkSteps.hadoopEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER)); } - StepLaunch launch = new StepLaunch(accountId, region, cluster.getId(), step.getId(), generation); + StepLaunch launch = new StepLaunch(accountId, region, cluster.getId(), step.getId(), generation, + teardowns.get()); executing.add(stepKey(accountId, step.getId())); - stepExecutor.execute(() -> runStep(job, launch, releaseImage)); + stepExecutor.execute(() -> runStep(job, launch, releaseImage, hdfs)); } @Override @@ -1464,7 +1515,8 @@ public class EmrService implements Resettable, StoredResourceArns { // A step's thread: its driver runs to its end, or the step fails at once when Floci does not run its kind. A // cluster with Hive's image is made first, when it is not there yet, so a failure to make it fails the step. - private void runStep(SparkJobRunner.Job job, StepLaunch launch, Supplier releaseImage) { + private void runStep(SparkJobRunner.Job job, StepLaunch launch, Supplier releaseImage, + Function hdfs) { String failure; if (job == null) { failure = EmrSparkSteps.NOT_RUN; @@ -1474,15 +1526,26 @@ public class EmrService implements Resettable, StoredResourceArns { try { SparkJobRunner.Job running = releaseImage != null && !progress.cancelled() ? job.inImage(releaseImage.get()) : job; - // The cluster's storage is there before its first step's container mounts it. A step a cancel, - // its cluster's end or a reset has passed does not start, so it makes none. + // The cluster's storage is there, its HDFS running, before its first step's container mounts it. A step + // a cancel, its cluster's end or a reset has passed does not start, so it makes none. if (job.storage() != null && !progress.cancelled()) { clusterStorage.create(launch.clusterId(), launch.accountId(), launch.region()); + running = running.onStorage(hdfs.apply(progress::cancelled)); } outcome = sparkRunner.run(running, progress); + } catch (ClusterStorage.Stopped e) { + // It stopped while its HDFS started, before its driver did, as a driver stopped then would. + outcome = SparkJobRunner.Outcome.halted(); } catch (RuntimeException e) { - LOG.warnv(e, "EMR step {0} could not run", launch.stepId()); - outcome = SparkJobRunner.Outcome.couldNotStart(e.getMessage()); + if (progress.cancelled() || Thread.currentThread().isInterrupted()) { + // A teardown, a cancel or Floci's shutdown cut its start short, as it would have a driver. + LOG.warnv(e, "EMR step {0} stopped while it started, as this failed: {1}", launch.stepId(), + e.getMessage()); + outcome = SparkJobRunner.Outcome.halted(); + } else { + LOG.warnv(e, "EMR step {0} could not run", launch.stepId()); + outcome = SparkJobRunner.Outcome.couldNotStart(e.getMessage()); + } } // A reset since the step started has swept the storage and wiped its cluster, so nothing would remove // volumes made, or mounted, after its sweep: they go now, the step's container being gone. @@ -1495,11 +1558,20 @@ public class EmrService implements Resettable, StoredResourceArns { } failure = failureOf(job, outcome); } - RequestScopes.runAs(launch.accountId(), launch.region(), () -> run(() -> stepEnded(launch, failure))); + // A teardown since the step was handed off ends it as it does a driver, whatever it ran to: ending it now + // could start the next step after the teardown has passed. The service's lock orders the two. + RequestScopes.runAs(launch.accountId(), launch.region(), () -> run(() -> { + if (teardowns.get() != launch.teardownsBefore()) { + driverStopped(launch); + } else { + stepEnded(launch, failure); + } + })); } /** A cluster handed to a bootstrap thread: whose it is, where, and under which reset. */ - private record BootstrapLaunch(String accountId, String region, String clusterId, long launchedIn) {} + private record BootstrapLaunch(String accountId, String region, String clusterId, long launchedIn, + long teardownsBefore) {} /** Runs each cluster's bootstrap actions on a thread of its own, which ends its BOOTSTRAPPING. */ private final class ContainerBootstrap implements EmrClusterLifecycle.BootstrapExecution { @@ -1507,13 +1579,20 @@ public class EmrService implements Resettable, StoredResourceArns { @Override public void start(EmrCluster cluster, String region) { String accountId = regionResolver.getAccountId(); + if (tornDown) { + // Left BOOTSTRAPPING and counted as bootstrapping, as one the teardown stopped: the reset wipes it, a + // restart ends it. + bootstrapping.add(clusterKey(accountId, cluster.getId())); + return; + } // "logs//node//bootstrap-actions//stdout.gz" String logFolder = EmrServerlessSparkRunner.logFolder(cluster.getLogUri(), cluster.getId() + "/node/" + masterInstanceId(cluster) + "/bootstrap-actions/"); BootstrapRunner.Bootstrap bootstrap = new BootstrapRunner.Bootstrap(cluster.getId(), accountId, region, cluster.getReleaseLabel(), imageTemplate, dockerNetwork, instanceProfileRole(cluster, accountId), bootstrapActions(cluster), logFolder); - BootstrapLaunch launch = new BootstrapLaunch(accountId, region, cluster.getId(), generation); + BootstrapLaunch launch = new BootstrapLaunch(accountId, region, cluster.getId(), generation, + teardowns.get()); Supplier releaseImage = releaseImage(cluster); bootstrapping.add(clusterKey(accountId, cluster.getId())); stepExecutor.execute(() -> runBootstrap(bootstrap, launch, releaseImage)); @@ -1543,6 +1622,16 @@ public class EmrService implements Resettable, StoredResourceArns { return () -> releaseImages.image(release, spark, hive); } + /** + * The image a cluster runs its HDFS in: its release's EMR Serverless Hive image, which has HDFS's daemons, or, for + * a release of the AWS runtime for Apache Spark, which has no Hive image, {@link #SPARK_RUNTIME_HDFS_RELEASE}'s. + */ + private String hdfsImage(String releaseLabel) { + String release = EmrServerlessSparkRunner.sparkRuntime(releaseLabel) ? SPARK_RUNTIME_HDFS_RELEASE + : releaseLabel; + return EmrServerlessSparkRunner.image(hiveImageTemplate, release, SparkJobRunner.Engine.HIVE); + } + // A cluster's BootstrapActionConfig list, as RunJobFlow stored it once it had checked it. private static List bootstrapActions(EmrCluster cluster) { List actions = new ArrayList<>(); @@ -1565,8 +1654,9 @@ public class EmrService implements Resettable, StoredResourceArns { // removed it, before the thread ran; a failure to make it ends the cluster as one to run the bootstrap does. private void runBootstrap(BootstrapRunner.Bootstrap bootstrap, BootstrapLaunch launch, Supplier releaseImage) { - BooleanSupplier cancelled = () -> !RequestScopes.callAs(launch.accountId(), launch.region(), - () -> stillBootstrapping(launch)); + // A teardown since the bootstrap was handed off stops it as it does a step, before it runs or as it goes. + BooleanSupplier cancelled = () -> teardowns.get() != launch.teardownsBefore() + || !RequestScopes.callAs(launch.accountId(), launch.region(), () -> stillBootstrapping(launch)); BootstrapRunner.Outcome outcome; try { outcome = bootstrapRunner.run(releaseImage != null && !cancelled.getAsBoolean() @@ -1576,8 +1666,17 @@ public class EmrService implements Resettable, StoredResourceArns { outcome = BootstrapRunner.Outcome.couldNotRun(e.getMessage()); } BootstrapRunner.Outcome ended = outcome; - RequestScopes.runAs(launch.accountId(), launch.region(), - () -> run(() -> bootstrapEnded(bootstrap, launch, ended))); + // One that ended, however, after a teardown began ends as one Floci stopped, which starts no step: the + // service's lock orders the two. + AtomicBoolean tornDownSince = new AtomicBoolean(); + RequestScopes.runAs(launch.accountId(), launch.region(), () -> run(() -> { + tornDownSince.set(teardowns.get() != launch.teardownsBefore()); + bootstrapEnded(bootstrap, launch, tornDownSince.get() ? BootstrapRunner.Outcome.halted() : ended); + })); + // An image it committed as the teardown began goes, as no cluster starts from it. + if (tornDownSince.get() && ended.image() != null) { + bootstrapRunner.removeImage(ended.image()); + } } // Whether a cluster's bootstrap may still start, or go on: one that ended, or a reset removed, is past it. @@ -1638,18 +1737,26 @@ public class EmrService implements Resettable, StoredResourceArns { return "i-" + String.format("%017d", index); } - // The primary instance's: the first of the MASTER group in the order ListInstances lists them. + /** The private IPv4 address ListInstances gives a cluster's instance {@code index}, counted from 1. */ + static String privateIpAddress(int index) { + return "10.0.0." + index; + } + + // The primary instance's: the first of the MASTER group, which ListInstances numbers before the others. static String masterInstanceId(EmrCluster cluster) { - int index = 1; - for (EmrInstanceGroup group : cluster.getInstanceGroups()) { - if ("MASTER".equals(group.getInstanceGroupType())) { - return ec2InstanceId(index); - } - index += group.getRunningInstanceCount(); - } return ec2InstanceId(1); } + // The primary instance's private DNS name, as ListInstances gives it, which names the cluster's HDFS: the same + // while the other groups resize, so an hdfs:// path naming it keeps leading there. + static String masterPrivateDnsName(EmrCluster cluster) { + return AwsRegions.ec2PrivateIpDnsName(privateIpAddress(1), cluster.getRegion()); + } + + static boolean isMasterGroup(EmrInstanceGroup group) { + return "MASTER".equals(group.getInstanceGroupType()); + } + /** What a step's thread asks the service while its driver goes: a step has no timeout to report. */ private final class StepProgress implements SparkJobRunner.Progress { @@ -1671,7 +1778,8 @@ public class EmrService implements Resettable, StoredResourceArns { @Override public boolean cancelled() { - return !RequestScopes.callAs(launch.accountId(), launch.region(), () -> stillRunning(launch)); + return teardowns.get() != launch.teardownsBefore() + || !RequestScopes.callAs(launch.accountId(), launch.region(), () -> stillRunning(launch)); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunner.java b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunner.java index c79c84d0fb..fa155fab40 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunner.java +++ b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunner.java @@ -62,12 +62,13 @@ import java.util.zip.GZIPOutputStream; * are unpacked into its working directory before the driver starts. The driver's output goes to * Floci's log and, while it runs, to the run's CloudWatch log streams, when it has some; once it ends, its * standard output and error go, gzipped, to the run's log folder in Floci's S3, when it has one. An EMR step's - * container mounts its cluster's storage, where {@code hdfs://} paths, and paths without a scheme, lead, and a - * step's {@code hadoop} command, and a MapReduce job its {@code spark-submit} starts, reach Floci's S3 and run - * MapReduce in local mode, with the cluster's Hadoop configuration. A Hive run starts {@code hive} in a container of - * the release's EMR Serverless Hive image instead, with Tez in local mode in Hive's JVM, S3A on Floci's S3 and the - * Glue Data Catalog client, the image's metastore, on Floci's Glue; an EMR step's in the image of its cluster, which - * holds Spark and Hive, on its storage, with the cluster's HDFS and the cluster's own metastore. + * container mounts its cluster's storage and reaches its cluster's HDFS, where {@code hdfs://} paths, and paths + * without a scheme, lead, and a step's {@code hadoop} command, and a MapReduce job its {@code spark-submit} + * starts, reach Floci's S3 and run MapReduce in local mode, with the cluster's Hadoop configuration. A Hive run + * starts {@code hive} in a container of the release's EMR Serverless Hive image instead, with Tez in local mode in + * Hive's JVM, S3A on Floci's S3 and the Glue Data Catalog client, the image's metastore, on Floci's Glue; an EMR + * step's in the image of its cluster, which holds Spark and Hive, on its storage, with the cluster's HDFS and the + * cluster's own metastore. */ @ApplicationScoped public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardown { @@ -85,21 +86,18 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo private static final String HADOOP_LOG4J_VARIABLE = "FLOCI_HADOOP_LOG4J"; private static final String HADOOP_ENV_VARIABLE = "FLOCI_HADOOP_ENV"; private static final Pattern SHELL_NAME = Pattern.compile("[A-Za-z_][A-Za-z0-9_]*"); - // A cluster's HDFS, as Hadoop settings: hdfs:// paths, and those without a scheme ("hdfs:// (or no prefix)"), - // lead to the HDFS folder of the cluster's /mnt volume, through a view of it under the hdfs scheme, as the - // image has no HDFS of its own. - private static final String HDFS_FOLDER = "/mnt/hdfs"; - private static final List HDFS_SETTINGS = List.of( - new SparkSetting("fs.defaultFS", "hdfs:///"), - new SparkSetting("fs.hdfs.impl", "org.apache.hadoop.fs.viewfs.ViewFileSystemOverloadScheme"), - new SparkSetting("fs.viewfs.mounttable.default.linkFallback", "file://" + HDFS_FOLDER)); - // Spark's default checkpoint manager goes through Hadoop's FileContext, which refuses an hdfs:// path - // without a host, so a streaming query keeps its checkpoints through the file system instead. + // The port of a cluster's NameNode, HDFS's own default, which hdfs:// paths and those without a scheme + // ("hdfs:// (or no prefix)") reach through the cluster's primary node. + private static final int HDFS_PORT = 8020; + // Spark's default checkpoint manager goes through Hadoop's FileContext, which refuses an hdfs:// path without a + // host, though "hdfs:///path-to-data" and "/path-to-data" "would resolve to the same location in HDFS", as the + // Management Guide puts it; so a streaming query keeps its checkpoints through the file system instead. private static final SparkSetting FILE_SYSTEM_CHECKPOINTS = new SparkSetting( "spark.sql.streaming.checkpointFileManagerClass", "org.apache.spark.sql.execution.streaming.FileSystemBasedCheckpointFileManager"); // Where Hadoop's local job runner puts a job's files, -files and -archives among them: a folder of the local - // file system, whose files it then names by their path alone, which leads to the cluster's HDFS. + // file system, whose files it then names by their path alone, which leads to the cluster's HDFS (see + // localJobHdfsSettings). private static final String MAPRED_STAGING = "/tmp/hadoop/mapred/staging"; // A step's MapReduce runs in the JVM that starts it, as there is no YARN to run it on. private static final String MAPRED_SITE = "mapreduce.framework.namelocal" @@ -167,10 +165,6 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo " }", " site core-site.xml \"$" + HADOOP_SITE_VARIABLE + "\"", " site mapred-site.xml \"$" + MAPRED_SITE_VARIABLE + "\"", - // The local staging folder is a link to the same path in the HDFS folder, so a job's files are where - // their path leads. - " mkdir -p \"" + HDFS_FOLDER + MAPRED_STAGING + "\" \"$(dirname " + MAPRED_STAGING + ")\"", - " ln -sfn \"" + HDFS_FOLDER + MAPRED_STAGING + "\" " + MAPRED_STAGING, " if [ ! -s \"$hadoop_conf/log4j.properties\" ]; then", " printf '%s\\n' '" + String.join("' '", HADOOP_CONSOLE_LOG) + "' > \"$hadoop_conf/log4j.properties\"", " fi", @@ -243,15 +237,10 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo private static final List HIVE_SETTINGS = List.of( new SparkSetting("tez.local.mode", "true"), new SparkSetting("tez.am.client.am.port-range", "40000-40100")); - // On a cluster, after the HDFS settings, Hive's file system is their view of the cluster's HDFS under the viewfs - // scheme: Hive looks up the HDFS encryption zone of a path of the hdfs scheme, which only HDFS answers, as its - // shim takes that path's file system for HDFS's own, so a table Hive makes in the cluster's HDFS is at a viewfs: - // path, the folder an hdfs:// path leads to in other steps. Its metastore is the cluster's own, as "Hive records - // metastore information in a MySQL database on the primary node's file system": an embedded Derby database in - // the cluster's /mnt, whose tables DataNucleus creates on first use. A cluster's hive-site replaces them, with - // the Glue Data Catalog's client factory for one. + // On a cluster, Hive's metastore is the cluster's own, as "Hive records metastore information in a MySQL database + // on the primary node's file system": an embedded Derby database in the cluster's /mnt, whose tables DataNucleus + // creates on first use. A cluster's hive-site replaces it, with the Glue Data Catalog's client factory for one. private static final List HIVE_CLUSTER_SETTINGS = List.of( - new SparkSetting("fs.defaultFS", "viewfs:///"), new SparkSetting("hive.metastore.client.factory.class", "org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClientFactory"), new SparkSetting("javax.jdo.option.ConnectionURL", @@ -393,6 +382,10 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo if (job.storage() != null) { container.withNamedVolume(job.storage().home(), "/home/hadoop") .withNamedVolume(job.storage().mnt(), "/mnt"); + // The primary node's name leads to its HDFS, as the cluster's DNS resolves it. + if (job.storage().hdfsHost() != null) { + container.withExtraHost(job.storage().hdfsHost(), job.storage().hdfsAddress()); + } } // Hive's settings reach it as --hiveconf settings, so only a Spark job's container sets up Hadoop. if (job.storage() != null && job.engine() == Engine.SPARK) { @@ -415,6 +408,10 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo .build(); String containerId = lifecycleManager.create(spec); launch.started(containerId); + // A cluster's HDFS is on a network of its own, which only its steps join. + if (job.storage() != null && job.storage().hdfsNetwork() != null) { + lifecycleManager.connectToNetwork(containerId, job.storage().hdfsNetwork()); + } // A stop, a reset or a shutdown while the image was pulled, the trust store copied or the archives put // in is read now, before the driver starts; one before an archive or while it streams in puts in no // more of them. @@ -491,6 +488,10 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo Container::getId); for (Container container : containers) { Map labels = container.getLabels() != null ? container.getLabels() : Map.of(); + // A live EMR cluster's HDFS, which its storage keeps, carries the service's labels too. + if (Storage.HDFS_COMPONENT.equals(labels.get(ContainerStorageHelper.COMPONENT_LABEL))) { + continue; + } if (aliases.consistent(container.getId(), labels) && aliases.matches(labels, ContainerStorageHelper.OWNER_LABEL, owner)) { lifecycleManager.removeIfExists(container.getId()); @@ -564,10 +565,15 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo public static String image(String imageTemplate, String releaseLabel, Engine engine) { String template = imageTemplate != null ? imageTemplate : engine == Engine.HIVE ? HIVE_DEFAULT_IMAGE - : releaseLabel.startsWith("emr-spark-") ? SPARK_RUNTIME_DEFAULT_IMAGE : DEFAULT_IMAGE; + : sparkRuntime(releaseLabel) ? SPARK_RUNTIME_DEFAULT_IMAGE : DEFAULT_IMAGE; return template.formatted(releaseLabel); } + /** Whether {@code releaseLabel} is a release of the AWS runtime for Apache Spark, emr-spark-8.0.0 on. */ + public static boolean sparkRuntime(String releaseLabel) { + return releaseLabel.startsWith("emr-spark-"); + } + /** A driver's environment: Floci's own variables, then the job's, one of which replaces Floci's of its name. */ static List environment(List flocis, Map jobs) { Map byName = new LinkedHashMap<>(); @@ -736,7 +742,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo List settings = new ArrayList<>(hadoopSettings(job, flociEndpoint)); settings.addAll(HIVE_SETTINGS); if (job.storage() != null) { - settings.addAll(HDFS_SETTINGS); + settings.addAll(hdfsSettings(job.storage())); settings.addAll(HIVE_CLUSTER_SETTINGS); } List arguments = new ArrayList<>(); @@ -808,7 +814,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo */ static String hadoopSite(Job job, String flociEndpoint) { List settings = new ArrayList<>(hadoopSettings(job, flociEndpoint)); - settings.addAll(HDFS_SETTINGS); + settings.addAll(localJobHdfsSettings(job.storage())); List properties = new ArrayList<>(); for (SparkSetting setting : settings) { properties.add(siteProperty(setting.key(), setting.value())); @@ -916,11 +922,42 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo new SparkSetting("aws.region", job.region())); } - // Floci's settings, then the job's spark-defaults, in the order a later one wins. + // A cluster's HDFS, as Hadoop settings: its NameNode, on the cluster's primary node, which hdfs:// paths without a + // host, and paths without a scheme, lead to; none before it runs. + private static List hdfsSettings(Storage storage) { + return storage == null || storage.hdfsHost() == null ? List.of() + : List.of(new SparkSetting("fs.defaultFS", "hdfs://" + storage.hdfsHost() + ":" + HDFS_PORT)); + } + + // The cluster's HDFS for a MapReduce job in local mode, which reads the core-site.xml of the hadoop command's + // configuration, a custom JAR's in the driver included: Hadoop's JobResourceUploader copies a job's files to + // MAPRED_STAGING, on the local file system, then drops that folder's scheme, so the job looks for them at the + // same path of the cluster's HDFS. The hdfs scheme is therefore a view of the cluster's HDFS in which that one + // folder is the local one; the view names its mount table after the host alone. Spark and Hive keep HDFS's own + // client (see sparkSettings), as Hive casts an hdfs:// file system to it to look up its encryption zones. + private static List localJobHdfsSettings(Storage storage) { + List settings = new ArrayList<>(hdfsSettings(storage)); + if (!settings.isEmpty()) { + String mountTable = "fs.viewfs.mounttable." + storage.hdfsHost(); + settings.add(new SparkSetting("fs.hdfs.impl", "org.apache.hadoop.fs.viewfs.ViewFileSystemOverloadScheme")); + settings.add(new SparkSetting("fs.viewfs.overload.scheme.target.hdfs.impl", + "org.apache.hadoop.hdfs.DistributedFileSystem")); + settings.add(new SparkSetting(mountTable + ".link." + MAPRED_STAGING, "file://" + MAPRED_STAGING)); + settings.add(new SparkSetting(mountTable + ".linkFallback", + "hdfs://" + storage.hdfsHost() + ":" + HDFS_PORT)); + } + return settings; + } + + // Floci's settings, then the job's spark-defaults, in the order a later one wins. Spark's own Hadoop configuration + // takes HDFS's client back from the core-site.xml's view, for Spark and its Hive client, which writes a Hive table + // in HDFS only through it. private static List sparkSettings(Job job, String flociEndpoint) { List hadoop = new ArrayList<>(hadoopSettings(job, flociEndpoint)); - if (job.storage() != null) { - hadoop.addAll(HDFS_SETTINGS); + List hdfs = hdfsSettings(job.storage()); + hadoop.addAll(hdfs); + if (!hdfs.isEmpty()) { + hadoop.add(new SparkSetting("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem")); } List settings = new ArrayList<>(); hadoop.forEach(setting -> settings.add(new SparkSetting("spark.hadoop." + setting.key(), setting.value()))); diff --git a/src/main/java/io/github/hectorvent/floci/services/emrserverless/SparkJobRunner.java b/src/main/java/io/github/hectorvent/floci/services/emrserverless/SparkJobRunner.java index d8b722def9..690b1f7c49 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emrserverless/SparkJobRunner.java +++ b/src/main/java/io/github/hectorvent/floci/services/emrserverless/SparkJobRunner.java @@ -90,6 +90,14 @@ public interface SparkJobRunner { Map sparkLog4j2, Map mapredSite, Map hadoopLog4j, Map hadoopEnvironment) { + /** This job, on {@code storage}. */ + public Job onStorage(Storage storage) { + return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage, + dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder, + cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j, + hadoopEnvironment); + } + /** This job, run in {@code image}. */ public Job inImage(String image) { return new Job(service, runId, accountId, region, releaseLabel, engine, image, customImage, dockerNetwork, @@ -99,10 +107,29 @@ public interface SparkJobRunner { } /** - * The Docker volumes holding an EMR cluster's storage, which every one of its steps' containers mounts: - * {@code home} at {@code /home/hadoop}, and {@code mnt} at {@code /mnt}, where its HDFS is. + * An EMR cluster's storage: the Docker volumes every one of its steps' containers mounts, {@code home} at + * {@code /home/hadoop} and {@code mnt} at {@code /mnt}; and its HDFS, whose NameNode is on the cluster's + * primary node, named {@code hdfsHost}, which a step's container reaches at {@code hdfsAddress} on the Docker + * network {@code hdfsNetwork}, the cluster's own, which the container joins (all three null until it runs, the + * network also on the host's own network, which steps share with it). */ - record Storage(String home, String mnt) { + record Storage(String home, String mnt, String hdfsHost, String hdfsAddress, String hdfsNetwork) { + + /** + * The component label of an EMR cluster's HDFS container, which carries its service's labels as a driver + * does but is the cluster's storage's to keep or remove, not a driver. + */ + public static final String HDFS_COMPONENT = "emr-hdfs"; + + /** A cluster's volumes, before its HDFS runs. */ + public Storage(String home, String mnt) { + this(home, mnt, null, null, null); + } + + /** This storage, its HDFS's NameNode on {@code host}, at {@code address} on {@code network}. */ + public Storage withHdfs(String host, String address, String network) { + return new Storage(home, mnt, host, address, network); + } } /** diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 3a446034bb..8d61248acb 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -623,7 +623,7 @@ floci: runner-mode: immediate # docker = run bootstrap actions and steps in containers # docker-network: floci-network # image-template: "registry.internal/emr-serverless/spark/%s:20250425" # %s = the release label - # hive-image-template: "registry.internal/emr-serverless/hive/%s:20250425" # Hive for clusters with Hive + # hive-image-template: "registry.internal/emr-serverless/hive/%s:20250425" # every cluster's HDFS, and Hive # Remove the step drivers a previous run of this deployment left on the daemon, and the images # bootstrap actions left for clusters that are gone or have ended, when the EMR service starts. # Scoped to this deployment's own containers and images. diff --git a/src/main/resources/emr/s3-dist-cp.py b/src/main/resources/emr/s3-dist-cp.py index 00677224e3..8be9dbed58 100644 --- a/src/main/resources/emr/s3-dist-cp.py +++ b/src/main/resources/emr/s3-dist-cp.py @@ -386,8 +386,8 @@ class Copier: def write(self, dest_fs, target, sources, output_codec, recompress): """Writes sources, one after the other, to target, decompressed and compressed again when --outputCodec is given, and returns the bytes read. With --appendToLastFile they follow what target holds, through a - copy that takes its place (see replace), as neither S3 nor the cluster's HDFS, a local folder, can append - in place; the copy has a name no other file has, and goes unless it took target's place.""" + copy that takes its place (see replace), on every file system, as S3 cannot append in place; the copy has + a name no other file has, and goes unless it took target's place.""" new_path = self.jvm.org.apache.hadoop.fs.Path staged = None if self.options.get("appendToLastFile") and dest_fs.exists(target): diff --git a/src/test/java/io/github/hectorvent/floci/core/common/ContainerTeardownsTest.java b/src/test/java/io/github/hectorvent/floci/core/common/ContainerTeardownsTest.java index 9546887f3e..c8183ce42a 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/ContainerTeardownsTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/ContainerTeardownsTest.java @@ -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 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 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 resources = IntStream.range(0, 83).boxed().toList(); diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerNetworkTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerNetworkTest.java index e0379d37fe..97933d69e9 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerNetworkTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerNetworkTest.java @@ -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); } diff --git a/src/test/java/io/github/hectorvent/floci/services/emr/EmrClusterStorageTest.java b/src/test/java/io/github/hectorvent/floci/services/emr/EmrClusterStorageTest.java new file mode 100644 index 0000000000..39a9f83913 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/emr/EmrClusterStorageTest.java @@ -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> 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(" ", + "\"dfs.namenode.rpc-bind-host$FLOCI_HDFS_BIND\"", + "\"dfs.namenode.http-address$FLOCI_HDFS_BIND:9870\"", + "\"dfs.datanode.address$FLOCI_HDFS_BIND:9866\"", + "\"dfs.datanode.http.address$FLOCI_HDFS_BIND:9864\"", + "\"dfs.datanode.ipc.address" + + "$FLOCI_HDFS_BIND:9867\"")))); + 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 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 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 starting = steps.submit( + () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", NOT_STOPPED)); + assertTrue(firstLooked.await(10, TimeUnit.SECONDS)); + Future 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> 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> secondLooks = ContainerExecStubs.completeEveryExec(docker, hdfsName, 1L, "", ""); + CountDownLatch firstLooks = new CountDownLatch(1); + AtomicReference 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 first = steps.submit( + () -> timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED)); + assertTrue(firstLooks.await(10, TimeUnit.SECONDS)); + Future 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 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 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 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) { + 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) { + 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; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/emr/EmrDockerRunnerDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/emr/EmrDockerRunnerDockerIntegrationTest.java index 5c9acb0de8..33ad8731b6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/emr/EmrDockerRunnerDockerIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/emr/EmrDockerRunnerDockerIntegrationTest.java @@ -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", """ diff --git a/src/test/java/io/github/hectorvent/floci/services/emr/EmrHiveStepsDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/emr/EmrHiveStepsDockerIntegrationTest.java index 21c3af692f..7f4fa13a6b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/emr/EmrHiveStepsDockerIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/emr/EmrHiveStepsDockerIntegrationTest.java @@ -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")); diff --git a/src/test/java/io/github/hectorvent/floci/services/emr/EmrResizeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/emr/EmrResizeIntegrationTest.java index 190c732561..bf7539502f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/emr/EmrResizeIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/emr/EmrResizeIntegrationTest.java @@ -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); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/emr/EmrServiceContainerStepsTest.java b/src/test/java/io/github/hectorvent/floci/services/emr/EmrServiceContainerStepsTest.java index 438964b7dd..cc3a145377 100644 --- a/src/test/java/io/github/hectorvent/floci/services/emr/EmrServiceContainerStepsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/emr/EmrServiceContainerStepsTest.java @@ -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 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 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 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(); diff --git a/src/test/java/io/github/hectorvent/floci/services/emr/EmrServiceFixture.java b/src/test/java/io/github/hectorvent/floci/services/emr/EmrServiceFixture.java index fbf4354903..e8ef689fc2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/emr/EmrServiceFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/emr/EmrServiceFixture.java @@ -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 created = new ArrayList<>(); + // Each HDFS started: its cluster, primary node's host name, image and Docker network. + final List> hdfs = new ArrayList<>(); + RuntimeException hdfsFailure; + // Runs as each HDFS starts, with what tells it the step is past starting. + Consumer whileStartingHdfs = stopped -> { }; final List removed = new ArrayList<>(); final List> 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); diff --git a/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunnerTest.java b/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunnerTest.java index aafb2d69d4..039f7375c6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunnerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunnerTest.java @@ -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 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", - "fs.defaultFShdfs:///", - "fs.hdfs.implorg.apache.hadoop.fs.viewfs.ViewFileSystemOverloadScheme" - + "", - "fs.viewfs.mounttable.default.linkFallbackfile:///mnt/hdfs" - + "")))); + verify(spec).withEnv(eq("FLOCI_HADOOP_SITE"), argThat(site -> site.contains( + "fs.defaultFShdfs://ip-10-0-0-1.ec2.internal:8020") + && site.endsWith("fs.viewfs.mounttable.ip-10-0-0-1.ec2.internal.linkFallback" + + "hdfs://ip-10-0-0-1.ec2.internal:8020"))); 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", "mapreduce.framework.namelocal" + "mapreduce.jobtracker.staging.root.dir" + "/tmp/hadoop/mapred/staging"); - 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 { "aws.glue.endpointhttp://floci:4566", "hive.metastore.glue.catalogid123456789012", "aws.regioneu-west-1", - "fs.defaultFShdfs:///", + "fs.defaultFShdfs://ip-10-0-0-1.ec2.internal:8020", "fs.hdfs.implorg.apache.hadoop.fs.viewfs.ViewFileSystemOverloadScheme" + "", - "fs.viewfs.mounttable.default.linkFallbackfile:///mnt/hdfs" - + "", + "fs.viewfs.overload.scheme.target.hdfs.impl" + + "org.apache.hadoop.hdfs.DistributedFileSystem", + "fs.viewfs.mounttable.ip-10-0-0-1.ec2.internal.link./tmp/hadoop/mapred/staging" + + "file:///tmp/hadoop/mapred/staging", + "fs.viewfs.mounttable.ip-10-0-0-1.ec2.internal.linkFallback" + + "hdfs://ip-10-0-0-1.ec2.internal:8020", "fs.permissions.umask-mode077", "floci.notea<b & "c" 'd'"), 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) {