diff --git a/docs/services/emr.md b/docs/services/emr.md index 1ebdf36a1e..9ba245dcd8 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -112,7 +112,7 @@ one container per step from the cluster's release image, the one EMR Serverless' (`public.ecr.aws/emr-serverless/spark/`), and runs the step in it: a Spark step's `spark-submit` in local mode, the container holding the driver and its executors, or a command or a script. The cluster itself gets no container, and goes through its lifecycle as in the `immediate` mode, -but for its bootstrap actions. +but for its bootstrap actions and its storage. * **Which steps run**: a `command-runner.jar` step whose first argument is `spark-submit`, the way the Management Guide writes Spark steps, runs the arguments after it, without its `--master` and @@ -127,10 +127,30 @@ but for its bootstrap actions. 3, Java, `curl` and the AWS CLI v2, which reaches Floci through `AWS_ENDPOINT_URL`. A `script-runner.jar` step's script is fetched from S3 with the AWS CLI and the step's credentials, then run with the step's other arguments; a path not in S3 is run as it is, a bare name from `/home/hadoop` - when a file there has it, though nothing a former step wrote is there, each step having a container of - its own. A `spark-submit` they start runs in local mode on Floci's S3 with the cluster's - `spark-defaults` and `spark-hive-site`, which Floci puts in a Spark configuration of its own, ahead of the image's EMR - Serverless master; its own `--master yarn` or `--deploy-mode cluster` fails, as there is no YARN. + when a file there has it, one a former step left there included. `hadoop fs` and `hdfs dfs` reach the + cluster's HDFS (see **Storage**). A `spark-submit` they start runs in local mode on Floci's S3 with the + cluster's `spark-defaults` and `spark-hive-site`, which Floci puts in a Spark configuration of its own, + 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` 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; 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, `hadoop fs -ls /` fails ("URI scheme is not "file""), where + `-ls -d /` and a folder below it do not, and `hadoop fs` does not reach S3, as its classpath has no AWS + SDK v2 and the image's EMRFS is not pointed at Floci (`aws s3 cp` does). `/tmp` is each container's own. * **HTTPS**: with [TLS](../configuration/tls.md) on, each step's container, and the bootstrap actions' one, also gets Floci's CA bundle as a Java trust store, which every JVM in it uses, as an [EMR Serverless job run](emr-serverless.md#running-spark-job-runs)'s do, so Java code reaches Floci @@ -183,8 +203,9 @@ but for its bootstrap actions. for the Glue Data Catalog applies; a `spark.hadoop.` setting in `spark-defaults` wins over the same one in `spark-hive-site`. `s3://` and `s3a://` paths reach Floci's S3 through S3A, on releases before 7.10.0 too, where `s3://` would otherwise be EMRFS, so the application and its files can be read - from there; the Glue Data Catalog client is pointed at Floci's Glue. A step's `Properties` are not - applied, nor are the other classifications (`core-site`, `hadoop-env`, `spark-log4j2` and the rest). + from there; the Glue Data Catalog client is pointed at Floci's Glue, and `hdfs://` paths, and those + without a scheme, at the cluster's HDFS. A step's `Properties` are not applied, nor are the other + classifications (`core-site`, `hadoop-env`, `spark-log4j2` and the rest). * **`spark-env`**: the variables the cluster's `spark-env` exports, in its nested `export` classification, are in each step's container environment, `PYSPARK_PYTHON` or `JAVA_HOME` say, replacing any of Floci's own with the same name. They are set as given, with no shell expansion of a `$VARIABLE` in 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 new file mode 100644 index 0000000000..dd74c4ab33 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/emr/ClusterStorage.java @@ -0,0 +1,32 @@ +package io.github.hectorvent.floci.services.emr; + +import io.github.hectorvent.floci.services.emrserverless.SparkJobRunner; + +import java.util.Set; + +/** + * A cluster's storage in the EMR {@code docker} runner mode: the disks of its primary node, which every one of + * its steps' containers mounts, so what a step leaves in {@code /home/hadoop}, or in HDFS, is there for the + * next, until the cluster ends ("HDFS is ephemeral storage that is reclaimed when you terminate a cluster"). + * {@link EmrClusterStorage} is the Docker implementation, and a test supplies its own. + */ +public interface ClusterStorage { + + /** The volumes holding {@code clusterId}'s storage, whether or not they are there yet. */ + SparkJobRunner.Storage volumes(String clusterId); + + /** Makes the volumes of {@code clusterId}'s storage, in its account and Region, when they are not there. */ + 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. + */ + boolean remove(String clusterId); + + /** + * Removes the storage of every cluster of this deployment but those in {@code kept}, by id: after a + * restart, the storage of the clusters that are gone or have ended, and on a reset all of it. + */ + void removeAllBut(Set kept); +} 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 new file mode 100644 index 0000000000..dd706d1c85 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/emr/EmrClusterStorage.java @@ -0,0 +1,85 @@ +package io.github.hectorvent.floci.services.emr; + +import com.github.dockerjava.api.command.InspectVolumeResponse; +import com.github.dockerjava.api.command.ListVolumesResponse; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager; +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.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * 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. + */ +@ApplicationScoped +public class EmrClusterStorage implements ClusterStorage { + + private static final Logger LOG = Logger.getLogger(EmrClusterStorage.class); + private static final String SERVICE = "emr"; + private static final String COMPONENT = "emr-storage"; + + private final ContainerLifecycleManager lifecycleManager; + private final EmulatorConfig config; + + @Inject + public EmrClusterStorage(ContainerLifecycleManager lifecycleManager, EmulatorConfig config) { + this.lifecycleManager = lifecycleManager; + this.config = config; + } + + @Override + public SparkJobRunner.Storage volumes(String clusterId) { + return new SparkJobRunner.Storage( + ContainerStorageHelper.dockerName(config, SERVICE + "-" + clusterId + "-home"), + ContainerStorageHelper.dockerName(config, SERVICE + "-" + clusterId + "-mnt")); + } + + @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)); + SparkJobRunner.Storage storage = volumes(clusterId); + lifecycleManager.ensureVolume(storage.home(), labels); + lifecycleManager.ensureVolume(storage.mnt(), labels); + } + + @Override + public boolean remove(String clusterId) { + SparkJobRunner.Storage storage = volumes(clusterId); + // Both are tried, so one Docker refused does not keep the other. + boolean homeGone = lifecycleManager.removeVolume(storage.home()); + return lifecycleManager.removeVolume(storage.mnt()) && homeGone; + } + + @Override + public void removeAllBut(Set kept) { + try { + ListVolumesResponse response = lifecycleManager.getDockerClient().listVolumesCmd() + .withFilter("label", List.of(ContainerStorageHelper.COMPONENT_LABEL + "=" + COMPONENT, + ContainerStorageHelper.OWNER_LABEL + "=" + ContainerStorageHelper.ownerIdentity(config))) + .exec(); + List volumes = response != null && response.getVolumes() != null + ? response.getVolumes() : List.of(); + for (InspectVolumeResponse volume : volumes) { + Map labels = volume.getLabels() != null ? volume.getLabels() : Map.of(); + if (!kept.contains(labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL))) { + lifecycleManager.removeVolume(volume.getName()); + } + } + } catch (RuntimeException e) { + LOG.warnv("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/EmrService.java b/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java index fdaa9c8d41..03330f2627 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 @@ -111,6 +111,7 @@ public class EmrService implements Resettable { // The docker runner mode's; null in the immediate one. private final SparkJobRunner sparkRunner; private final BootstrapRunner bootstrapRunner; + private final ClusterStorage clusterStorage; private final Executor stepExecutor; private final IamService iamService; // Where a step's driver runs: image-template, with the release label for %s, and docker-network; null when @@ -124,6 +125,8 @@ public class EmrService implements Resettable { // The images of ended clusters a thread is removing. A cluster names its image until it is gone, so one // Docker refused to remove is tried again the next time the cluster is read or stored. private final Set imagesBeingRemoved = new HashSet<>(); + // Likewise the clusters, by account and id, whose storage a thread is removing. + 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; @@ -188,24 +191,26 @@ public class EmrService implements Resettable { @Inject public EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver, EmrEventPublisher eventPublisher, EmrServerlessSparkRunner sparkRunner, - EmrBootstrapRunner bootstrapRunner, IamService iamService) { + EmrBootstrapRunner bootstrapRunner, EmrClusterStorage clusterStorage, IamService iamService) { this(storageFactory, config, regionResolver, eventPublisher, Clock.systemUTC(), Wakeups.timer(Clock.systemUTC()), RUNNER_DOCKER.equalsIgnoreCase(config.services().emr().runnerMode()) ? sparkRunner : null, RUNNER_DOCKER.equalsIgnoreCase(config.services().emr().runnerMode()) ? bootstrapRunner : null, + RUNNER_DOCKER.equalsIgnoreCase(config.services().emr().runnerMode()) ? clusterStorage : null, Executors.newCachedThreadPool(Thread.ofPlatform().daemon().name("emr-step-", 0).factory()), iamService); } EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver, EmrEventPublisher eventPublisher, Clock clock, Wakeups wakeups) { - this(storageFactory, config, regionResolver, eventPublisher, clock, wakeups, null, null, Runnable::run, + this(storageFactory, config, regionResolver, eventPublisher, clock, wakeups, null, null, null, Runnable::run, null); } EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver, EmrEventPublisher eventPublisher, Clock clock, Wakeups wakeups, SparkJobRunner sparkRunner, - BootstrapRunner bootstrapRunner, Executor stepExecutor, IamService iamService) { + BootstrapRunner bootstrapRunner, ClusterStorage clusterStorage, Executor stepExecutor, + IamService iamService) { this.clusterStore = storageFactory.create("emr", "emr-clusters.json", new TypeReference>() {}); this.secConfigStore = storageFactory.create("emr", "emr-security-configs.json", @@ -217,6 +222,7 @@ public class EmrService implements Resettable { this.defaultReleaseLabel = config.services().emr().defaultReleaseLabel(); this.sparkRunner = sparkRunner; this.bootstrapRunner = bootstrapRunner; + this.clusterStorage = clusterStorage; this.stepExecutor = stepExecutor; this.iamService = iamService; this.imageTemplate = config.services().emr().imageTemplate().orElse(null); @@ -237,8 +243,10 @@ public class EmrService implements Resettable { // After a restart, a stored cluster with a change still to come wakes the service as before, and one // with a step a container ran, or bootstrap actions, which no thread runs any more, wakes it at once to // fail them. The images bootstrap left for clusters that are gone, or have ended, go first: a wakeup - // runs on the timer's thread, and a cluster it moved on could keep an image the sweep never knew of. + // runs on the timer's thread, and a cluster it moved on could keep an image the sweep never knew of. The + // storage of the clusters that are gone, or have ended, goes then too. Set imagesInUse = new HashSet<>(); + Set clustersUp = new HashSet<>(); List wakeAtStart = new ArrayList<>(); for (AccountAwareStorageBackend.AccountEntry entry : clusterStore.scanAllAccountEntries(k -> true)) { @@ -252,10 +260,16 @@ public class EmrService implements Resettable { if (cluster.getBootstrapImage() != null && !EmrClusterLifecycle.isTerminated(cluster.getState())) { imagesInUse.add(cluster.getBootstrapImage()); } + if (!EmrClusterLifecycle.isTerminated(cluster.getState())) { + clustersUp.add(cluster.getId()); + } } if (bootstrapRunner != null && config.services().emr().reconcileContainersOnStartup()) { bootstrapRunner.removeImages(imagesInUse); } + if (clusterStorage != null && config.services().emr().reconcileContainersOnStartup()) { + clusterStorage.removeAllBut(clustersUp); + } wakeAtStart.forEach(Runnable::run); } @@ -275,8 +289,8 @@ public class EmrService implements Resettable { /** * 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 go with them. Its - * teardown has already stopped their containers. + * wipe that follows leaves none of their clusters behind, and the images bootstrap left, and the clusters' + * own storage, go with them. Its teardown has already stopped their containers. */ @Override public synchronized void beforeReset() { @@ -286,6 +300,9 @@ public class EmrService implements Resettable { if (bootstrapRunner != null) { bootstrapRunner.removeImages(Set.of()); } + if (clusterStorage != null) { + clusterStorage.removeAllBut(Set.of()); + } } @Override @@ -1136,7 +1153,7 @@ public class EmrService implements Resettable { if (changed) { clusterStore.put(cluster.getId(), cluster); } - releaseBootstrapImage(cluster); + releaseEnded(cluster); wakeForNextChange(cluster); return cluster; } @@ -1156,6 +1173,17 @@ public class EmrService implements Resettable { return EmrClusterLifecycle.BOOTSTRAPPING.equals(cluster.getState()) && cluster.isBootstrapInContainer(); } + // What an ended cluster kept goes once no step of it still runs in a container: its bootstrap's image and + // its storage. + private void releaseEnded(EmrCluster cluster) { + releaseBootstrapImage(cluster); + releaseStorage(cluster); + } + + private boolean stepsExecuting(EmrCluster cluster, String accountId) { + return cluster.getSteps().stream().anyMatch(step -> executing.contains(stepKey(accountId, step.getId()))); + } + /** * Once a cluster has ended and no step of it still runs in a container, the image its bootstrap left * goes, off the service's lock. The cluster names it until it is gone, and while a thread removes it, it @@ -1167,8 +1195,7 @@ public class EmrService implements Resettable { return; } String accountId = regionResolver.getAccountId(); - if (cluster.getSteps().stream().anyMatch(step -> executing.contains(stepKey(accountId, step.getId()))) - || !imagesBeingRemoved.add(image)) { + if (stepsExecuting(cluster, accountId) || !imagesBeingRemoved.add(image)) { return; } String clusterId = cluster.getId(); @@ -1191,6 +1218,41 @@ public class EmrService implements Resettable { }); } + /** + * Once a cluster has ended and no step of it still runs in a container, its storage goes, off the service's + * lock, as its bootstrap's image does: the cluster keeps it until it is gone, and while a thread removes it, + * it is not removed again. + */ + private void releaseStorage(EmrCluster cluster) { + if (!cluster.isStorageCreated() || clusterStorage == null + || !EmrClusterLifecycle.isTerminated(cluster.getState())) { + return; + } + String accountId = regionResolver.getAccountId(); + String key = clusterKey(accountId, cluster.getId()); + if (stepsExecuting(cluster, accountId) || !storageBeingRemoved.add(key)) { + return; + } + String clusterId = cluster.getId(); + String region = regionOf(cluster); + stepExecutor.execute(() -> { + boolean gone = clusterStorage.remove(clusterId); + RequestScopes.runAs(accountId, region, () -> run(() -> storageRemoved(clusterId, key, gone))); + }); + } + + // A thread's removal of a cluster's storage has ended: the cluster keeps it no more once it is gone. + private void storageRemoved(String clusterId, String key, boolean gone) { + storageBeingRemoved.remove(key); + if (!gone) { + return; + } + clusterStore.get(clusterId).filter(EmrCluster::isStorageCreated).ifPresent(cluster -> { + cluster.setStorageCreated(false); + clusterStore.put(clusterId, cluster); + }); + } + private boolean failInterruptedSteps(EmrCluster cluster) { if (sparkRunner == null) { return false; @@ -1260,8 +1322,8 @@ public class EmrService implements Resettable { EmrStep step = found.flatMap(cluster -> cluster.getSteps().stream() .filter(candidate -> launch.stepId().equals(candidate.getId())).findFirst()).orElse(null); if (step == null || !EmrClusterLifecycle.RUNNING.equals(step.getState())) { - // A step of a cluster that has ended no longer runs: the cluster's image may go with it, its last one. - found.ifPresent(this::releaseBootstrapImage); + // A step of a cluster that has ended no longer runs: what the cluster kept may go with it, its last one. + found.ifPresent(this::releaseEnded); return; } EmrCluster cluster = found.get(); @@ -1279,7 +1341,7 @@ public class EmrService implements Resettable { private void driverStopped(StepLaunch launch) { if (!stillRunning(launch)) { executing.remove(stepKey(launch.accountId(), launch.stepId())); - clusterStore.get(launch.clusterId()).ifPresent(this::releaseBootstrapImage); + clusterStore.get(launch.clusterId()).ifPresent(this::releaseEnded); } } @@ -1304,6 +1366,10 @@ public class EmrService implements Resettable { && EmrClusterLifecycle.RUNNING.equals(step.getState())); } + private synchronized boolean resetSince(StepLaunch launch) { + return launch.launchedIn() != generation; + } + /** 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) {} @@ -1315,6 +1381,11 @@ public class EmrService implements Resettable { String accountId = regionResolver.getAccountId(); List application = EmrSparkSteps.application(step); List command = application == null ? EmrSparkSteps.command(step) : null; + SparkJobRunner.Storage storage = null; + if ((application != null || command != null) && clusterStorage != null) { + storage = clusterStorage.volumes(cluster.getId()); + cluster.setStorageCreated(true); + } SparkJobRunner.Job job = application == null && command == null ? null : new SparkJobRunner.Job(SERVICE, step.getId(), accountId, region, cluster.getReleaseLabel(), cluster.getBootstrapImage() != null ? cluster.getBootstrapImage() : imageTemplate, null, @@ -1322,7 +1393,8 @@ public class EmrService implements Resettable { EmrSparkSteps.sparkDefaults(cluster.getConfigurations(), SNAPSHOT_MAPPER), application != null ? application : List.of(), command, Duration.ZERO, EmrSparkSteps.logFolder(cluster, step), null, - EmrSparkSteps.sparkEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER), List.of()); + EmrSparkSteps.sparkEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER), List.of(), + storage); StepLaunch launch = new StepLaunch(accountId, region, cluster.getId(), step.getId(), generation); executing.add(stepKey(accountId, step.getId())); stepExecutor.execute(() -> runStep(job, launch)); @@ -1341,12 +1413,23 @@ public class EmrService implements Resettable { failure = EmrSparkSteps.NOT_RUN; } else { SparkJobRunner.Outcome outcome; + StepProgress progress = new StepProgress(launch); try { - outcome = sparkRunner.run(job, new StepProgress(launch)); + // 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. + if (job.storage() != null && !progress.cancelled()) { + clusterStorage.create(launch.clusterId(), launch.accountId(), launch.region()); + } + outcome = sparkRunner.run(job, progress); } catch (RuntimeException e) { 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. + if (job.storage() != null && resetSince(launch)) { + clusterStorage.remove(launch.clusterId()); + } if (outcome.stopped()) { RequestScopes.runAs(launch.accountId(), launch.region(), () -> run(() -> driverStopped(launch))); return; @@ -1514,7 +1597,7 @@ public class EmrService implements Resettable { /** Stores a cluster a call changed, once every change that falls due by now is made. */ private void store(EmrCluster cluster) { lifecycle.advance(cluster, now(), regionOf(cluster)); - releaseBootstrapImage(cluster); + releaseEnded(cluster); clusterStore.put(cluster.getId(), cluster); wakeForNextChange(cluster); } diff --git a/src/main/java/io/github/hectorvent/floci/services/emr/model/EmrCluster.java b/src/main/java/io/github/hectorvent/floci/services/emr/model/EmrCluster.java index ba3c918250..84e8dac9ac 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emr/model/EmrCluster.java +++ b/src/main/java/io/github/hectorvent/floci/services/emr/model/EmrCluster.java @@ -51,6 +51,9 @@ public class EmrCluster { // its steps run in; Floci's own, as the API has neither. private boolean bootstrapInContainer; private String bootstrapImage; + // Whether the docker runner mode has made the cluster's storage, which goes once the cluster has ended; Floci's + // own, as the API has none. + private boolean storageCreated; // The cluster's ManagedScalingPolicy and AutoTerminationPolicy as given, raw JSON; null when none. private String managedScalingPolicy; private String autoTerminationPolicy; @@ -177,6 +180,9 @@ public class EmrCluster { public String getBootstrapImage() { return bootstrapImage; } public void setBootstrapImage(String bootstrapImage) { this.bootstrapImage = bootstrapImage; } + public boolean isStorageCreated() { return storageCreated; } + public void setStorageCreated(boolean storageCreated) { this.storageCreated = storageCreated; } + public String getManagedScalingPolicy() { return managedScalingPolicy; } public void setManagedScalingPolicy(String managedScalingPolicy) { this.managedScalingPolicy = managedScalingPolicy; } diff --git a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessJobRunService.java b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessJobRunService.java index e0bd9e10c0..3c1d376027 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessJobRunService.java +++ b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessJobRunService.java @@ -494,7 +494,8 @@ public class EmrServerlessJobRunService implements Resettable { SparkJobRunner.Job job = new SparkJobRunner.Job(SERVICE, run.getJobRunId(), arn.accountId(), arn.region(), run.getReleaseLabel(), imageTemplate, customImage(app), dockerNetwork, run.getExecutionRole(), sparkDefaults, application(sparkSubmit), null, timeout, driverLogFolder(app, run), - driverCloudWatchLogs(app, run), driverEnvironment(sparkProperties), archives(sparkProperties)); + driverCloudWatchLogs(app, run), driverEnvironment(sparkProperties), archives(sparkProperties), + null); executing.add(run.getJobRunId()); long launchedIn = generation; runExecutor.execute(() -> execute(job, launchedIn)); 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 406090f8e1..bd255affc8 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 @@ -57,7 +57,8 @@ import java.util.zip.GZIPOutputStream; * trusts Floci's CA, through the Java trust store copied in before it starts, and the run's archives in S3 * 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. + * 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. */ @ApplicationScoped public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardown { @@ -65,6 +66,24 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo private static final Logger LOG = Logger.getLogger(EmrServerlessSparkRunner.class); private static final String SPARK_SUBMIT = "/usr/lib/spark/bin/spark-submit"; private static final String SPARK_DEFAULTS_VARIABLE = "FLOCI_SPARK_DEFAULTS"; + private static final String HADOOP_SITE_VARIABLE = "FLOCI_HADOOP_SITE"; + // 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 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:///mnt/hdfs")); + // 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. + private static final SparkSetting FILE_SYSTEM_CHECKPOINTS = new SparkSetting( + "spark.sql.streaming.checkpointFileManagerClass", + "org.apache.spark.sql.execution.streaming.FileSystemBasedCheckpointFileManager"); + // HDFS_SETTINGS as core-site.xml properties, for the hadoop command; none needs escaping. + private static final String HADOOP_SITE = String.join("\n", HDFS_SETTINGS.stream() + .map(setting -> "" + setting.key() + "" + setting.value() + + "") + .toList()); // A command runs after this sets up a Spark configuration of its own, so a spark-submit it starts runs // locally on Floci's S3: the image's spark-defaults.conf names EMR Serverless's resource manager as its // master, which a system property cannot override, so its master and that manager's lines give way to @@ -78,6 +97,30 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo + " -e '/^spark\\.submit\\.customResourceManager/d' \"$conf/spark-defaults.conf\"", "printf '%s\\n' \"$" + SPARK_DEFAULTS_VARIABLE + "\" >> \"$conf/spark-defaults.conf\"", "export SPARK_CONF_DIR=\"$conf\"", + // On a cluster, the hadoop command gets its HDFS too, through a copy of its Hadoop configuration (the + // image's, or the folder a spark-env export names), links followed, whose core-site.xml takes in the + // original's through Hadoop's XInclude, whatever its XML, then HADOOP_SITE_VARIABLE's properties, which + // win. Its script runs only once its HDFS, MapReduce and YARN homes name folders that are there, and the + // image has /usr/lib/hadoop alone. The image's hdfs command cannot run, so hdfs dfs runs as hadoop fs. + "if [ -n \"${" + HADOOP_SITE_VARIABLE + ":-}\" ]; then", + " hadoop_conf=/tmp/floci-hadoop-conf source_conf=\"${HADOOP_CONF_DIR:-/etc/hadoop/conf}\"", + " mkdir -p \"$hadoop_conf\" /tmp/floci-bin", + " cp -rL \"$source_conf/.\" \"$hadoop_conf\" 2>/dev/null", + " include=", + " if [ -f \"$hadoop_conf/core-site.xml\" ]; then", + " mv \"$hadoop_conf/core-site.xml\" \"$hadoop_conf/floci-original-core-site.xml\"", + " include=''", + " fi", + " printf '%s\\n' '' \"$include\" \"$" + + HADOOP_SITE_VARIABLE + "\" '' > \"$hadoop_conf/core-site.xml\"", + " printf '%s\\n' '#!/bin/bash' 'if [ \"$1\" = dfs ]; then shift; exec hadoop fs \"$@\"; fi'" + + " 'echo \"hdfs $1: only hdfs dfs runs here, as hadoop fs\" >&2' 'exit 1' > /tmp/floci-bin/hdfs", + " chmod +x /tmp/floci-bin/hdfs", + " export HADOOP_CONF_DIR=\"$hadoop_conf\" PATH=\"/tmp/floci-bin:$PATH\"", + " export HADOOP_HDFS_HOME=\"${HADOOP_HDFS_HOME:-/usr/lib/hadoop}\"", + " export HADOOP_MAPRED_HOME=\"${HADOOP_MAPRED_HOME:-/usr/lib/hadoop}\"", + " export HADOOP_YARN_HOME=\"${HADOOP_YARN_HOME:-/usr/lib/hadoop}\"", + "fi", "exec \"$@\""); // The archives a driver needs in its working directory are put in this folder of its container, each in a // numbered folder of its own, which the copy creates. @@ -186,6 +229,13 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo container.withEntrypoint(unpackingFirst(archives, List.of("/bin/bash", "-c", COMMAND_WRAPPER, "floci"))) .withCmd(job.command()) .withEnv(SPARK_DEFAULTS_VARIABLE, sparkDefaultsFile(job, endpoint)); + if (job.storage() != null) { + container.withEnv(HADOOP_SITE_VARIABLE, HADOOP_SITE); + } + } + if (job.storage() != null) { + container.withNamedVolume(job.storage().home(), "/home/hadoop") + .withNamedVolume(job.storage().mnt(), "/mnt"); } ContainerSpec spec = container .withDockerNetwork(Optional.ofNullable(job.dockerNetwork())) @@ -473,8 +523,9 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo /** * {@code spark-submit}'s arguments: local mode, S3A on Floci's S3 for {@code s3://} and {@code s3a://} - * paths, then the run's {@code spark-defaults} and its own options, which win over what comes before - * them, then its application and that application's arguments. Before release 7.10.0 + * paths, the cluster's HDFS for {@code hdfs://} paths and those without a scheme on a step, then the run's + * {@code spark-defaults} and its own options, which win over what comes before them, then its + * application and that application's arguments. Before release 7.10.0 * {@code s3://} is EMRFS, which ignores the endpoint setting, so it is switched to S3A. S3A writes * are committed through commit data the writer keeps in memory, without which EMR's committer finds * none and a write is silently lost. @@ -532,6 +583,11 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo new SparkSetting("spark.hadoop.fs.AbstractFileSystem.s3.impl", "org.apache.hadoop.fs.s3a.S3A"), new SparkSetting("spark.hadoop.aws.glue.endpoint", flociEndpoint), new SparkSetting("spark.hadoop.aws.region", job.region()))); + if (job.storage() != null) { + HDFS_SETTINGS.forEach(setting -> settings.add(new SparkSetting("spark.hadoop." + setting.key(), + setting.value()))); + settings.add(FILE_SYSTEM_CHECKPOINTS); + } job.sparkDefaults().forEach((key, value) -> settings.add(new SparkSetting(key, value))); return settings; } 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 87f98cc5d5..f3885996da 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 @@ -63,15 +63,22 @@ public interface SparkJobRunner { * {@code stderr.gz} go to once it ends, ending in a slash (null for none); where in CloudWatch Logs * its driver's output goes while it runs (null for nowhere but Floci's log); the environment variables * its container gets besides Floci's own, which they replace where a name is the same (empty for none); - * and its {@code spark.archives}, each a path with, after a {@code #}, the directory it is unpacked to, - * of which those in S3 are unpacked into the container's working directory before the driver starts - * (empty for none). + * its {@code spark.archives}, each a path with, after a {@code #}, the directory it is unpacked to, of + * which those in S3 are unpacked into the container's working directory before the driver starts (empty + * for none); and the storage of the cluster it runs on (null for none, as for an EMR Serverless run). */ record Job(String service, String runId, String accountId, String region, String releaseLabel, String imageTemplate, String customImage, String dockerNetwork, String executionRole, Map sparkDefaults, List application, List command, Duration timeout, String logFolder, CloudWatchLogs cloudWatchLogs, Map environment, - List archives) { + List archives, Storage storage) { + } + + /** + * 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. + */ + record Storage(String home, String mnt) { } /** 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 aecf8e6570..1b5d1430db 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 @@ -30,10 +30,13 @@ import static io.github.hectorvent.floci.services.emr.EmrServiceFixture.ACCOUNT; import static io.github.hectorvent.floci.services.emr.EmrServiceFixture.REGION; import static io.github.hectorvent.floci.services.emr.EmrServiceFixture.cluster; 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.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -97,6 +100,8 @@ 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(List.of(cluster.getId()), fixture.clusterStorage.created); } @Test @@ -446,21 +451,23 @@ class EmrServiceContainerStepsTest { } @Test - void leftoverDriversAndBootstrapImagesAreRemovedWhenTheServiceStartsUnlessReconcilingIsOff() { + void leftoverDriversBootstrapImagesAndStorageAreRemovedWhenTheServiceStartsUnlessReconcilingIsOff() { for (boolean reconcile : List.of(true, false)) { EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); when(config.services().emr().runnerMode()).thenReturn("docker"); when(config.services().emr().reconcileContainersOnStartup()).thenReturn(reconcile); EmrServerlessSparkRunner sparkRunner = mock(EmrServerlessSparkRunner.class); EmrBootstrapRunner bootstrapRunner = mock(EmrBootstrapRunner.class); + EmrClusterStorage clusterStorage = mock(EmrClusterStorage.class); RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT); new EmrService(new InMemoryStorageFactory(ACCOUNT), config, regionResolver, new EmrEventPublisher(mock(EventBridgeService.class), new ObjectMapper(), regionResolver), - sparkRunner, bootstrapRunner, mock(IamService.class)).shutdown(); + sparkRunner, bootstrapRunner, clusterStorage, mock(IamService.class)).shutdown(); verify(sparkRunner, times(reconcile ? 1 : 0)).removeLeftoverDrivers("emr"); verify(bootstrapRunner, times(reconcile ? 1 : 0)).removeImages(Set.of()); + verify(clusterStorage, times(reconcile ? 1 : 0)).removeAllBut(Set.of()); } } @@ -621,6 +628,122 @@ class EmrServiceContainerStepsTest { assertEquals(0, bootstrapping.stepThreadsWaiting()); } + @Test + void aClustersStepsShareItsStorageWhichGoesOnceItHasEndedAndItsLastStepIsDone() { + EmrCluster cluster = service.runJobFlow(cluster("shared", false, sparkStep("load", "CONTINUE"), + sparkStep("report", "CONTINUE")), REGION); + fixture.runStepThread(); + // The second step's driver, still running as its cluster ends, still needs the storage, however often + // the cluster is read meanwhile. + List threadsAsTheClusterEnded = new ArrayList<>(); + runner.whileRunning = () -> { + service.terminateJobFlows(List.of(cluster.getId())); + service.describeCluster(cluster.getId()); + threadsAsTheClusterEnded.add(fixture.stepThreadsWaiting()); + }; + + fixture.runStepThread(); + assertEquals(List.of(0), threadsAsTheClusterEnded); + assertTrue(service.describeCluster(cluster.getId()).isStorageCreated()); + fixture.runStepThread(); + + SparkJobRunner.Storage storage = new SparkJobRunner.Storage(cluster.getId() + "-home", + cluster.getId() + "-mnt"); + 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()); + assertEquals(0, fixture.stepThreadsWaiting()); + } + + @Test + void theStorageOfAClusterItsLastStepEndedGoesWithoutTheClusterBeingReadAgain() { + EmrCluster cluster = service.runJobFlow(cluster("finished", false, sparkStep("report", "CONTINUE")), REGION); + + fixture.runStepThread(); + // The step's end ended the cluster, and its storage's removal is on a thread of its own already. + assertEquals(1, fixture.stepThreadsWaiting()); + fixture.runStepThread(); + + assertEquals(List.of(cluster.getId()), fixture.clusterStorage.removed); + EmrCluster ended = service.describeCluster(cluster.getId()); + assertEquals("TERMINATED", ended.getState()); + assertFalse(ended.isStorageCreated()); + } + + @Test + void storageMadeAsAResetSweptGoesOnceItsStepsThreadIsDone() { + EmrCluster cluster = service.runJobFlow(cluster("reset", true, sparkStep("load", "CONTINUE")), REGION); + // The reset sweeps every cluster's storage while the step's thread is making it. + fixture.clusterStorage.whileCreating = service::beforeReset; + + fixture.runStepThread(); + + assertEquals(List.of(Set.of()), fixture.clusterStorage.kept); + assertEquals(List.of(cluster.getId()), fixture.clusterStorage.removed); + assertEquals(List.of(), runner.driversStarted); + } + + @Test + void storageDockerRefusesToRemoveIsTriedAgainTheNextTimeItsClusterIsRead() { + EmrCluster cluster = service.runJobFlow(cluster("refused", true, sparkStep("load", "CONTINUE")), REGION); + fixture.runStepThread(); + fixture.clusterStorage.refuse = true; + service.terminateJobFlows(List.of(cluster.getId())); + + // One removal at a time, however often the cluster is read meanwhile. + service.describeCluster(cluster.getId()); + assertEquals(1, fixture.stepThreadsWaiting()); + fixture.runStepThread(); + // Refused: the cluster still keeps its storage, and reading it tries again. + assertTrue(service.describeCluster(cluster.getId()).isStorageCreated()); + fixture.clusterStorage.refuse = false; + fixture.runStepThread(); + + assertEquals(List.of(cluster.getId(), cluster.getId()), fixture.clusterStorage.removed); + assertFalse(service.describeCluster(cluster.getId()).isStorageCreated()); + assertEquals(0, fixture.stepThreadsWaiting()); + } + + @Test + void aClusterWhoseStepsNoContainerRanHasNoStorage() { + EmrStep copy = sparkStep("copy", "CONTINUE"); + copy.setArgs(new ArrayList<>(List.of("s3-dist-cp", "--src=s3://bucket/in/", "--dest=hdfs:///in/"))); + EmrCluster cluster = service.runJobFlow(cluster("unrun", true, copy), REGION); + fixture.runStepThread(); + + service.terminateJobFlows(List.of(cluster.getId())); + + assertFalse(service.describeCluster(cluster.getId()).isStorageCreated()); + assertEquals(List.of(), fixture.clusterStorage.created); + assertEquals(List.of(), fixture.clusterStorage.removed); + assertEquals(0, fixture.stepThreadsWaiting()); + } + + @Test + void theStorageOfClustersThatAreGoneOrHaveEndedIsRemovedBeforeARestartedClusterCanMoveOn() { + // Its step was running as Floci stopped: the wakeup that fails it could start another step. + EmrCluster up = service.runJobFlow(cluster("up", true, sparkStep("cut", "CONTINUE")), REGION); + EmrCluster ended = service.runJobFlow(cluster("ended", true), REGION); + service.terminateJobFlows(List.of(ended.getId())); + EmrService.Wakeups wakeups = mock(EmrService.Wakeups.class); + doAnswer(invocation -> { + assertEquals(List.of(Set.of(up.getId())), fixture.clusterStorage.kept); + return null; + }).when(wakeups).at(any(), any()); + + fixture.restartReconciling(mock(SparkJobRunner.class), wakeups); + + verify(wakeups, atLeastOnce()).at(any(), any()); + assertEquals(List.of(Set.of(up.getId())), fixture.clusterStorage.kept); + } + + @Test + void aResetRemovesTheStorageOfEveryCluster() { + service.beforeReset(); + + assertEquals(List.of(Set.of()), fixture.clusterStorage.kept); + } + @Test void aClusterARestartLeftBootstrappingEndsWithErrors() { EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null); 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 5ddb80bedd..45c4634377 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 @@ -17,6 +17,7 @@ import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.Set; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.mockito.ArgumentMatchers.anyString; @@ -47,6 +48,40 @@ final class EmrServiceFixture { private record Wakeup(Instant due, Runnable task) {} + /** + * A cluster's storage as what the service asked of it, each removal refused while {@link #refuse} is set, and + * {@link #whileCreating} run as each is made. + */ + static final class RecordingStorage implements ClusterStorage { + final List created = new ArrayList<>(); + final List removed = new ArrayList<>(); + final List> kept = new ArrayList<>(); + boolean refuse; + Runnable whileCreating = () -> { }; + + @Override + public SparkJobRunner.Storage volumes(String clusterId) { + return new SparkJobRunner.Storage(clusterId + "-home", clusterId + "-mnt"); + } + + @Override + public void create(String clusterId, String accountId, String region) { + created.add(clusterId); + whileCreating.run(); + } + + @Override + public boolean remove(String clusterId) { + removed.add(clusterId); + return !refuse; + } + + @Override + public void removeAllBut(Set kept) { + this.kept.add(kept); + } + } + final ObjectMapper objectMapper = new ObjectMapper(); final List published = new ArrayList<>(); final MutableClock clock; @@ -62,6 +97,8 @@ final class EmrServiceFixture { private final InMemoryStorageFactory storage; private final SparkJobRunner runner; private final BootstrapRunner bootstrap; + // The docker runner mode's; null in the immediate one. + final RecordingStorage clusterStorage; private final IamService iam; private final int[] durations; @@ -71,7 +108,7 @@ final class EmrServiceFixture { } EmrServiceFixture(int startupDelaySeconds, int stepDurationSeconds, int terminationDelaySeconds) { - this(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), null, null, null, + this(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), null, null, null, null, startupDelaySeconds, stepDurationSeconds, terminationDelaySeconds); } @@ -82,16 +119,18 @@ final class EmrServiceFixture { /** As {@link #docker(SparkJobRunner, IamService)}, its clusters' bootstrap actions run by {@code bootstrap}. */ static EmrServiceFixture docker(SparkJobRunner runner, BootstrapRunner bootstrap, IamService iam) { - return new EmrServiceFixture(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), runner, bootstrap, iam, - 0, 0, 0); + return new EmrServiceFixture(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), runner, bootstrap, + new RecordingStorage(), iam, 0, 0, 0); } private EmrServiceFixture(InMemoryStorageFactory storage, MutableClock clock, SparkJobRunner runner, - BootstrapRunner bootstrap, IamService iam, int... durations) { + BootstrapRunner bootstrap, RecordingStorage clusterStorage, IamService iam, + int... durations) { this.storage = storage; this.clock = clock; this.runner = runner; this.bootstrap = bootstrap; + this.clusterStorage = clusterStorage; this.iam = iam; this.durations = durations; EventBridgeService eventBridge = mock(EventBridgeService.class); @@ -118,12 +157,12 @@ final class EmrServiceFixture { public void deliver(Runnable delivery) { deliveries.add(delivery); } - }, runner, bootstrap, stepThreads::add, iam); + }, runner, bootstrap, clusterStorage, stepThreads::add, iam); } /** A new service on the same storage and clock, as after a restart of Floci with persistent storage. */ EmrServiceFixture restart() { - return new EmrServiceFixture(storage, clock, runner, bootstrap, iam, durations); + return new EmrServiceFixture(storage, clock, runner, bootstrap, clusterStorage, iam, durations); } /** @@ -132,7 +171,7 @@ final class EmrServiceFixture { */ EmrService restartReconciling(SparkJobRunner runner, EmrService.Wakeups wakeups) { return new EmrService(storage, config(true), new RegionResolver(REGION, ACCOUNT), publisher, clock, wakeups, - runner, bootstrap, stepThreads::add, iam); + runner, bootstrap, clusterStorage, stepThreads::add, iam); } private EmulatorConfig config(boolean reconcile) { diff --git a/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessJobRunServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessJobRunServiceTest.java index c40b2c6273..fa4e506bbe 100644 --- a/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessJobRunServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessJobRunServiceTest.java @@ -265,6 +265,8 @@ class EmrServerlessJobRunServiceTest { assertNull(job.cloudWatchLogs()); assertEquals(Map.of(), job.environment()); assertEquals(List.of(), job.archives()); + // An EMR Serverless application has no cluster, nor its storage. + assertNull(job.storage()); } @Test 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 65def90aa6..a6fe10e4e2 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 @@ -77,6 +77,8 @@ import static org.mockito.Mockito.when; class EmrServerlessSparkRunnerTest { private static final String ENDPOINT = "http://floci:4566"; + private static final SparkJobRunner.Storage STORAGE = new SparkJobRunner.Storage( + "floci-aws-emr-j-2AXXXXXXGAPLF-home", "floci-aws-emr-j-2AXXXXXXGAPLF-mnt"); private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); private final ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); @@ -169,6 +171,8 @@ 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. + verify(spec, never()).withNamedVolume(anyString(), anyString()); } @Test @@ -216,6 +220,7 @@ class EmrServerlessSparkRunnerTest { verify(spec).withJavaTrustStore(); // The job's own variables, a cluster's spark-env exports, beside Floci's (none from this test's mock). verify(spec).withEnv(List.of("PYSPARK_PYTHON=/usr/bin/python3.11")); + verify(spec, never()).withEnv(eq("FLOCI_HADOOP_SITE"), anyString()); } @Test @@ -396,6 +401,62 @@ class EmrServerlessSparkRunnerTest { assertFalse(ended.output().contains("started")); } + @Test + void aStepMountsItsClustersStorageWhoseHdfsIsWherePathsWithoutASchemeLead() { + ContainerBuilder builder = mock(ContainerBuilder.class); + ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF); + when(builder.newContainer(anyString())).thenReturn(spec); + SparkJobRunner.Job job = stepJob(Map.of("spark.hadoop.fs.defaultFS", "file:///")); + + runner(builder).run(job, progress); + List arguments = EmrServerlessSparkRunner.sparkSubmitArguments(job, ENDPOINT); + + verify(spec).withNamedVolume(STORAGE.home(), "/home/hadoop"); + verify(spec).withNamedVolume(STORAGE.mnt(), "/mnt"); + // After Floci's S3 settings, before the cluster's spark-defaults, which win. + assertEquals("spark.hadoop.aws.region=eu-west-1", arguments.get(17)); + 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.sql.streaming.checkpointFileManagerClass=" + + "org.apache.spark.sql.execution.streaming.FileSystemBasedCheckpointFileManager", + "--conf", "spark.hadoop.fs.defaultFS=file:///", + "s3://bucket/jobs/report.py"), arguments.subList(18, arguments.size())); + } + + @Test + void aCommandOnAClusterGivesItsHadoopCommandTheClustersHdfsToo() { + ContainerBuilder builder = mock(ContainerBuilder.class); + ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF); + when(builder.newContainer(anyString())).thenReturn(spec); + List command = List.of("bash", "-c", "hadoop fs -put data.csv /input/"); + + runner(builder).run(commandJob(command, Map.of(), STORAGE), progress); + + verify(spec).withNamedVolume(STORAGE.home(), "/home/hadoop"); + verify(spec).withNamedVolume(STORAGE.mnt(), "/mnt"); + verify(spec).withEnv("FLOCI_HADOOP_SITE", 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_SPARK_DEFAULTS"), argThat(file -> file.contains( + "\nspark.hadoop.fs.defaultFS hdfs:///\n"))); + // 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( + "source_conf=\"${HADOOP_CONF_DIR:-/etc/hadoop/conf}\"\n") + && entrypoint.get(2).contains("cp -rL \"$source_conf/.\" \"$hadoop_conf\"") + && entrypoint.get(2).contains( + "include=''") + && entrypoint.get(2).contains("''" + + " \"$include\" \"$FLOCI_HADOOP_SITE\" '' > \"$hadoop_conf/core-site.xml\"") + && entrypoint.get(2).contains( + "export HADOOP_CONF_DIR=\"$hadoop_conf\" PATH=\"/tmp/floci-bin:$PATH\""))); + } + @Test void aCommandsOwnSparkSubmitRunsLocallyOnFlocisS3WithTheJobsSparkDefaults() { assertEquals(String.join("\n", @@ -835,24 +896,37 @@ class EmrServerlessSparkRunnerTest { SparkJobRunner.CloudWatchLogs cloudWatchLogs) { return new SparkJobRunner.Job("emr-serverless", "00f0000000000001", "123456789012", "eu-west-1", "emr-7.5.0", imageTemplate, null, "floci-network", "arn:aws:iam::123456789012:role/job", sparkDefaults, - application, null, timeout, logFolder, cloudWatchLogs, Map.of(), List.of()); + application, null, timeout, logFolder, cloudWatchLogs, Map.of(), List.of(), null); } private static SparkJobRunner.Job customImageJob(String customImage) { return new SparkJobRunner.Job("emr-serverless", "00f0000000000001", "123456789012", "eu-west-1", "emr-7.5.0", null, customImage, "floci-network", "arn:aws:iam::123456789012:role/job", Map.of(), - List.of("s3://bucket/jobs/app.jar"), null, Duration.ZERO, null, null, Map.of(), List.of()); + List.of("s3://bucket/jobs/app.jar"), null, Duration.ZERO, null, null, Map.of(), List.of(), null); } private static SparkJobRunner.Job archiveJob(List archives) { return new SparkJobRunner.Job("emr-serverless", "00f0000000000001", "123456789012", "eu-west-1", "emr-7.5.0", null, null, "floci-network", "arn:aws:iam::123456789012:role/job", Map.of(), - List.of("s3://bucket/jobs/app.jar"), null, Duration.ZERO, null, null, Map.of(), archives); + List.of("s3://bucket/jobs/app.jar"), null, Duration.ZERO, null, null, Map.of(), archives, null); } private static SparkJobRunner.Job commandJob(List command, Map sparkDefaults) { + return commandJob(command, sparkDefaults, null); + } + + private static SparkJobRunner.Job commandJob(List command, Map sparkDefaults, + SparkJobRunner.Storage storage) { return new SparkJobRunner.Job("emr", "s-1A2B3C4D5E6F7", "123456789012", "eu-west-1", "emr-7.5.0", null, null, "floci-network", "arn:aws:iam::123456789012:role/job", sparkDefaults, List.of(), command, - Duration.ZERO, null, null, Map.of("PYSPARK_PYTHON", "/usr/bin/python3.11"), List.of()); + Duration.ZERO, null, null, Map.of("PYSPARK_PYTHON", "/usr/bin/python3.11"), List.of(), + storage); + } + + // A Spark step on a cluster, which has storage. + private static SparkJobRunner.Job stepJob(Map sparkDefaults) { + return new SparkJobRunner.Job("emr", "s-1A2B3C4D5E6F7", "123456789012", "eu-west-1", "emr-7.5.0", null, + null, "floci-network", "arn:aws:iam::123456789012:role/job", sparkDefaults, + List.of("s3://bucket/jobs/report.py"), null, Duration.ZERO, null, null, Map.of(), List.of(), STORAGE); } }