fix(emr): remove the release images a newer pull replaces (#8395)

A cluster's release image is named after the ids of the two images it
is made of, so a newer pull of either makes another, and the older one
stayed on the Docker daemon for good. Each release image is now
labelled with its kind: its release, the names of the two images and
what is copied. Once Floci makes a newer image of a kind, it removes the
others of that kind, without force, so one a container still uses stays
until the next newer one. Another kind (with or without Hive, or other
image names) is never touched, and an image made before the label is
left as it is.

Images of one kind are made one at a time, the two names resolved to
ids under that kind's lock, so one made of the older images never comes
after the newer one to remove it. A step or a bootstrap holds the image
it was given until it ends, as it may have no container of it yet, and
a held image is not removed either. A failure to remove one is logged
with its exception; the new image is there, so it fails nothing.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-14 22:20:04 -04:00
1 parent fb3c93018e
commit be6488b7ea
7 files changed
+280 -17

No files matched your search

+5 -1
View File
@@ -338,7 +338,11 @@ holding the driver and its executors, or a command or a script. The cluster itse
another). Floci makes it the first time one of the release's clusters needs it: a container of the release's
image, never started, gets the Hive image's folders, and is committed, as a bootstrap's is, as
`floci-aws-emr-release:<release>-<hash>`, 0.6 GB more than the release's image, and kept for the release's next
cluster (`docker image rm` removes it); a newer pull of either image makes another. A failure to make it, a Hive
cluster (`docker image rm` removes it); a newer pull of either image makes another, which replaces the ones made
before from the same two image names for the same release and kind (with Hive or without): each is removed then,
unless a container still uses it, or a step or a bootstrap given it has yet to end, which keeps it until the next
newer one. Images of one kind are made one at a time, so one made of the older images never comes after the newer
one. One made before Floci labelled images with their kind is left. A failure to make it, a Hive
image that cannot be pulled say, fails the step that needed it ("The step could not start: ..."), or, for a
bootstrap, ends the cluster with `INTERNAL_ERROR`. The two images ship different builds of one goodies JAR under
one name, so Tez keeps the Hive image's, and Hive runs with the Hive image's Hadoop configuration, which puts Tez
@@ -1,7 +1,9 @@
package io.floci.aws.services.emr;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.exception.ConflictException;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Image;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.config.EmulatorConfig.EcsServiceConfig.ImagePullBehavior;
import io.floci.aws.core.common.Digests;
@@ -22,6 +24,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -37,7 +40,8 @@ import java.util.concurrent.ConcurrentHashMap;
* leading there, and the Hive image's Hadoop configuration, which puts Tez on the class path, goes to
* {@link EmrServerlessSparkRunner#HIVE_HADOOP_CONF}, for Hive alone. The image is named after its release, the ids of
* the two images and what is copied, so a newer pull of either, or a change to what is copied, makes another, and it is
* kept for the release's next cluster. A release of the AWS runtime for Apache Spark has no Hive image, and another
* kept for the release's next cluster; the one a newer pull makes replaces those of its kind made before
* ({@link #KIND_LABEL}). A release of the AWS runtime for Apache Spark has no Hive image, and another
* release's HDFS and YARN do not run on its newer Hadoop, so its image gets the whole of that release's Hadoop, in a
* folder apart, which only its primary node's daemons run from.
*/
@@ -47,6 +51,9 @@ public class EmrReleaseImages implements ReleaseImages {
private static final Logger LOG = Logger.getLogger(EmrReleaseImages.class);
private static final String SERVICE = "emr";
private static final String COMPONENT = "emr-release";
// An image's kind: its release, the names of the two images it is made of, and what is copied. The image made after
// a newer pull of either replaces the others of its kind.
static final String KIND_LABEL = "io.floci.emr-release.kind";
private static final String EMR_SHARE = "/usr/share/aws/emr";
private static final String GOODIES = EMR_SHARE + "/serverless-goodies/lib";
private static final String HIVE_GOODIES = "serverless-goodies-hive/lib";
@@ -83,8 +90,13 @@ public class EmrReleaseImages implements ReleaseImages {
new Copy("/usr/lib/hadoop-mapreduce", HADOOP_APART),
new Copy("/usr/lib/hadoop-yarn", HADOOP_APART));
// One making at a time for each image; another thread asking for it waits, then finds it there.
// One making at a time for each kind of image, from the ids its two names lead to once it has the lock, so one made
// of images a newer pull has since replaced is never made after the newer one, to remove it; another thread asking
// for the same image waits, then finds it there.
private final Map<String, Object> making = new ConcurrentHashMap<>();
// The images given to a step or a bootstrap that has not ended, by id, with how many hold each: none of them is
// removed, as no container of it may be there yet to keep it.
private final Map<String, Integer> held = new ConcurrentHashMap<>();
private final ContainerLifecycleManager lifecycleManager;
private final ContainerBuilder containerBuilder;
@@ -117,14 +129,17 @@ public class EmrReleaseImages implements ReleaseImages {
: withHive ? COPIES : HADOOP_COPIES;
String spark = containerBuilder.resolveImage(sparkImage);
String hive = containerBuilder.resolveImage(hiveImage);
String sparkId = imageCacheService.resolveForLaunch(spark, ImagePullBehavior.PREFER_CACHED, null).imageId();
String hiveId = imageCacheService.resolveForLaunch(hive, ImagePullBehavior.PREFER_CACHED, null).imageId();
String repository = ContainerStorageHelper.dockerName(config, COMPONENT);
String tag = releaseLabel + "-" + Digests.sha256Hex(sparkId + "\n" + hiveId + "\n" + copies).substring(0, 12);
synchronized (making.computeIfAbsent(repository + ":" + tag, name -> new Object())) {
String kind = Digests.sha256Hex(releaseLabel + "\n" + spark + "\n" + hive + "\n" + copies).substring(0, 12);
synchronized (making.computeIfAbsent(repository + ":" + kind, name -> new Object())) {
String sparkId = imageCacheService.resolveForLaunch(spark, ImagePullBehavior.PREFER_CACHED, null)
.imageId();
String hiveId = imageCacheService.resolveForLaunch(hive, ImagePullBehavior.PREFER_CACHED, null).imageId();
String tag = releaseLabel + "-"
+ Digests.sha256Hex(sparkId + "\n" + hiveId + "\n" + copies).substring(0, 12);
DockerClient docker = lifecycleManager.getDockerClient();
try {
return docker.inspectImageCmd(repository + ":" + tag).exec().getId();
return hold(docker.inspectImageCmd(repository + ":" + tag).exec().getId());
} catch (NotFoundException e) {
LOG.infov("Making {0}:{1} for EMR clusters {2}, from {3} and {4}", repository, tag,
withHive ? "with Hive" : "without Hive", spark, hive);
@@ -134,6 +149,8 @@ public class EmrReleaseImages implements ReleaseImages {
labels.put(ContainerStorageHelper.SERVICE_LABEL, SERVICE);
labels.put(ContainerStorageHelper.COMPONENT_LABEL, COMPONENT);
labels.put(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config));
labels.put(KIND_LABEL, kind);
String made;
List<String> containers = new ArrayList<>();
try {
String target = docker.createContainerCmd(sparkId).withLabels(labels).exec().getId();
@@ -144,7 +161,7 @@ public class EmrReleaseImages implements ReleaseImages {
RetryingTarCopier.copyStreamed(docker, target, copy.into(), copy.from(),
out -> copy(docker.copyArchiveFromContainerCmd(source, copy.from()).exec(), out, copy));
}
return lifecycleManager.commit(target, repository, tag,
made = lifecycleManager.commit(target, repository, tag,
user == null || user.isBlank() ? "root" : user, labels);
} finally {
for (String container : containers) {
@@ -156,6 +173,52 @@ public class EmrReleaseImages implements ReleaseImages {
}
}
}
removeReplaced(docker, labels, made, repository + ":" + tag);
return hold(made);
}
}
@Override
public void released(String imageId) {
held.computeIfPresent(imageId, (id, holders) -> holders > 1 ? holders - 1 : null);
}
// The image is held, under its kind's lock, until released(), before a step or a bootstrap gets its id.
private String hold(String imageId) {
held.merge(imageId, 1, Integer::sum);
return imageId;
}
/**
* Removes the images of {@code kind} that {@code made}, named {@code name}, replaces: made before a newer pull of
* either image, which no cluster asks for again, as the ids it would now be made of lead to {@code made}. One a
* step or a bootstrap holds stays, and so does one a container still uses, as Docker refuses to remove it without
* force, each until the next newer one is made. One made before images were labelled with their kind is left. The
* new image is there either way, so a failure to remove the others fails nothing, and is logged.
*/
private void removeReplaced(DockerClient docker, Map<String, String> kind, String made, String name) {
List<Image> images;
try {
images = docker.listImagesCmd().withLabelFilter(kind).exec();
} catch (RuntimeException e) {
LOG.warnv(e, "Could not list the EMR release images {0} replaces: {1}", name, e.getMessage());
return;
}
for (Image image : images) {
if (made.equals(image.getId()) || held.containsKey(image.getId())
|| (image.getRepoTags() != null && Arrays.asList(image.getRepoTags()).contains(name))) {
continue;
}
try {
docker.removeImageCmd(image.getId()).exec();
LOG.infov("Removed EMR release image {0}, which {1} replaces", image.getId(), name);
} catch (ConflictException e) {
LOG.debugv("Kept EMR release image {0}, which a container still uses: {1}", image.getId(),
e.getMessage());
} catch (RuntimeException e) {
LOG.warnv(e, "Could not remove EMR release image {0}, which {1} replaces: {2}", image.getId(), name,
e.getMessage());
}
}
}
@@ -1633,9 +1633,10 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
} else {
SparkJobRunner.Outcome outcome;
StepProgress progress = new StepProgress(launch);
String image = null;
try {
SparkJobRunner.Job running = releaseImage != null && !progress.cancelled()
? job.inImage(releaseImage.get()) : job;
image = releaseImage != null && !progress.cancelled() ? releaseImage.get() : null;
SparkJobRunner.Job running = image != null ? job.inImage(image) : job;
// The cluster's storage is there, its HDFS running, before its first step's container mounts it. A step
// a cancel, its cluster's end or a reset has passed does not start, so it makes none.
if (job.storage() != null && !progress.cancelled()) {
@@ -1656,6 +1657,11 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
LOG.warnv(e, "EMR step {0} could not run", launch.stepId());
outcome = SparkJobRunner.Outcome.couldNotStart(e.getMessage());
}
} finally {
// Its containers have come and gone, or never came, so a newer image of its kind may remove this one.
if (image != null) {
releaseImages.released(image);
}
}
// 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.
@@ -1907,12 +1913,19 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
BooleanSupplier cancelled = () -> teardowns.get() != launch.teardownsBefore()
|| !RequestScopes.callAs(launch.accountId(), launch.region(), () -> stillBootstrapping(launch));
BootstrapRunner.Outcome outcome;
String image = null;
try {
outcome = bootstrapRunner.run(releaseImage != null && !cancelled.getAsBoolean()
? bootstrap.inImage(releaseImage.get()) : bootstrap, cancelled);
image = releaseImage != null && !cancelled.getAsBoolean() ? releaseImage.get() : null;
outcome = bootstrapRunner.run(image != null ? bootstrap.inImage(image) : bootstrap, cancelled);
} catch (RuntimeException e) {
LOG.warnv(e, "The bootstrap actions of EMR cluster {0} could not run", launch.clusterId());
outcome = BootstrapRunner.Outcome.couldNotRun(e.getMessage());
} finally {
// An image it kept is built on this one, which Docker then keeps, so a newer one may remove it only as that
// image goes.
if (image != null) {
releaseImages.released(image);
}
}
BootstrapRunner.Outcome ended = outcome;
// One that ended, however, after a teardown began ends as one Floci stopped, which starts no step: the
@@ -15,4 +15,11 @@ public interface ReleaseImages {
* the two; a failure is thrown.
*/
String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive);
/**
* The step or the bootstrap that {@link #image} gave {@code imageId} to has ended, so a newer image of its kind may
* remove it; until then it stays, as no container of it may be there yet to keep it. Once for each id given.
*/
default void released(String imageId) {
}
}
@@ -8,12 +8,17 @@ import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.InfoCmd;
import com.github.dockerjava.api.command.InspectImageCmd;
import com.github.dockerjava.api.command.InspectImageResponse;
import com.github.dockerjava.api.command.ListImagesCmd;
import com.github.dockerjava.api.command.RemoveContainerCmd;
import com.github.dockerjava.api.command.RemoveImageCmd;
import com.github.dockerjava.api.exception.ConflictException;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.ContainerConfig;
import com.github.dockerjava.api.model.Image;
import com.github.dockerjava.api.model.Info;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.config.EmulatorConfig.EcsServiceConfig.ImagePullBehavior;
import io.floci.aws.core.common.Digests;
import io.floci.aws.core.common.docker.ContainerBuilder;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.common.docker.ContainerStorageHelper;
@@ -41,6 +46,7 @@ import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -71,6 +77,9 @@ class EmrReleaseImagesTest {
private final ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
private final ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
private final ImageCacheService imageCache = mock(ImageCacheService.class);
// The images of the made image's kind the daemon lists, and the command listing them.
private final List<Image> listed = new ArrayList<>();
private final ListImagesCmd listImages = mock(ListImagesCmd.class, RETURNS_SELF);
private final EmrReleaseImages images = new EmrReleaseImages(lifecycle, containerBuilder, imageCache, config);
@Test
@@ -138,9 +147,13 @@ class EmrReleaseImagesTest {
assertEquals(List.of("/usr/lib/hadoop-hdfs", "/usr/lib/hadoop-mapreduce", "/usr/lib/hadoop-yarn"), copied);
assertTrue(EmrReleaseImages.COPIES.containsAll(EmrReleaseImages.HADOOP_COPIES));
ArgumentCaptor<String> tags = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<Map<String, String>> labels = mapCaptor();
images.image("emr-7.5.0", SPARK, HIVE, true);
verify(lifecycle, times(2)).commit(eq("target"), anyString(), tags.capture(), anyString(), any());
verify(lifecycle, times(2)).commit(eq("target"), anyString(), tags.capture(), anyString(), labels.capture());
assertNotEquals(tags.getAllValues().get(0), tags.getAllValues().get(1));
// Nor does either replace the other: they are of two kinds.
assertNotEquals(labels.getAllValues().get(0).get(EmrReleaseImages.KIND_LABEL),
labels.getAllValues().get(1).get(EmrReleaseImages.KIND_LABEL));
}
@Test
@@ -156,6 +169,129 @@ class EmrReleaseImagesTest {
argThat(tag -> tag.matches("emr-spark-8\\.0\\.0-[0-9a-f]{12}")), eq("hadoop:hadoop"), any());
}
@Test
void theImageANewerPullMakesReplacesTheOlderOnesOfItsKindButOneAContainerStillUses() {
String repository = ContainerStorageHelper.dockerName(config, "emr-release");
String name = repository + ":emr-7.5.0-"
+ Digests.sha256Hex("sha256:spark\nsha256:hive\n" + EmrReleaseImages.COPIES).substring(0, 12);
// The one just made by its id, as an untagged image is listed, and one under its name.
listed.addAll(List.of(image("sha256:made", "<none>:<none>"), image("sha256:same-name", name),
image("sha256:older", repository + ":emr-7.5.0-000000000000"),
image("sha256:used", repository + ":emr-7.5.0-111111111111")));
RemoveImageCmd removed = mock(RemoveImageCmd.class, RETURNS_SELF);
when(docker.removeImageCmd("sha256:older")).thenReturn(removed);
RemoveImageCmd refused = mock(RemoveImageCmd.class, RETURNS_SELF);
when(refused.exec()).thenThrow(new ConflictException("image is being used by running container"));
when(docker.removeImageCmd("sha256:used")).thenReturn(refused);
makesMissing(true);
// Only images of its kind are listed: its release, the names of the two it is made of, and what is copied.
ArgumentCaptor<Map<String, String>> committed = mapCaptor();
verify(lifecycle).commit(eq("target"), eq(repository), anyString(), anyString(), committed.capture());
verify(listImages).withLabelFilter(committed.getValue());
assertTrue(committed.getValue().get(EmrReleaseImages.KIND_LABEL).matches("[0-9a-f]{12}"));
// Without force, so Docker keeps one a container uses.
verify(removed, never()).withForce(true);
verify(docker).removeImageCmd("sha256:used");
verify(docker, never()).removeImageCmd("sha256:made");
verify(docker, never()).removeImageCmd("sha256:same-name");
}
@Test
void anImageAStepOrABootstrapHoldsStaysUntilItIsReleased() {
String repository = ContainerStorageHelper.dockerName(config, "emr-release");
when(lifecycle.getDockerClient()).thenReturn(docker);
when(containerBuilder.resolveImage(anyString()))
.thenAnswer(invocation -> "mirror/" + invocation.getArgument(0));
resolves("mirror/" + SPARK, "sha256:spark");
resolves("mirror/" + HIVE, "sha256:hive");
InspectImageCmd there = mock(InspectImageCmd.class);
InspectImageResponse given = mock(InspectImageResponse.class);
when(given.getId()).thenReturn("sha256:given");
when(there.exec()).thenReturn(given);
when(docker.inspectImageCmd(argThat((String image) -> image != null && image.startsWith(repository + ":"))))
.thenReturn(there);
// A step is given the image there, and has no container of it yet when a newer pull makes another.
assertEquals("sha256:given", images.image("emr-7.5.0", SPARK, HIVE, true));
listed.add(image("sha256:given", repository + ":emr-7.5.0-000000000000"));
when(docker.removeImageCmd("sha256:given")).thenReturn(mock(RemoveImageCmd.class, RETURNS_SELF));
makesMissing(true);
verify(docker, never()).removeImageCmd("sha256:given");
images.released("sha256:given");
makesMissing(true);
verify(docker).removeImageCmd("sha256:given");
}
@Test
void anImageMadeOfOlderImagesIsNeverMadeAfterANewerOneOfItsKindToRemoveIt() throws InterruptedException {
when(lifecycle.getDockerClient()).thenReturn(docker);
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
String repository = ContainerStorageHelper.dockerName(config, "emr-release");
resolves(SPARK, "sha256:spark");
// The Hive image's name leads to a newer id once a newer image is pulled under it.
when(imageCache.resolveForLaunch(HIVE, ImagePullBehavior.PREFER_CACHED, null)).thenReturn(
new LaunchImage("sha256:hive", null), new LaunchImage("sha256:newer-hive", null));
when(docker.inspectImageCmd(anyString())).thenAnswer(invocation -> {
InspectImageCmd inspect = mock(InspectImageCmd.class);
if (invocation.<String>getArgument(0).startsWith(repository + ":")) {
when(inspect.exec()).thenThrow(new NotFoundException("missing"));
} else {
when(inspect.exec()).thenReturn(mock(InspectImageResponse.class, RETURNS_DEEP_STUBS));
}
return inspect;
});
CreateContainerCmd create = mock(CreateContainerCmd.class, RETURNS_SELF);
when(create.exec()).thenReturn(mock(CreateContainerResponse.class));
when(docker.createContainerCmd(anyString())).thenReturn(create);
when(docker.copyArchiveFromContainerCmd(any(), anyString())).thenAnswer(invocation -> {
CopyArchiveFromContainerCmd from = mock(CopyArchiveFromContainerCmd.class);
when(from.exec()).thenAnswer(read -> new ByteArrayInputStream(new byte[0]));
return from;
});
when(docker.copyArchiveToContainerCmd(any())).thenReturn(mock(CopyArchiveToContainerCmd.class, RETURNS_SELF));
when(docker.removeContainerCmd(any())).thenReturn(mock(RemoveContainerCmd.class, RETURNS_SELF));
when(docker.removeImageCmd(anyString())).thenReturn(mock(RemoveImageCmd.class, RETURNS_SELF));
when(listImages.exec()).thenAnswer(invocation -> List.copyOf(listed));
when(docker.listImagesCmd()).thenReturn(listImages);
CountDownLatch committing = new CountDownLatch(1);
CountDownLatch committed = new CountDownLatch(1);
AtomicInteger commits = new AtomicInteger();
when(lifecycle.commit(any(), anyString(), anyString(), any(), any())).thenAnswer(invocation -> {
String tag = invocation.getArgument(2);
if (commits.getAndIncrement() == 0) {
committing.countDown();
assertTrue(committed.await(10, TimeUnit.SECONDS));
listed.add(image("sha256:older", repository + ":" + tag));
return "sha256:older";
}
listed.add(image("sha256:newer", repository + ":" + tag));
return "sha256:newer";
});
AtomicReference<String> first = new AtomicReference<>();
Thread older = Thread.ofPlatform().start(() -> first.set(images.image("emr-7.5.0", SPARK, HIVE, true)));
assertTrue(committing.await(10, TimeUnit.SECONDS));
AtomicReference<String> second = new AtomicReference<>();
Thread newer = Thread.ofPlatform().start(() -> second.set(images.image("emr-7.5.0", SPARK, HIVE, true)));
ThreadStates.awaitBlockedOrDone(newer);
// It waits for the image of its kind being made before it reads where the two names lead.
verify(imageCache, times(1)).resolveForLaunch(HIVE, ImagePullBehavior.PREFER_CACHED, null);
committed.countDown();
older.join(10_000);
newer.join(10_000);
assertEquals("sha256:older", first.get());
assertEquals("sha256:newer", second.get());
// The newer one is made last, and the older one, which the first caller still holds, stays too.
verify(docker, never()).removeImageCmd("sha256:newer");
verify(docker, never()).removeImageCmd("sha256:older");
}
@Test
void anImageOfAReleaseWithAHiveImageRunsItsOwnHadoop() {
assertNull(EmrReleaseImages.hadoopFolder("emr-7.5.0"));
@@ -190,6 +326,8 @@ class EmrReleaseImagesTest {
});
when(docker.copyArchiveToContainerCmd(any())).thenReturn(mock(CopyArchiveToContainerCmd.class, RETURNS_SELF));
when(docker.removeContainerCmd(any())).thenReturn(mock(RemoveContainerCmd.class, RETURNS_SELF));
when(listImages.exec()).thenAnswer(invocation -> listed);
when(docker.listImagesCmd()).thenReturn(listImages);
CountDownLatch committing = new CountDownLatch(1);
CountDownLatch committed = new CountDownLatch(1);
when(lifecycle.commit(any(), anyString(), anyString(), any(), any())).thenAnswer(invocation -> {
@@ -244,7 +382,7 @@ class EmrReleaseImagesTest {
when(docker.inspectImageCmd(anyString())).thenAnswer(invocation -> {
asked.add(invocation.getArgument(0));
InspectImageCmd there = mock(InspectImageCmd.class);
when(there.exec()).thenReturn(mock(InspectImageResponse.class));
when(there.exec()).thenReturn(new InspectImageResponse().withId("sha256:made"));
return there;
});
@@ -317,7 +455,7 @@ class EmrReleaseImagesTest {
resolves("mirror/" + HIVE, "sha256:hive");
InspectImageCmd missing = mock(InspectImageCmd.class);
when(missing.exec()).thenThrow(new NotFoundException("missing"));
when(docker.inspectImageCmd(argThat((String image) -> image.startsWith(repository + ":"))))
when(docker.inspectImageCmd(argThat((String image) -> image != null && image.startsWith(repository + ":"))))
.thenReturn(missing);
InspectImageCmd spark = mock(InspectImageCmd.class);
InspectImageResponse sparkImage = mock(InspectImageResponse.class);
@@ -340,6 +478,8 @@ class EmrReleaseImagesTest {
when(lifecycle.commit(eq("target"), eq(repository), anyString(), eq("hadoop:hadoop"), any()))
.thenReturn("sha256:made");
when(docker.removeContainerCmd(anyString())).thenReturn(mock(RemoveContainerCmd.class, RETURNS_SELF));
when(listImages.exec()).thenAnswer(invocation -> listed);
when(docker.listImagesCmd()).thenReturn(listImages);
assertEquals("sha256:made", images.image(release, SPARK, HIVE, withHive));
return copied;
@@ -355,6 +495,18 @@ class EmrReleaseImagesTest {
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
}
private static Image image(String id, String tag) {
Image image = mock(Image.class);
when(image.getId()).thenReturn(id);
when(image.getRepoTags()).thenReturn(new String[] {tag});
return image;
}
@SuppressWarnings("unchecked")
private static ArgumentCaptor<Map<String, String>> mapCaptor() {
return ArgumentCaptor.forClass(Map.class);
}
private void container(String image, String id) {
CreateContainerCmd create = mock(CreateContainerCmd.class, RETURNS_SELF);
CreateContainerResponse created = mock(CreateContainerResponse.class);
@@ -1432,6 +1432,22 @@ class EmrServiceContainerStepsTest {
assertEquals("s3://logs/emr/" + cluster.getId() + "/steps/" + stepId + "/", job.logFolder());
assertEquals(List.of(cluster.getId()), fixture.clusterStorage.created);
assertEquals("COMPLETED", service.describeStep(cluster.getId(), stepId).getState());
// Held from when the step got it until it ended, so no newer image of its kind removed it under the step.
assertEquals(List.of(EmrServiceFixture.RecordingReleaseImages.IMAGE), fixture.releaseImages.released);
}
@Test
void aStepThatCouldNotStartReleasesTheImageItWasGiven() {
EmrCluster requested = cluster("hive-failing", true, hiveStep("report", "-e", "show tables;"));
requested.setApplications("[{\"Name\": \"Hive\"}]");
runner.whileRunning = () -> {
throw new IllegalStateException("The step's container could not be created");
};
service.runJobFlow(requested, REGION);
fixture.runStepThread();
assertEquals(List.of(EmrServiceFixture.RecordingReleaseImages.IMAGE), fixture.releaseImages.released);
}
@Test
@@ -1462,8 +1478,9 @@ class EmrServiceContainerStepsTest {
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, bootstrap.bootstraps.get(0).imageTemplate());
assertEquals(SparkJobRunner.Engine.HIVE, runner.jobs.get(0).engine());
assertEquals(IMAGE, runner.jobs.get(0).imageTemplate());
// Made once, for the bootstrap: the image it left holds it.
// Made once, for the bootstrap: the image it left holds it. Released once the bootstrap ended.
assertEquals(1, bootstrapping.releaseImages.asked.size());
assertEquals(List.of(EmrServiceFixture.RecordingReleaseImages.IMAGE), bootstrapping.releaseImages.released);
}
@Test
@@ -151,6 +151,8 @@ final class EmrServiceFixture {
static final String IMAGE = "sha256:" + "3".repeat(64);
// Each image asked for: its release, then the two it is made of, then whether it has Hive.
final List<List<String>> asked = new ArrayList<>();
// Each image released, by id.
final List<String> released = new ArrayList<>();
RuntimeException failure;
@Override
@@ -161,6 +163,11 @@ final class EmrServiceFixture {
}
return IMAGE;
}
@Override
public void released(String imageId) {
released.add(imageId);
}
}
final ObjectMapper objectMapper = new ObjectMapper();