feat(emr): run a cluster's bootstrap actions in the docker runner mode (#6878)

In the docker runner mode a cluster's BootstrapActions were stored and
listed but never run, so a step that needed what they install, such as
a Python library a PySpark step imports, failed where on AWS it would
run. Now a cluster with bootstrap actions is BOOTSTRAPPING while they
run, one after the other, in one container of the release's EMR
Serverless image, and that container is then kept as the image the
cluster's steps run in.

- Each action's script is read from Floci's S3 (s3n:// and s3a:// name
  the same bucket) and runs with its Args in /home/hadoop through
  docker exec, with the credentials of the cluster's instance profile
  in that exec's environment alone, so they never become part of the
  image.
- "Bootstrap actions execute as the Hadoop user by default. You can
  execute a bootstrap action with root privileges by using sudo", but
  the image has no sudo: an action runs as root, with a sudo that runs
  its command as it is, and what it leaves in /home/hadoop is the
  hadoop user's. The kept image runs as the user of the image the
  container ran, as the steps do, and the steps get it by its id, which
  runs as it is whatever image-registry-base Floci pulls images from.
- An action that exits with another code than 0 ends the cluster
  TERMINATED_WITH_ERRORS, with BOOTSTRAP_FAILURE and "On the master
  instance (<instance-id>), bootstrap action <n> returned a non-zero
  return code", as a real cluster gave it
  (hashicorp/terraform-provider-aws#4378) and the Management Guide
  quotes it. A script that cannot be read ends it the same way, in
  Floci's words; a bootstrap that cannot run, or that a restart cut
  short, with INTERNAL_ERROR. TerminateJobFlows stops it at once.
- With a LogUri, each action's stdout.gz and stderr.gz go under
  <LogUri>/<cluster-id>/node/<instance-id>/bootstrap-actions/<n>/, the
  instance the master as ListInstances gives it. An action's output
  goes to Floci's log line by line as it runs, and to those files
  gzipped as it arrives, through a file on disk, so however much it
  writes, Floci keeps no more than a line of it in memory.
- The image goes once the cluster has ended and its last step is done,
  and the cluster names it until it is gone, so a removal Docker
  refuses is tried again the next time the cluster is read; a reset
  removes them all, and the startup sweep, before any restarted cluster
  can move on, the ones of clusters that are gone or have ended.

ContainerExec gets an overload that sets an environment for one
command alone. What the bootstrap has in common with the Spark runner
and the rest of Floci is shared rather than copied:

- core.common.docker.ContainerLaunches: the runs in progress and their
  containers, which a stop, a reset or a shutdown removes; both EMR
  runners keep theirs in it.
- ContainerLifecycleManager.commit and removeImage.
- ContainerLogStreamer.consoleLines, a stream that logs each line as it
  arrives through the line logger its attach methods now share.
- S3Uri.isS3 and parseAnyScheme, which read s3n:// and s3a:// as s3://.
- EmrServerlessSparkRunner.putLogs, the runner's S3 log writing, which
  now reads each file from a stream.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-28 21:59:40 -05:00
1 parent 8ececd84b4
commit 591d5f533b
24 files changed
+1763 -126

No files matched your search

@@ -3,7 +3,9 @@ package io.github.hectorvent.floci.core.common;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class S3UriTest {
@@ -30,4 +32,15 @@ class S3UriTest {
assertThrows(IllegalArgumentException.class, () -> S3Uri.parse("s3:///emr/"));
assertThrows(IllegalArgumentException.class, () -> S3Uri.parse(null));
}
@Test
void hadoopsSchemesNameTheSameBuckets() {
assertEquals(new S3Uri("logs", "emr/"), S3Uri.parseAnyScheme("s3n://logs/emr/"));
assertEquals(new S3Uri("logs", "emr/"), S3Uri.parseAnyScheme("s3a://logs/emr/"));
assertEquals(new S3Uri("logs", "emr/"), S3Uri.parseAnyScheme("s3://logs/emr/"));
assertTrue(S3Uri.isS3("s3n://logs/emr/"));
assertFalse(S3Uri.isS3("file:/usr/share/aws/emr/scripts/install"));
assertFalse(S3Uri.isS3(null));
assertThrows(IllegalArgumentException.class, () -> S3Uri.parseAnyScheme("hdfs://logs/emr/"));
}
}
@@ -32,6 +32,15 @@ public final class ContainerExecStubs {
/** Returns the commands run in {@code containerId}, in order, as the stubbed execs see them. */
public static List<List<String>> completeEveryExec(DockerClient dockerClient, String containerId, long exitCode,
String stdout, String stderr) {
return completeEveryExec(dockerClient, containerId, List.of(exitCode), stdout, stderr);
}
/**
* As {@link #completeEveryExec(DockerClient, String, long, String, String)}, the execs exiting with
* {@code exitCodes} in turn, and every one after them with the last.
*/
public static List<List<String>> completeEveryExec(DockerClient dockerClient, String containerId,
List<Long> exitCodes, String stdout, String stderr) {
String execId = "exec-" + containerId;
List<List<String>> commands = new ArrayList<>();
@@ -61,7 +70,8 @@ public final class ContainerExecStubs {
InspectExecCmd inspectCmd = mock(InspectExecCmd.class);
InspectExecResponse inspectResponse = mock(InspectExecResponse.class);
when(inspectResponse.getExitCodeLong()).thenReturn(exitCode);
when(inspectResponse.getExitCodeLong())
.thenReturn(exitCodes.getFirst(), exitCodes.subList(1, exitCodes.size()).toArray(Long[]::new));
when(inspectCmd.exec()).thenReturn(inspectResponse);
when(dockerClient.inspectExecCmd(execId)).thenReturn(inspectCmd);
return commands;
@@ -0,0 +1,55 @@
package io.github.hectorvent.floci.core.common.docker;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
/** A run's container is removed by whoever claims it first, the run itself or a stop, and by no one else. */
class ContainerLaunchesTest {
private final ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
private final ContainerLaunches launches = new ContainerLaunches();
@Test
void aStopRemovesAStartedContainerAndLeavesTheRunNothingToRemove() {
ContainerLaunches.Launch launch = launches.begin("run-1");
launch.started("container-1");
launches.stopAll(lifecycle, 0);
verify(lifecycle).stopAndRemove("container-1", null, 0);
assertTrue(launch.stopRequested());
assertNull(launches.end("run-1", launch));
assertNull(launches.get("run-1"));
}
@Test
void aStopBeforeTheContainerIsUpOnlyAsksTheRunToStop() {
ContainerLaunches.Launch launch = launches.begin("run-1");
launches.get("run-1").stopNow(lifecycle, 0);
launch.started("container-1");
verifyNoInteractions(lifecycle);
assertTrue(launch.stopRequested());
assertEquals("container-1", launches.end("run-1", launch));
}
@Test
void aRequestedStopRemovesNothing() {
ContainerLaunches.Launch launch = launches.begin("run-1");
launch.started("container-1");
launch.requestStop();
verify(lifecycle, never()).stopAndRemove("container-1", null, 0);
assertEquals("container-1", launch.container());
assertEquals("container-1", launches.end("run-1", launch));
}
}
@@ -0,0 +1,62 @@
package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CommitCmd;
import com.github.dockerjava.api.command.RemoveImageCmd;
import com.github.dockerjava.api.exception.ConflictException;
import com.github.dockerjava.api.exception.NotFoundException;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** A container kept as an image, and an image removed: gone counts as removed, a refusal does not. */
class ContainerLifecycleManagerImagesTest {
private final DockerClient docker = mock(DockerClient.class);
private final ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, null, null, null);
@Test
void aCommitNamesTheImageAndSetsItsUserAndLabels() {
CommitCmd commit = mock(CommitCmd.class, RETURNS_SELF);
when(commit.exec()).thenReturn("sha256:kept");
when(docker.commitCmd("container-1")).thenReturn(commit);
assertEquals("sha256:kept", manager.commit("container-1", "floci-aws-emr-bootstrap", "j-1", "hadoop",
Map.of("io.floci.component", "emr-bootstrap")));
verify(commit).withRepository("floci-aws-emr-bootstrap");
verify(commit).withTag("j-1");
verify(commit).withUser("hadoop");
verify(commit).withLabels(Map.of("io.floci.component", "emr-bootstrap"));
}
@Test
void anImageIsRemovedByForceAndOneAlreadyGoneCountsAsRemoved() {
RemoveImageCmd removed = mock(RemoveImageCmd.class, RETURNS_SELF);
when(docker.removeImageCmd("kept:1")).thenReturn(removed);
RemoveImageCmd missing = mock(RemoveImageCmd.class, RETURNS_SELF);
when(missing.exec()).thenThrow(new NotFoundException("No such image"));
when(docker.removeImageCmd("gone:1")).thenReturn(missing);
assertTrue(manager.removeImage("kept:1"));
assertTrue(manager.removeImage("gone:1"));
verify(removed).withForce(true);
}
@Test
void anImageTheDaemonRefusesToRemoveIsReported() {
RemoveImageCmd refused = mock(RemoveImageCmd.class, RETURNS_SELF);
when(refused.exec()).thenThrow(new ConflictException("image is being used by running container"));
when(docker.removeImageCmd("in-use:1")).thenReturn(refused);
assertFalse(manager.removeImage("in-use:1"));
}
}
@@ -14,6 +14,9 @@ import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
@@ -46,6 +49,27 @@ class ContainerLogStreamerTest {
return s.getBytes(StandardCharsets.UTF_8);
}
private static void write(OutputStream stream, String text) {
try {
stream.write(utf8(text));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static void close(OutputStream stream) {
try {
stream.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
// The container lines that records logged, without their prefix.
private static List<Object> loggedLines(List<LogRecord> records) {
return records.stream().map(record -> record.getParameters()[1]).toList();
}
@Test
void ensureLogGroupAndStreamUsesOwningAccount() {
CloudWatchLogsService cloudWatchLogsService = mock(CloudWatchLogsService.class);
@@ -208,6 +232,22 @@ class ContainerLogStreamerTest {
eq("us-east-1"));
}
@Test
void consoleLinesLogsEachLineAsItArrivesAndALastOneWithoutANewlineWhenClosed() {
OutputStream console = ContainerLogStreamer.consoleLines("emr:j-1:bootstrap-action-1");
List<LogRecord> asWritten = LogCapture.capture(ContainerLogStreamer.class, () -> {
write(console, "Collecting pan");
write(console, "das\n\nInstalled pandas\nDone");
});
List<LogRecord> asClosed = LogCapture.capture(ContainerLogStreamer.class, () -> close(console));
// A blank line is dropped, as the attach methods drop one.
assertEquals(List.of("Collecting pandas", "Installed pandas"), loggedLines(asWritten));
assertEquals(List.of("Done"), loggedLines(asClosed));
assertEquals("emr:j-1:bootstrap-action-1", asClosed.getFirst().getParameters()[0]);
}
@Test
void reassemblesSingleLineSplitAcrossFrames() {
// A ~1.5 KB stdout line that Docker delivers as multiple frames must arrive
@@ -0,0 +1,258 @@
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.model.Image;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
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.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
import io.github.hectorvent.floci.services.lambda.launcher.BootstrapProcess;
import io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentials;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.zip.GZIPInputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
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.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 bootstrap actions run one after the other through {@code docker exec}, as root, in one
* container of the release's image, which is then kept as the image the cluster's steps run in.
*/
class EmrBootstrapRunnerTest {
private static final String ACCOUNT = "123456789012";
private static final String REGION = "eu-west-1";
private static final String CONTAINER = "bootstrap";
private static final String RELEASE_IMAGE = "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest";
private static final String RELEASE_IMAGE_ID = "sha256:" + "1".repeat(64);
private static final String IMAGE_ID = "sha256:" + "2".repeat(64);
private static final List<String> ENV = List.of("AWS_ACCESS_KEY_ID=ASIAEXAMPLE", "AWS_ENDPOINT_URL=http://floci");
private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
private final ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
private final DockerClient docker = mock(DockerClient.class, RETURNS_DEEP_STUBS);
private final ContainerBuilder builder = mock(ContainerBuilder.class);
private final ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
private final LaunchedContainerAwsEnv awsEnv = mock(LaunchedContainerAwsEnv.class);
private final LambdaExecutionRoleCredentials roleCredentials = mock(LambdaExecutionRoleCredentials.class);
private final S3Service s3 = mock(S3Service.class);
private final EmrBootstrapRunner runner =
new EmrBootstrapRunner(builder, lifecycle, awsEnv, roleCredentials, s3, config);
// What the runner put in S3, by bucket and key, gunzipped: read as it is put, as its files then go.
private final Map<String, String> uploaded = new LinkedHashMap<>();
@BeforeEach
void setUp() {
when(builder.newContainer(anyString())).thenReturn(spec);
when(lifecycle.getDockerClient()).thenReturn(docker);
when(lifecycle.createAndStart(any()))
.thenReturn(new ContainerLifecycleManager.ContainerInfo(CONTAINER, Map.of()));
when(roleCredentials.forRole(any(), any(), any())).thenReturn(Optional.empty());
when(awsEnv.sdkBaselineEnv(REGION, Optional.empty(), Optional.empty(), ACCOUNT)).thenReturn(ENV);
// The container runs the release image, under whatever name an image-registry-base gave it.
when(docker.inspectContainerCmd(CONTAINER).exec().getImageId()).thenReturn(RELEASE_IMAGE_ID);
when(docker.inspectImageCmd(RELEASE_IMAGE_ID).exec().getConfig().getUser()).thenReturn("hadoop");
when(docker.inspectImageCmd(ContainerStorageHelper.dockerName(config, "emr-bootstrap") + ":j-1").exec()
.getId()).thenReturn(IMAGE_ID);
script("bucket", "bootstrap/install.sh");
script("bucket", "bootstrap/jars.sh");
when(s3.putObjectFromStream(anyString(), anyString(), any(InputStream.class), eq("application/x-gzip"),
anyMap())).thenAnswer(put -> {
try (GZIPInputStream gunzip = new GZIPInputStream(put.<InputStream>getArgument(2))) {
uploaded.put(put.getArgument(0) + "/" + put.getArgument(1),
new String(gunzip.readAllBytes(), StandardCharsets.UTF_8));
}
return null;
});
}
@Test
void eachActionRunsInTurnAsRootThenTheContainerIsKeptAsTheImageTheStepsRunIn() {
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, CONTAINER, 0, "installed\n", "");
BootstrapRunner.Outcome outcome = runner.run(bootstrap("s3://logs/j-1/node/i-1/bootstrap-actions/",
action("s3://bucket/bootstrap/install.sh", "pandas", "2.2"),
action("s3n://bucket/bootstrap/jars.sh")), () -> false);
// The steps get the kept image's id, which runs as it is, whatever registry Floci pulls images from.
assertEquals(BootstrapRunner.Outcome.succeeded(IMAGE_ID), outcome);
verify(builder).newContainer(RELEASE_IMAGE);
verify(spec).withUser("root");
verify(spec).withEntrypoint(List.of("sleep", "infinity"));
verify(spec).withLabels(argThat(labels -> "emr".equals(labels.get(ContainerStorageHelper.SERVICE_LABEL))
&& "j-1".equals(labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL))
&& "emr-bootstrap".equals(labels.get(ContainerStorageHelper.COMPONENT_LABEL))));
// Each script is read as the cluster's account and copied in, then run with its arguments.
verify(s3).getObject("bucket", "bootstrap/install.sh");
verify(s3).getObject("bucket", "bootstrap/jars.sh");
assertEquals(List.of("bootstrap-action", "/tmp/floci-bootstrap-action-1-install.sh", "pandas", "2.2"),
commands.get(0).subList(3, commands.get(0).size()));
assertEquals(List.of("bootstrap-action", "/tmp/floci-bootstrap-action-2-jars.sh"),
commands.get(1).subList(3, commands.get(1).size()));
assertEquals(List.of("bash", "-c"), commands.get(0).subList(0, 2));
assertTrue(commands.get(0).get(2).contains("chown -R hadoop:hadoop /home/hadoop"));
assertEquals(3, commands.size());
// The credentials go to each action's exec alone, never to the container the image is made of.
ExecCreateCmd exec = docker.execCreateCmd(CONTAINER);
verify(exec, times(2)).withEnv(ENV);
verify(spec, never()).withEnv(any(List.class));
// The image runs as the user of the image the container ran, as the steps do.
String repository = ContainerStorageHelper.dockerName(config, "emr-bootstrap");
verify(lifecycle).commit(eq(CONTAINER), eq(repository), eq("j-1"), eq("hadoop"),
argThat(labels -> "emr-bootstrap".equals(labels.get(ContainerStorageHelper.COMPONENT_LABEL))));
assertEquals(Map.of("logs/j-1/node/i-1/bootstrap-actions/1/stdout.gz", "installed\n",
"logs/j-1/node/i-1/bootstrap-actions/1/stderr.gz", "",
"logs/j-1/node/i-1/bootstrap-actions/2/stdout.gz", "installed\n",
"logs/j-1/node/i-1/bootstrap-actions/2/stderr.gz", ""), uploaded);
verify(lifecycle).stopAndRemove(CONTAINER, null, 0);
}
@Test
void aFailingActionEndsTheBootstrapThereAndNothingIsKept() {
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, CONTAINER, List.of(0L, 3L), "", "");
BootstrapRunner.Outcome outcome = runner.run(bootstrap(null, action("s3://bucket/bootstrap/install.sh"),
action("s3://bucket/bootstrap/jars.sh"), action("s3://bucket/bootstrap/never.sh")), () -> false);
assertEquals(BootstrapRunner.Outcome.actionFailed(2, 3), outcome);
assertEquals(2, commands.size());
verify(lifecycle, never()).commit(any(), any(), any(), any(), any());
assertTrue(uploaded.isEmpty());
verify(lifecycle).stopAndRemove(CONTAINER, null, 0);
}
@Test
void anActionsOutputReachesItsLogsWholeHoweverLongAndLeavesNoFileBehind() throws IOException {
// Megabytes of output, as a chatty pip install gives, which is kept on disk as it arrives, not in memory.
String output = IntStream.range(0, 2_000).mapToObj(line -> "Collecting package-" + line + " "
+ "x".repeat(1_000) + "\n").collect(Collectors.joining());
ContainerExecStubs.completeEveryExec(docker, CONTAINER, 0, output, "WARNING: no newline at the end");
Set<Path> filesBefore = bootstrapFiles();
runner.run(bootstrap("s3://logs/j-1/node/i-1/bootstrap-actions/", action("s3://bucket/bootstrap/install.sh")),
() -> false);
assertEquals(output, uploaded.get("logs/j-1/node/i-1/bootstrap-actions/1/stdout.gz"));
assertEquals("WARNING: no newline at the end", uploaded.get("logs/j-1/node/i-1/bootstrap-actions/1/stderr.gz"));
assertEquals(filesBefore, bootstrapFiles());
}
@Test
void aScriptThatCannotBeReadFailsItsActionWithoutRunningIt() {
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, CONTAINER, 0, "", "");
when(s3.getObject("bucket", "bootstrap/missing.sh"))
.thenThrow(new AwsException("NoSuchKey", "The specified key does not exist.", 404));
BootstrapRunner.Outcome outcome = runner.run(bootstrap(null, action("s3://bucket/bootstrap/missing.sh")),
() -> false);
assertEquals(BootstrapRunner.Outcome.notDownloaded(1, "The specified key does not exist."), outcome);
assertTrue(commands.isEmpty());
}
@Test
void aClusterThatEndsWhileAnActionRunsStopsTheBootstrapThere() {
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, CONTAINER, 0, "", "");
AtomicBoolean ended = new AtomicBoolean();
when(s3.getObject("bucket", "bootstrap/install.sh")).thenAnswer(read -> {
ended.set(true);
return content("#!/bin/bash\n");
});
BootstrapRunner.Outcome outcome = runner.run(bootstrap(null, action("s3://bucket/bootstrap/install.sh"),
action("s3://bucket/bootstrap/jars.sh")), ended::get);
assertEquals(BootstrapRunner.Outcome.halted(), outcome);
assertEquals(1, commands.size());
verify(lifecycle, never()).commit(any(), any(), any(), any(), any());
}
@Test
void imagesOfClustersThatAreGoneAreRemovedAndTheOthersKept() {
String goneId = "sha256:" + "3".repeat(64);
Image kept = mock(Image.class);
when(kept.getId()).thenReturn(IMAGE_ID);
Image gone = mock(Image.class);
when(gone.getId()).thenReturn(goneId);
when(docker.listImagesCmd().withLabelFilter(anyMap()).exec()).thenReturn(List.of(kept, gone));
runner.removeImages(Set.of(IMAGE_ID));
verify(lifecycle).removeImage(goneId);
verify(lifecycle, never()).removeImage(IMAGE_ID);
}
@Test
void sudoDropsItsOptionsAndRunsItsCommandAsItIs(@TempDir Path directory) throws Exception {
Path sudo = directory.resolve("sudo");
Files.writeString(sudo, EmrBootstrapRunner.SUDO + "\n");
BootstrapProcess.Result ended = BootstrapProcess.run(new ProcessBuilder("bash", sudo.toString(), "-E", "-u",
"root", "--", "GREETING=hello", "sh", "-c", "printf '%s %s|' \"$GREETING\" \"$1\"", "sh", "two words"));
assertEquals(new BootstrapProcess.Result(0, "hello two words|"), ended);
}
// The files an action's output is gzipped into while it runs, in the temporary directory.
private static Set<Path> bootstrapFiles() throws IOException {
try (Stream<Path> files = Files.list(Path.of(System.getProperty("java.io.tmpdir")))) {
return files.filter(file -> file.getFileName().toString().startsWith("floci-emr-bootstrap-"))
.collect(Collectors.toSet());
}
}
private void script(String bucket, String key) {
S3Object object = content("#!/bin/bash\necho installed\n");
when(s3.getObject(bucket, key)).thenReturn(object);
}
private static S3Object content(String script) {
S3Object object = mock(S3Object.class);
when(object.getData()).thenReturn(script.getBytes(StandardCharsets.UTF_8));
return object;
}
private static BootstrapRunner.Action action(String path, String... args) {
return new BootstrapRunner.Action(path.substring(path.lastIndexOf('/') + 1), path, List.of(args));
}
private static BootstrapRunner.Bootstrap bootstrap(String logFolder, BootstrapRunner.Action... actions) {
return new BootstrapRunner.Bootstrap("j-1", ACCOUNT, REGION, "emr-7.5.0", null, null,
"arn:aws:iam::" + ACCOUNT + ":role/emr-ec2", List.of(actions), logFolder);
}
}
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
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;
import io.github.hectorvent.floci.services.emr.model.EmrStep;
import io.github.hectorvent.floci.services.emrserverless.EmrServerlessSparkRunner;
import io.github.hectorvent.floci.services.emrserverless.SparkJobRunner;
@@ -23,12 +24,14 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.BooleanSupplier;
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.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.inOrder;
@@ -40,14 +43,19 @@ import static org.mockito.Mockito.when;
/**
* The {@code docker} runner mode: each step runs in a container from when it goes RUNNING until its Spark
* driver ends, and then is COMPLETED, or FAILED with its ActionOnFailure taken, as the API reference and
* the Management Guide give it.
* the Management Guide give it. A cluster's bootstrap actions run while it is BOOTSTRAPPING, and its steps
* then in the image they left.
*/
class EmrServiceContainerStepsTest {
private static final String REPORT = "s3://bucket/jobs/report.py";
private static final String DRIVER_FAILED = "The Spark driver exited with code 1.";
private static final String INSTALL = "s3://bucket/bootstrap/install.sh";
// The id of the image a bootstrap kept, which the cluster's steps run in.
private static final String IMAGE = "sha256:" + "2".repeat(64);
private final FakeRunner runner = new FakeRunner();
private final FakeBootstrap bootstrap = new FakeBootstrap();
private final EmrServiceFixture fixture = EmrServiceFixture.docker(runner, null);
private final EmrService service = fixture.service;
@@ -385,6 +393,21 @@ class EmrServiceContainerStepsTest {
order.verify(wakeups).at(any(), any());
}
@Test
void leftoverBootstrapImagesAreRemovedBeforeARestartedClusterCanMoveOn() {
BootstrapRunner bootstrapRunner = mock(BootstrapRunner.class);
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrapRunner, null);
bootstrapping.service.runJobFlow(bootstrapped(cluster("restarted", true)), REGION);
EmrService.Wakeups wakeups = mock(EmrService.Wakeups.class);
bootstrapping.restartReconciling(runner, wakeups);
// A wakeup runs on the timer's thread: a cluster it moved on could keep an image the sweep never knew of.
InOrder order = inOrder(bootstrapRunner, wakeups);
order.verify(bootstrapRunner).removeImages(Set.of());
order.verify(wakeups).at(any(), any());
}
@Test
void aStepRunsAsItsRuntimeRoleOrElseAsTheClustersInstanceProfileRole() {
IamService iam = mock(IamService.class);
@@ -418,22 +441,217 @@ class EmrServiceContainerStepsTest {
}
@Test
void leftoverDriversAreRemovedWhenTheServiceStartsUnlessReconcilingIsOff() {
void leftoverDriversAndBootstrapImagesAreRemovedWhenTheServiceStartsUnlessReconcilingIsOff() {
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);
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
new EmrService(new InMemoryStorageFactory(ACCOUNT), config, regionResolver,
new EmrEventPublisher(mock(EventBridgeService.class), new ObjectMapper(), regionResolver),
sparkRunner, mock(IamService.class)).shutdown();
sparkRunner, bootstrapRunner, mock(IamService.class)).shutdown();
verify(sparkRunner, times(reconcile ? 1 : 0)).removeLeftoverDrivers("emr");
verify(bootstrapRunner, times(reconcile ? 1 : 0)).removeImages(Set.of());
}
}
@Test
void aClustersBootstrapActionsRunWhileItIsBootstrappingThenItsStepsRunInTheImageTheyLeft() {
IamService iam = mock(IamService.class);
InstanceProfile profile = new InstanceProfile();
profile.setRoleNames(List.of("emr-ec2"));
IamRole role = new IamRole();
role.setArn("arn:aws:iam::" + ACCOUNT + ":role/emr-ec2");
when(iam.findInstanceProfile(ACCOUNT, "EMR_EC2_DefaultRole")).thenReturn(Optional.of(profile));
when(iam.findRole(ACCOUNT, "emr-ec2")).thenReturn(Optional.of(role));
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, iam);
EmrCluster requested = bootstrapped(cluster("bootstrapped", true, sparkStep("report", "CONTINUE")));
requested.setJobFlowRole("EMR_EC2_DefaultRole");
requested.setLogUri("s3://logs/emr/");
// ListInstances lists the core group's two instances before the master's.
requested.setInstanceGroups(new ArrayList<>(List.of(group("CORE", 2), group("MASTER", 1))));
EmrCluster cluster = bootstrapping.service.runJobFlow(requested, REGION);
String stepId = cluster.getSteps().get(0).getId();
assertEquals("BOOTSTRAPPING", bootstrapping.service.describeCluster(cluster.getId()).getState());
assertEquals("PENDING", bootstrapping.service.describeStep(cluster.getId(), stepId).getState());
bootstrapping.runStepThread();
// "logs/<cluster-id>/node/<primary-instance-id>/bootstrap-actions/<action-number>/stdout.gz"
assertEquals(new BootstrapRunner.Bootstrap(cluster.getId(), ACCOUNT, REGION, "emr-7.5.0", null, null,
"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/"),
bootstrap.bootstraps.get(0));
assertEquals("RUNNING", bootstrapping.service.describeCluster(cluster.getId()).getState());
assertEquals("RUNNING", bootstrapping.service.describeStep(cluster.getId(), stepId).getState());
bootstrapping.runStepThread();
assertEquals(IMAGE, runner.jobs.get(0).imageTemplate());
assertEquals("COMPLETED", bootstrapping.service.describeStep(cluster.getId(), stepId).getState());
assertEquals(List.of("STARTING", "PENDING report", "RUNNING report", "COMPLETED report", "WAITING"),
bootstrapping.states());
}
@Test
void aClusterWithoutBootstrapActionsRunsItsStepsInTheReleasesImage() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
EmrCluster cluster = bootstrapping.service.runJobFlow(cluster("plain", true, sparkStep("report", "CONTINUE")),
REGION);
assertEquals("RUNNING", bootstrapping.service.describeCluster(cluster.getId()).getState());
bootstrapping.runStepThread();
assertTrue(bootstrap.bootstraps.isEmpty());
assertNull(runner.jobs.get(0).imageTemplate());
}
@Test
void aFailedBootstrapActionEndsTheClusterWithErrorsBeforeAnyStepRuns() {
bootstrap.outcome = BootstrapRunner.Outcome.actionFailed(2, 1);
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
EmrCluster cluster = bootstrapping.service.runJobFlow(
bootstrapped(cluster("failing", true, sparkStep("report", "CONTINUE"))), REGION);
bootstrapping.runStepThread();
EmrCluster ended = bootstrapping.service.describeCluster(cluster.getId());
assertEquals("TERMINATED_WITH_ERRORS", ended.getState());
assertEquals("BOOTSTRAP_FAILURE", ended.getStateChangeReasonCode());
assertEquals("On the master instance (i-00000000000000001), bootstrap action 2 returned a non-zero return code",
ended.getStateChangeMessage());
assertEquals("CANCELLED", bootstrapping.service.describeStep(cluster.getId(),
cluster.getSteps().get(0).getId()).getState());
assertTrue(runner.jobs.isEmpty());
assertEquals(0, bootstrapping.stepThreadsWaiting());
}
@Test
void aScriptThatCannotBeReadOrABootstrapThatCannotRunEndsTheClusterWithErrorsToo() {
Map<BootstrapRunner.Outcome, List<String>> reasons = Map.of(
BootstrapRunner.Outcome.notDownloaded(1, "The specified key does not exist."),
List.of("BOOTSTRAP_FAILURE", "On the master instance (i-00000000000000001), bootstrap action 1 could"
+ " not be read from " + INSTALL + ": The specified key does not exist."),
BootstrapRunner.Outcome.couldNotRun("the image could not be pulled"),
List.of("INTERNAL_ERROR", "Floci could not run the bootstrap actions: the image could not be pulled"));
reasons.forEach((outcome, reason) -> {
bootstrap.outcome = outcome;
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
EmrCluster cluster = bootstrapping.service.runJobFlow(bootstrapped(cluster("broken", true)), REGION);
bootstrapping.runStepThread();
EmrCluster ended = bootstrapping.service.describeCluster(cluster.getId());
assertEquals("TERMINATED_WITH_ERRORS", ended.getState());
assertEquals(reason, List.of(ended.getStateChangeReasonCode(), ended.getStateChangeMessage()));
});
}
@Test
void aClusterTerminatedWhileBootstrappingStopsItsBootstrapAndTheImageItLeftGoes() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
EmrCluster cluster = bootstrapping.service.runJobFlow(
bootstrapped(cluster("cut short", true, sparkStep("report", "CONTINUE"))), REGION);
// As a bootstrap that had kept its image just as its cluster ended.
bootstrap.whileRunning = () -> bootstrapping.service.terminateJobFlows(List.of(cluster.getId()));
while (bootstrapping.stepThreadsWaiting() > 0) {
bootstrapping.runStepThread();
}
EmrCluster ended = bootstrapping.service.describeCluster(cluster.getId());
assertEquals("TERMINATED", ended.getState());
assertEquals("USER_REQUEST", ended.getStateChangeReasonCode());
assertEquals(List.of(cluster.getId()), bootstrap.stopped);
assertEquals(List.of(IMAGE), bootstrap.removed);
assertTrue(runner.jobs.isEmpty());
}
@Test
void theImageABootstrapLeftGoesOnceItsClusterHasEndedAndItsLastStepIsDone() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
EmrCluster cluster = bootstrapping.service.runJobFlow(
bootstrapped(cluster("transient", false, sparkStep("report", "CONTINUE"))), REGION);
bootstrapping.runStepThread();
// The step's driver, still running as its cluster ends, still needs the image.
List<Integer> threadsAsTheClusterEnded = new ArrayList<>();
runner.whileRunning = () -> {
bootstrapping.service.terminateJobFlows(List.of(cluster.getId()));
threadsAsTheClusterEnded.add(bootstrapping.stepThreadsWaiting());
};
bootstrapping.runStepThread();
assertEquals(List.of(0), threadsAsTheClusterEnded);
assertEquals("TERMINATED", bootstrapping.service.describeCluster(cluster.getId()).getState());
bootstrapping.runStepThread();
assertEquals(List.of(IMAGE), bootstrap.removed);
assertNull(bootstrapping.service.describeCluster(cluster.getId()).getBootstrapImage());
}
@Test
void anImageDockerRefusesToRemoveIsTriedAgainTheNextTimeItsClusterIsRead() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
EmrCluster cluster = bootstrapping.service.runJobFlow(bootstrapped(cluster("refused", true)), REGION);
bootstrapping.runStepThread();
bootstrap.removes = false;
bootstrapping.service.terminateJobFlows(List.of(cluster.getId()));
// One removal at a time, however often the cluster is read meanwhile.
bootstrapping.service.describeCluster(cluster.getId());
assertEquals(1, bootstrapping.stepThreadsWaiting());
bootstrapping.runStepThread();
// Refused: the cluster still names its image, and reading it tries again.
assertEquals(IMAGE, bootstrapping.service.describeCluster(cluster.getId()).getBootstrapImage());
bootstrap.removes = true;
bootstrapping.runStepThread();
assertEquals(List.of(IMAGE, IMAGE), bootstrap.removed);
assertNull(bootstrapping.service.describeCluster(cluster.getId()).getBootstrapImage());
assertEquals(0, bootstrapping.stepThreadsWaiting());
}
@Test
void aClusterARestartLeftBootstrappingEndsWithErrors() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
EmrCluster cluster = bootstrapping.service.runJobFlow(bootstrapped(cluster("interrupted", true)), REGION);
EmrCluster ended = bootstrapping.restart().service.describeCluster(cluster.getId());
assertEquals("TERMINATED_WITH_ERRORS", ended.getState());
assertEquals("INTERNAL_ERROR", ended.getStateChangeReasonCode());
assertEquals(EmrService.BOOTSTRAP_INTERRUPTED, ended.getStateChangeMessage());
}
@Test
void aResetRemovesEveryImageABootstrapLeft() {
EmrServiceFixture.docker(runner, bootstrap, null).service.beforeReset();
assertEquals(List.of(Set.of()), bootstrap.kept);
}
// Two bootstrap actions, as RunJobFlow stores them.
private static EmrCluster bootstrapped(EmrCluster cluster) {
cluster.setBootstrapActions("""
[{"Name": "pandas", "ScriptBootstrapAction": {"Path": "%s", "Args": ["pandas", "2.2"]}},
{"Name": "jars", "ScriptBootstrapAction": {"Path": "s3://bucket/bootstrap/jars.sh"}}]"""
.formatted(INSTALL));
return cluster;
}
private static EmrInstanceGroup group(String type, int count) {
EmrInstanceGroup group = new EmrInstanceGroup();
group.setInstanceGroupType(type);
group.setInstanceType("m5.xlarge");
group.setRequestedInstanceCount(count);
return group;
}
// A spark-submit step through command-runner.jar, written for a cluster with YARN.
private static EmrStep sparkStep(String name, String actionOnFailure) {
EmrStep step = new EmrStep();
@@ -448,6 +666,43 @@ class EmrServiceContainerStepsTest {
* Runs a step's driver on the test's thread: it starts, does what the test asks, and ends with
* {@code outcome}, or stopped once {@link #stop} has been called for it.
*/
private static final class FakeBootstrap implements BootstrapRunner {
final List<Bootstrap> bootstraps = new ArrayList<>();
final List<String> stopped = new ArrayList<>();
final List<String> removed = new ArrayList<>();
final List<Set<String>> kept = new ArrayList<>();
Outcome outcome = Outcome.succeeded(IMAGE);
Runnable whileRunning = () -> { };
// Whether Docker removes an image it is asked to.
boolean removes = true;
@Override
public Outcome run(Bootstrap bootstrap, BooleanSupplier cancelled) {
bootstraps.add(bootstrap);
if (cancelled.getAsBoolean()) {
return Outcome.halted();
}
whileRunning.run();
return outcome;
}
@Override
public void stop(String clusterId) {
stopped.add(clusterId);
}
@Override
public boolean removeImage(String image) {
removed.add(image);
return removes;
}
@Override
public void removeImages(Set<String> kept) {
this.kept.add(kept);
}
}
private static final class FakeRunner implements SparkJobRunner {
final List<Job> jobs = new ArrayList<>();
final Set<String> stopped = new HashSet<>();
@@ -32,7 +32,7 @@ import static org.mockito.Mockito.when;
* recording the {@code aws.emr} events it publishes. Each event is handed to {@link #target} as it is
* published, as EventBridge's first delivery is, and checked to be published once the service is let go,
* and, for a wakeup's, after it, as the timer's own thread never sends them. In the {@code docker} runner
* mode a step's thread is one the test runs, with {@link #runStepThread}.
* mode a step's thread, and a bootstrap's, is one the test runs, with {@link #runStepThread}.
*/
final class EmrServiceFixture {
@@ -61,6 +61,7 @@ final class EmrServiceFixture {
private boolean waking;
private final InMemoryStorageFactory storage;
private final SparkJobRunner runner;
private final BootstrapRunner bootstrap;
private final IamService iam;
private final int[] durations;
@@ -70,20 +71,27 @@ final class EmrServiceFixture {
}
EmrServiceFixture(int startupDelaySeconds, int stepDurationSeconds, int terminationDelaySeconds) {
this(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), null, null,
this(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), null, null, null,
startupDelaySeconds, stepDurationSeconds, terminationDelaySeconds);
}
/** The service in the {@code docker} runner mode, every duration 0, its steps run by {@code runner}. */
static EmrServiceFixture docker(SparkJobRunner runner, IamService iam) {
return new EmrServiceFixture(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), runner, iam, 0, 0, 0);
return docker(runner, null, iam);
}
/** 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);
}
private EmrServiceFixture(InMemoryStorageFactory storage, MutableClock clock, SparkJobRunner runner,
IamService iam, int... durations) {
BootstrapRunner bootstrap, IamService iam, int... durations) {
this.storage = storage;
this.clock = clock;
this.runner = runner;
this.bootstrap = bootstrap;
this.iam = iam;
this.durations = durations;
EventBridgeService eventBridge = mock(EventBridgeService.class);
@@ -110,12 +118,12 @@ final class EmrServiceFixture {
public void deliver(Runnable delivery) {
deliveries.add(delivery);
}
}, runner, stepThreads::add, iam);
}, runner, bootstrap, 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, iam, durations);
return new EmrServiceFixture(storage, clock, runner, bootstrap, iam, durations);
}
/**
@@ -124,7 +132,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, stepThreads::add, iam);
runner, bootstrap, stepThreads::add, iam);
}
private EmulatorConfig config(boolean reconcile) {
@@ -20,9 +20,9 @@ import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
@@ -121,6 +121,9 @@ class EmrServerlessSparkRunnerTest {
EmrServerlessSparkRunner.image(null, "emr-spark-8.1.0"));
assertEquals("registry.internal/emr-serverless/spark/emr-7.5.0:20250425",
EmrServerlessSparkRunner.image("registry.internal/emr-serverless/spark/%s:20250425", "emr-7.5.0"));
// The image a cluster's bootstrap left, which its steps get by id.
String bootstrapped = "sha256:" + "2".repeat(64);
assertEquals(bootstrapped, EmrServerlessSparkRunner.image(bootstrapped, "emr-7.5.0"));
}
@Test
@@ -359,7 +362,8 @@ class EmrServerlessSparkRunnerTest {
InOrder order = inOrder(lifecycle, docker, s3);
order.verify(lifecycle).stop("driver", 0);
order.verify(docker).logContainerCmd("driver");
order.verify(s3).putObject(eq("logs"), eq("emr/j-1/steps/s-1/stdout.gz"), any(), anyString(), anyMap());
order.verify(s3).putObjectFromStream(eq("logs"), eq("emr/j-1/steps/s-1/stdout.gz"), any(), anyString(),
anyMap());
order.verify(lifecycle).stopAndRemove("driver", null, 0);
}
@@ -382,7 +386,7 @@ class EmrServerlessSparkRunnerTest {
assertEquals(0, outcome.exitCode());
verify(stream).close();
verify(s3, never()).putObject(anyString(), anyString(), any(), anyString(), anyMap());
verify(s3, never()).putObjectFromStream(anyString(), anyString(), any(), anyString(), anyMap());
} finally {
assertTrue(Thread.interrupted());
}
@@ -392,7 +396,7 @@ class EmrServerlessSparkRunnerTest {
void logsThatCannotBeWrittenLeaveTheRunAsItEnded() {
EmrServerlessSparkRunner runner = runner();
driverWrote(new Frame(StreamType.STDOUT, bytes("done\n")));
when(s3.putObject(anyString(), anyString(), any(), anyString(), anyMap()))
when(s3.putObjectFromStream(anyString(), anyString(), any(), anyString(), anyMap()))
.thenThrow(new AwsException("NoSuchBucket", "The specified bucket does not exist", 404));
SparkJobRunner.Outcome outcome = runner.run(job("s3://missing/emr/j-1/steps/s-1/"), progress);
@@ -413,7 +417,7 @@ class EmrServerlessSparkRunnerTest {
assertTrue(outcome.stopped());
verify(docker, never()).logContainerCmd(anyString());
verify(s3, never()).putObject(anyString(), anyString(), any(), anyString(), anyMap());
verify(s3, never()).putObjectFromStream(anyString(), anyString(), any(), anyString(), anyMap());
}
@Test
@@ -499,9 +503,9 @@ class EmrServerlessSparkRunnerTest {
// The object the runner put at key, gunzipped.
private String written(String bucket, String key) throws IOException {
ArgumentCaptor<byte[]> data = ArgumentCaptor.forClass(byte[].class);
verify(s3).putObject(eq(bucket), eq(key), data.capture(), eq("application/x-gzip"), eq(Map.of()));
try (GZIPInputStream gunzip = new GZIPInputStream(new ByteArrayInputStream(data.getValue()))) {
ArgumentCaptor<InputStream> data = ArgumentCaptor.forClass(InputStream.class);
verify(s3).putObjectFromStream(eq(bucket), eq(key), data.capture(), eq("application/x-gzip"), eq(Map.of()));
try (GZIPInputStream gunzip = new GZIPInputStream(data.getValue())) {
return new String(gunzip.readAllBytes(), StandardCharsets.UTF_8);
}
}