fix(emr-serverless): resolve a custom image as its application starts (#8542)

EMR Serverless resolves a custom image's digest either for each workload
or once, at the application's start: "Custom images are resolved to a
digest at application start; that digest is used for all jobs until the
application restarts". The user guide's table makes that the default for
EMR 7.13 and earlier (applicationLevelDigestResolution = true) and
resolution per workload the default from 7.14. Floci resolved every
custom image for each run, whatever the release or the setting.

Where an image configuration's applicationLevelDigestResolution is true,
or left unset on 7.13 or earlier, the application now reads the digest
of its image in Floci's ECR as it starts, gives it to the image
configuration as its resolvedImageDigest, and each run pulls the image by
that digest until the application starts again, an update meanwhile
notwithstanding; a job run's image configurations carry it. An image
outside ECR, or one Floci's ECR does not hold, has no digest to read and
is resolved for each run, as before, as is one in another account's
repository, which Floci does not check the application may pull; any
other answer from Floci's ECR fails the start, leaving the application
as it was. An update that turns a running application's image to
resolution per workload ends its pin, and a stopped application reports
no digest. EcrRegistryManager gains ecrImage, the repository and the tag
or digest an image URI names.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-15 23:02:40 -04:00
1 parent b31b76e4aa
commit 9d65db843b
10 files changed
+483 -11

No files matched your search

+8 -4
View File
@@ -70,8 +70,11 @@ updates on running applications are not supported on applications with pre-initi
already going keeps the image and the maximum capacity it was launched with, and a new run, or a new attempt of a
run, takes the application's current ones: "New workloads submitted after the update automatically will use the new
image, while existing workloads continue with the original image". On a release up to 7.13 whose
`applicationLevelDigestResolution` is left true, AWS keeps the image it resolved at the application's start until the
application restarts; Floci resolves each run's image (see the custom images limitation) and runs the new one.
`applicationLevelDigestResolution` is left true, or any whose image configuration sets it true, "Custom images are
resolved to a digest at application start; that digest is used for all jobs until the application restarts": a new
run keeps the image the application resolved as it started (see **Image** under job runs) until it starts again,
unless the update turns that image configuration's `applicationLevelDigestResolution` to false, after which each run
resolves the image it is given.
`DeleteApplication` leaves the application in `TERMINATED` state. `GetApplication` continues to
report that state so lifecycle waiters can observe it, while an unfiltered `ListApplications`
@@ -247,7 +250,8 @@ worker of its own on EMR Serverless (see **Executors** below).
`image-template` names another image than the release's, such as a mirror or a dated tag of it:
`registry.internal/emr-serverless/spark/%s:20250425`. `GetJobRun` reports the image configurations each attempt
applies, as its application had them when the attempt was made: its `imageConfiguration`, and its worker types'
in `workerTypeSpecifications`, as AWS's do when digests are resolved for each run ("To identify which image
in `workerTypeSpecifications` (those the application resolved as it started, with that digest), as AWS's do when
digests are resolved for each run ("To identify which image
version each job is running, the GetJobRun API response returns the resolvedImageDigest for that specific job").
The driver's configuration, its worker type's or else the application's, has the `resolvedImageDigest` of the
image the attempt pulled for the driver, its manifest digest in Floci's ECR; the executors' has theirs, or the
@@ -306,7 +310,7 @@ application's `imageConfiguration`; a `TezTask` image is not used, as Tez's task
* **Archives**: only the archives of `spark.archives` that are in S3 are unpacked into the driver's working
directory; Spark alone unpacks the others, into its own files folder. Floci reads an archive itself,
whatever the execution role may read, though Spark's own read of it uses the role's credentials.
* **Custom images**: Floci does not check an `imageUri` against the model's pattern, which would refuse the repository URIs Floci's own ECR hands out, nor that the image was built from its release's base image (AWS refuses one that was not from `emr-7.14.0` and `emr-spark-8.1.0` on), nor the image's size. An image that cannot be pulled fails the run, not the request that names it. Every run resolves its image again, as releases from 7.14 do and earlier ones with `applicationLevelDigestResolution` false: Floci keeps no digest from the application's start, and reports no `resolvedImageDigest` on the application; a job run's comes from its attempt's own pull (see **Image** above), and its image configurations carry no `applicationLevelDigestResolution`.
* **Custom images**: Floci does not check an `imageUri` against the model's pattern, which would refuse the repository URIs Floci's own ECR hands out, nor that the image was built from its release's base image (AWS refuses one that was not from `emr-7.14.0` and `emr-spark-8.1.0` on), nor the image's size. An image that cannot be pulled fails the run, not the request that names it. An image's digest is resolved as the application starts where its `applicationLevelDigestResolution` is true, or left unset on EMR 7.13 or earlier, as the user guide's table has it, and AWS's "Custom images are resolved to a digest at application start; that digest is used for all jobs until the application restarts": the application's image configuration gets the digest of the image in Floci's ECR as its `resolvedImageDigest`, and each run pulls the image by it until the application starts again; a stopped application reports none. An image outside ECR, one in another account's repository (Floci does not check that the application may pull it), or one Floci's ECR does not hold or cannot read without Docker, has no digest to read and is resolved for each run, as every image is from 7.14 on; any other answer from Floci's ECR fails `StartApplication` with `InternalServerException`; such a run's digest comes from its attempt's own pull (see **Image** above), and a job run's image configurations carry no `applicationLevelDigestResolution`.
* **Not emulated**: the "EMR Serverless Job Run Retry" event, as Floci sends no EMR Serverless events, queuing (`QUEUED`), `totalResourceUtilization` and `billedResourceUtilization`, and `shutdownGracePeriodInSeconds` (accepted and ignored: a cancelled run's driver is stopped at once).
* **Instant Start/Stop**: Floci marks the application `STARTED` or `STOPPED` immediately without provisioning actual compute capacity in the background.
* **Data Plane**: Floci does not implement the data-plane API, such as interactive sessions.
@@ -87,6 +87,11 @@ public class EcrRegistryManager {
+ AwsPartitions.dnsSuffixRegex() + "|" + FLOCI_REGISTRY_HOST + ")"
+ "|" + FLOCI_REGISTRY_HOST + "/[0-9]{12}/([a-z0-9-]+))/.+$");
/** The account, Region and path of an image in an ECR repository, in {@link #ECR_IMAGE_REGION}'s forms. */
private static final Pattern ECR_IMAGE_PARTS = Pattern.compile("^(?:([0-9]{12})\\.dkr\\.ecr\\.([a-z0-9-]+)\\.(?:"
+ AwsPartitions.dnsSuffixRegex() + "|" + FLOCI_REGISTRY_HOST + ")"
+ "|" + FLOCI_REGISTRY_HOST + "/([0-9]{12})/([a-z0-9-]+))/(.+)$");
/**
* The container name actually in use. Differs from {@link #registryContainerName()} only when
* a legacy-named container surviving a pre-migration version was adopted.
@@ -222,6 +227,36 @@ public class EcrRegistryManager {
return rewritten;
}
/**
* The ECR repository an image URI names, in any of the forms {@link #imageRegion} reads, and the tag or digest it
* asks for, its tag {@code latest} where it names neither; empty for an image outside ECR.
*/
public static Optional<EcrImage> ecrImage(String image) {
Matcher m = image != null ? ECR_IMAGE_PARTS.matcher(image) : null;
if (m == null || !m.matches()) {
return Optional.empty();
}
String path = m.group(5);
String digest = null;
int at = path.indexOf('@');
if (at >= 0) {
digest = path.substring(at + 1);
path = path.substring(0, at);
}
String tag = null;
int colon = path.lastIndexOf(':');
if (colon > path.lastIndexOf('/')) {
tag = path.substring(colon + 1);
path = path.substring(0, colon);
}
return Optional.of(new EcrImage(m.group(1) != null ? m.group(1) : m.group(3),
m.group(2) != null ? m.group(2) : m.group(4), path, digest == null && tag == null ? "latest" : tag,
digest));
}
/** An image in an ECR repository: its registry, Region and repository, and the tag or the digest asked for. */
public record EcrImage(String registryId, String region, String repository, String tag, String digest) {}
/**
* The Region of the ECR repository an image URI names, AWS-shaped or one Floci's ECR hands out; empty for an
* image outside ECR.
@@ -618,12 +618,21 @@ public class EmrServerlessJobRunService implements Resettable {
* digest until the attempt's runner resolves that image, {@link #imageDigestResolved}.
*/
private static void applyImages(JobRun run, Application app) {
run.setImageConfiguration(appliedImage(app.getImageConfiguration()));
run.setImageConfiguration(pinned(app, "") != null ? copyOf(pinned(app, ""))
: appliedImage(app.getImageConfiguration()));
Map<String, WorkerTypeSpecification> workerTypes = new LinkedHashMap<>();
Map<String, WorkerTypeSpecification> specifications = new LinkedHashMap<>();
if (app.getWorkerTypeSpecifications() != null) {
app.getWorkerTypeSpecifications().forEach((workerType, specification) -> {
ImageConfiguration image = specification != null
? appliedImage(specification.getImageConfiguration()) : null;
specifications.putAll(app.getWorkerTypeSpecifications());
}
if (app.getPinnedImages() != null) {
app.getPinnedImages().keySet().stream().filter(key -> !key.isEmpty())
.forEach(key -> specifications.putIfAbsent(key, null));
}
if (!specifications.isEmpty()) {
specifications.forEach((workerType, specification) -> {
ImageConfiguration image = pinned(app, workerType) != null ? copyOf(pinned(app, workerType))
: specification != null ? appliedImage(specification.getImageConfiguration()) : null;
if (image != null) {
WorkerTypeSpecification applied = new WorkerTypeSpecification();
applied.setImageConfiguration(image);
@@ -643,6 +652,30 @@ public class EmrServerlessJobRunService implements Resettable {
return applied;
}
// The image the application resolved for a worker type ("" its own) as it started, which its runs take until it
// starts again (EmrServerlessService.pinImages); null where it resolved none.
private static ImageConfiguration pinned(Application app, String key) {
return app.getPinnedImages() != null ? app.getPinnedImages().get(key) : null;
}
private static ImageConfiguration copyOf(ImageConfiguration image) {
ImageConfiguration copy = new ImageConfiguration();
copy.setImageUri(image.getImageUri());
copy.setResolvedImageDigest(image.getResolvedImageDigest());
return copy;
}
// The image a run pulls for a resolved one: its repository by its digest, as its tag may since name another.
private static String byDigest(ImageConfiguration image) {
String uri = image.getImageUri();
if (uri.contains("@")) {
return uri;
}
int colon = uri.lastIndexOf(':');
String repository = colon > uri.lastIndexOf('/') ? uri.substring(0, colon) : uri;
return repository + "@" + image.getResolvedImageDigest();
}
// The image configuration an attempt applies to a worker type: the worker type's own, else the run's, as
// workerImage chose its image.
private static ImageConfiguration appliedImage(JobRun run, String workerType) {
@@ -651,14 +684,21 @@ public class EmrServerlessJobRunService implements Resettable {
return worker != null ? worker.getImageConfiguration() : run.getImageConfiguration();
}
// A worker type's custom image, else the application's, else null for the release's.
// A worker type's custom image, else the application's, else null for the release's: the one the application
// resolved as it started where it resolved it then, by its digest, else the one it names now.
private static String workerImage(Application app, String workerType) {
if (pinned(app, workerType) != null) {
return byDigest(pinned(app, workerType));
}
WorkerTypeSpecification worker = app.getWorkerTypeSpecifications() != null
? app.getWorkerTypeSpecifications().get(workerType) : null;
if (worker != null && worker.getImageConfiguration() != null
&& worker.getImageConfiguration().getImageUri() != null) {
return worker.getImageConfiguration().getImageUri();
}
if (pinned(app, "") != null) {
return byDigest(pinned(app, ""));
}
return app.getImageConfiguration() != null ? app.getImageConfiguration().getImageUri() : null;
}
@@ -11,6 +11,9 @@ import io.floci.aws.core.common.RequestContext;
import io.floci.aws.core.common.SmithyValidationErrors;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.ecr.EcrService;
import io.floci.aws.services.ecr.model.ImageDetail;
import io.floci.aws.services.ecr.model.ImageIdentifier;
import io.floci.aws.services.ecr.registry.EcrRegistryManager;
import io.floci.aws.services.emrserverless.model.Application;
import io.floci.aws.services.emrserverless.model.ApplicationSummary;
@@ -21,6 +24,7 @@ import io.floci.aws.services.emrserverless.model.UpdateApplicationRequest;
import io.floci.aws.services.emrserverless.model.WorkerTypeSpecification;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Clock;
import java.time.Instant;
@@ -31,6 +35,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Function;
@@ -62,6 +67,13 @@ public class EmrServerlessService {
private static final String RESERVED_PREFIX = "aws:";
private static final Pattern TAG_TEXT = Pattern.compile("[A-Za-z0-9 /_.:=+@-]*");
// ResourceArn's resource: an application, or one of its job runs or sessions.
private static final Logger LOG = Logger.getLogger(EmrServerlessService.class);
// Floci's ECR's answers for an image it does not hold, and, as ServerException, for image queries with no Docker
// daemon to serve its registry.
private static final Set<String> UNREADABLE_IMAGE_CODES =
Set.of("RepositoryNotFoundException", "ImageNotFoundException", "ServerException");
// A release label's major and minor versions.
private static final Pattern RELEASE_VERSION = Pattern.compile("emr-(\\d{1,6})\\.(\\d{1,6})(?:\\..*)?");
private static final Pattern RESOURCE =
Pattern.compile("/applications/([0-9a-zA-Z]+)(?:/(jobruns|sessions)/([0-9a-zA-Z]+))?");
private static final List<String> APPLICATION_STATES =
@@ -81,6 +93,10 @@ public class EmrServerlessService {
@Inject
RequestContext requestContext;
// Floci's ECR, which a custom image's digest is read from as an application starts; none in a test without it.
@Inject
EcrService ecrService;
@Inject
public EmrServerlessService(EmulatorConfig config, StorageFactory storageFactory,
RegionResolver regionResolver, Clock clock) {
@@ -251,6 +267,7 @@ public class EmrServerlessService {
if (request.getJobLevelCostAllocationConfiguration() != null) {
app.setJobLevelCostAllocationConfiguration(request.getJobLevelCostAllocationConfiguration());
}
unpinImagesResolvedPerWorkload(app);
app.setUpdatedAt(now());
storage.put(applicationId, app);
@@ -297,11 +314,161 @@ public class EmrServerlessService {
if ("TERMINATED".equals(state)) {
throw new AwsException("ValidationException", "Application is terminated.", 400);
}
pinImages(app);
app.setState("STARTED");
app.setUpdatedAt(now());
storage.put(applicationId, app);
}
/**
* Resolves, as the application starts, each custom image it resolves then: "Custom images are resolved to a digest
* at application start; that digest is used for all jobs until the application restarts" (EMR Serverless user
* guide, "Image digest resolution behavior"). Its image configuration gets the digest as its
* resolvedImageDigest, which "doesn't exist until an application has started", and its runs take that image
* until it starts again, an update meanwhile notwithstanding unless it turns the image to resolution per
* workload. An image outside ECR, in another account's repository, or one Floci's ECR does not hold, has no digest
* read, and is resolved for each run.
*/
private void pinImages(Application app) {
Map<String, ImageConfiguration> images = new LinkedHashMap<>();
images.put("", app.getImageConfiguration());
if (app.getWorkerTypeSpecifications() != null) {
app.getWorkerTypeSpecifications().forEach((workerType, specification) ->
images.put(workerType, specification != null ? specification.getImageConfiguration() : null));
}
// Every digest is read before any is written, so an answer that fails the start leaves the application as it
// was.
Map<String, String> digests = new LinkedHashMap<>();
images.forEach((key, image) -> {
String digest = startDigest(app, image);
if (digest != null) {
digests.put(key, digest);
}
});
Map<String, ImageConfiguration> pinned = new LinkedHashMap<>();
images.forEach((key, image) -> {
if (image == null) {
return;
}
// A digest from an earlier start is not this start's: one read now replaces it, and none read leaves
// none, as the runs then resolve the image themselves.
String digest = digests.get(key);
image.setResolvedImageDigest(digest);
if (digest != null) {
ImageConfiguration resolved = new ImageConfiguration();
resolved.setImageUri(image.getImageUri());
resolved.setResolvedImageDigest(digest);
pinned.put(key, resolved);
}
});
app.setPinnedImages(pinned.isEmpty() ? null : pinned);
}
// The digest an image configuration resolves as its application starts, or null where it has none to read then.
private String startDigest(Application app, ImageConfiguration image) {
if (image == null || image.getImageUri() == null || !applicationLevelDigests(app.getReleaseLabel(), image)) {
return null;
}
return ecrDigest(image.getImageUri(), accountOf(app));
}
/**
* Whether a custom image is resolved as its application starts: its image configuration's
* applicationLevelDigestResolution, else, as the user guide's table gives the default, true for "EMR 7.13 and
* earlier" and false for "EMR 7.14 and later". A release label not of the emr-x.y form is taken as current.
*/
static boolean applicationLevelDigests(String releaseLabel, ImageConfiguration image) {
if (image.getApplicationLevelDigestResolution() != null) {
return image.getApplicationLevelDigestResolution();
}
Matcher version = RELEASE_VERSION.matcher(releaseLabel == null ? "" : releaseLabel);
if (!version.matches()) {
return false;
}
int major = Integer.parseInt(version.group(1));
int minor = Integer.parseInt(version.group(2));
return major < 7 || major == 7 && minor <= 13;
}
/**
* Each run resolves its image again where an update turns a STARTED application's image to resolution per
* workload, or removes it: the pin of an image the application still resolves at its start stays until it starts
* again, "that digest is used for all jobs until the application restarts", and any other ends now.
*/
private static void unpinImagesResolvedPerWorkload(Application app) {
Map<String, ImageConfiguration> pinned = app.getPinnedImages();
if (pinned == null) {
return;
}
Map<String, ImageConfiguration> kept = new LinkedHashMap<>(pinned);
kept.keySet().removeIf(key -> {
ImageConfiguration current = imageConfigurationOf(app, key);
return current == null || current.getImageUri() == null
|| !applicationLevelDigests(app.getReleaseLabel(), current);
});
app.setPinnedImages(kept.isEmpty() ? null : kept);
}
// The application's image configuration for a pin's key: its own for "", else its worker type's.
private static ImageConfiguration imageConfigurationOf(Application app, String key) {
if (key.isEmpty()) {
return app.getImageConfiguration();
}
WorkerTypeSpecification specification = app.getWorkerTypeSpecifications() == null ? null
: app.getWorkerTypeSpecifications().get(key);
return specification == null ? null : specification.getImageConfiguration();
}
private static String accountOf(Application app) {
return AwsArnUtils.parse(app.getArn()).accountId();
}
/**
* The manifest digest of an image in one of the application's account's ECR repositories, the one its URI names
* where it names one; null for an image outside ECR, one in another account's repository, which Floci does not
* check the application may pull, or one Floci's ECR does not hold or cannot read without Docker. Each run then
* resolves the image itself. Any other answer from ECR fails the start.
*/
private String ecrDigest(String imageUri, String accountId) {
Optional<EcrRegistryManager.EcrImage> image = EcrRegistryManager.ecrImage(imageUri);
if (image.isEmpty() || !accountId.equals(image.get().registryId())) {
return null;
}
if (image.get().digest() != null) {
return image.get().digest();
}
if (ecrService == null) {
return null;
}
try {
List<ImageDetail> details = ecrService.describeImages(image.get().repository(),
List.of(new ImageIdentifier(image.get().tag(), null)), image.get().registryId(),
image.get().region()).imageDetails();
return details.isEmpty() ? null : details.getFirst().getImageDigest();
} catch (AwsException e) {
if (!UNREADABLE_IMAGE_CODES.contains(e.getErrorCode())) {
throw new AwsException("InternalServerException", "The custom image " + imageUri
+ " could not be resolved: " + e.getMessage(), 500);
}
LOG.infov("The custom image {0} has no digest in Floci's ECR ({1}), so each run resolves it: {2}",
imageUri, e.getErrorCode(), e.getMessage());
return null;
}
}
private static void clearResolvedDigests(Application app) {
if (app.getImageConfiguration() != null) {
app.getImageConfiguration().setResolvedImageDigest(null);
}
if (app.getWorkerTypeSpecifications() != null) {
for (WorkerTypeSpecification specification : app.getWorkerTypeSpecifications().values()) {
if (specification != null && specification.getImageConfiguration() != null) {
specification.getImageConfiguration().setResolvedImageDigest(null);
}
}
}
}
public synchronized void stopApplication(String applicationId) {
Application app = getApplication(applicationId);
String state = app.getState();
@@ -312,6 +479,9 @@ public class EmrServerlessService {
throw new AwsException("ValidationException", "Application is terminated.", 400);
}
app.setState("STOPPED");
// Its images are resolved again as it starts again.
app.setPinnedImages(null);
clearResolvedDigests(app);
app.setUpdatedAt(now());
storage.put(applicationId, app);
}
@@ -38,6 +38,9 @@ public class Application {
private NetworkConfiguration networkConfiguration;
private ImageConfiguration imageConfiguration;
private Map<String, WorkerTypeSpecification> workerTypeSpecifications;
// Each custom image resolved at the application's start, which its runs take until it starts again, by worker type,
// the application's own under ""; Floci's own, as the API has none.
private Map<String, ImageConfiguration> pinnedImages;
private MonitoringConfiguration monitoringConfiguration;
private List<RuntimeConfiguration> runtimeConfiguration;
private SchedulerConfiguration schedulerConfiguration;
@@ -103,4 +106,7 @@ public class Application {
return value != null && value.getEpochSecond() >= LEGACY_MILLIS_FLOOR
? Instant.ofEpochMilli(value.getEpochSecond()) : value;
}
public Map<String, ImageConfiguration> getPinnedImages() { return pinnedImages; }
public void setPinnedImages(Map<String, ImageConfiguration> pinnedImages) { this.pinnedImages = pinnedImages; }
}
@@ -8,7 +8,7 @@ public class GetApplicationResponse {
// The application is stored with the clientToken CreateApplication's retries are matched on, which
// GetApplication's Application does not have. It is left out here, not on Application, so storage keeps it.
@JsonIgnoreProperties("clientToken")
@JsonIgnoreProperties({"clientToken", "pinnedImages"})
private Application application;
public Application getApplication() {
@@ -8,7 +8,7 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
public class UpdateApplicationResponse {
// Without the clientToken storage keeps, as GetApplicationResponse leaves it out.
@JsonIgnoreProperties("clientToken")
@JsonIgnoreProperties({"clientToken", "pinnedImages"})
private Application application;
public Application getApplication() {
@@ -1083,4 +1083,17 @@ class EcrRegistryManagerTest {
}
assertEquals(Optional.empty(), EcrRegistryManager.imageRegion(null));
}
@Test
void anImageInAnEcrRepositoryNamesItsRepositoryAndTheTagOrDigestItAsksFor() {
String digest = "sha256:" + "d".repeat(64);
assertEquals(Optional.of(new EcrRegistryManager.EcrImage("123456789012", "us-east-1", "spark/custom", "7.5.0",
null)), EcrRegistryManager.ecrImage("123456789012.dkr.ecr.us-east-1.amazonaws.com/spark/custom:7.5.0"));
assertEquals(Optional.of(new EcrRegistryManager.EcrImage("000000000000", "us-west-2", "spark", null, digest)),
EcrRegistryManager.ecrImage("localhost:4566/000000000000/us-west-2/spark@" + digest));
// Neither a tag nor a digest asks for latest.
assertEquals(Optional.of(new EcrRegistryManager.EcrImage("000000000000", "eu-west-1", "spark", "latest",
null)), EcrRegistryManager.ecrImage("000000000000.dkr.ecr.eu-west-1.localhost:4566/spark"));
assertEquals(Optional.empty(), EcrRegistryManager.ecrImage("python:3.12"));
}
}
@@ -324,6 +324,27 @@ class EmrServerlessJobRunServiceTest {
assertNull(runner.jobs.get(2).customImage());
}
@Test
void aRunOfAnApplicationThatResolvedItsImageAsItStartedPullsThatImageByItsDigest() {
FakeRunner runner = new FakeRunner();
EmrServerlessJobRunService service = dockerService(runner);
String digest = "sha256:" + "c".repeat(64);
applications.ecrService = EmrServerlessServiceTest.ecrHolding("spark/custom", "7.5.0", digest);
CreateApplicationRequest custom = applicationRequest("resolved", "emr-7.5.0", "SPARK");
custom.setImageConfiguration(EmrServerlessServiceTest.image(
"000000000000.dkr.ecr.us-east-1.amazonaws.com/spark/custom:7.5.0"));
String customId = applications.createApplication(custom).getApplicationId();
// The run starts the application, which resolves its image as it starts.
String jobRunId = service.startJobRun(customId, request(null, null)).getJobRunId();
runNext();
assertEquals("000000000000.dkr.ecr.us-east-1.amazonaws.com/spark/custom@" + digest,
runner.jobs.get(0).customImage());
assertEquals(digest, service.getJobRun(customId, jobRunId, null).getImageConfiguration()
.getResolvedImageDigest());
}
@Test
void aRunReportsTheImageConfigurationsItAppliesEachWithTheDigestOfTheImageItsRunnerResolvedForIt() {
FakeRunner runner = new FakeRunner();
@@ -5,6 +5,8 @@ import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.PersistentStorage;
import io.floci.aws.services.ecr.EcrService;
import io.floci.aws.services.ecr.model.ImageDetail;
import io.floci.aws.services.emrserverless.model.Application;
import io.floci.aws.services.emrserverless.model.CreateApplicationRequest;
import io.floci.aws.services.emrserverless.model.ImageConfiguration;
@@ -32,7 +34,13 @@ import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class EmrServerlessServiceTest {
@@ -41,7 +49,12 @@ class EmrServerlessServiceTest {
private static final String ACCOUNT_ID = "000000000000";
private static final TypeReference<Map<String, Application>> APPLICATIONS = new TypeReference<>() {};
private static final String CUSTOM_IMAGE = "123456789012.dkr.ecr.us-east-1.amazonaws.com/spark/custom:7.5.0";
private static final String DIGEST = "sha256:" + "a".repeat(64);
private static final String NEWER_DIGEST = "sha256:" + "b".repeat(64);
private static final String OTHER_IMAGE = "123456789012.dkr.ecr.us-east-1.amazonaws.com/spark/custom:7.5.1";
// Images in the application's own account's ECR, which an application resolves as it starts.
private static final String OWN_IMAGE = "000000000000.dkr.ecr.us-east-1.amazonaws.com/spark/custom:7.5.0";
private static final String OWN_NEWER_IMAGE = "000000000000.dkr.ecr.us-east-1.amazonaws.com/spark/newer:7.5.0";
// The settings a STARTED application's update may name, besides an idempotency token and the path's application.
private static final Set<String> STARTED_UPDATE_MEMBERS = Set.of("setApplicationId", "setClientToken",
"setMaximumCapacity", "setImageConfiguration", "setWorkerTypeSpecifications");
@@ -108,6 +121,176 @@ class EmrServerlessServiceTest {
assertEquals("create-00abc", reloaded.getClientToken());
}
@Test
void anApplicationOf713OrEarlierResolvesItsImageAsItStartsAndKeepsItUntilItStartsAgain() {
EmrServerlessService service = service();
service.ecrService = ecrHolding("spark/custom", "7.5.0", DIGEST, "spark/newer", "7.5.0", NEWER_DIGEST);
CreateApplicationRequest create = createRequest();
create.setImageConfiguration(image(OWN_IMAGE));
String applicationId = service.createApplication(create).getApplicationId();
// "The image digest doesn't exist until an application has started."
assertNull(service.getApplication(applicationId).getImageConfiguration().getResolvedImageDigest());
service.startApplication(applicationId);
// "Custom images are resolved to a digest at application start" for EMR 7.13 and earlier.
Application started = service.getApplication(applicationId);
assertEquals(DIGEST, started.getImageConfiguration().getResolvedImageDigest());
assertEquals(DIGEST, started.getPinnedImages().get("").getResolvedImageDigest());
// "that digest is used for all jobs until the application restarts", an update notwithstanding.
UpdateApplicationRequest update = new UpdateApplicationRequest();
update.setImageConfiguration(image(OWN_NEWER_IMAGE));
service.updateApplication(applicationId, update);
assertEquals(OWN_IMAGE, service.getApplication(applicationId).getPinnedImages().get("").getImageUri());
service.stopApplication(applicationId);
service.startApplication(applicationId);
assertEquals(NEWER_DIGEST, service.getApplication(applicationId).getPinnedImages().get("")
.getResolvedImageDigest());
}
@Test
void anApplicationOf714OrLaterResolvesItsImageForEachRunUnlessItAsksOtherwise() {
EmrServerlessService service = service();
service.ecrService = ecrHolding("spark/custom", "7.5.0", DIGEST, "spark/newer", "7.5.0", NEWER_DIGEST);
CreateApplicationRequest later = createRequest();
later.setReleaseLabel("emr-7.14.0");
later.setImageConfiguration(image(OWN_IMAGE));
String laterId = service.createApplication(later).getApplicationId();
CreateApplicationRequest asked = createRequest();
asked.setReleaseLabel("emr-7.14.0");
asked.setImageConfiguration(image(OWN_IMAGE));
asked.getImageConfiguration().setApplicationLevelDigestResolution(true);
String askedId = service.createApplication(asked).getApplicationId();
CreateApplicationRequest declined = createRequest();
declined.setImageConfiguration(image(OWN_IMAGE));
declined.getImageConfiguration().setApplicationLevelDigestResolution(false);
String declinedId = service.createApplication(declined).getApplicationId();
service.startApplication(laterId);
service.startApplication(askedId);
service.startApplication(declinedId);
// "EMR 7.14 and later: applicationLevelDigestResolution = false".
assertNull(service.getApplication(laterId).getPinnedImages());
assertEquals(DIGEST, service.getApplication(askedId).getImageConfiguration().getResolvedImageDigest());
assertNull(service.getApplication(declinedId).getPinnedImages());
}
@Test
void anImageInAnotherAccountsRepositoryIsResolvedForEachRun() {
EmrServerlessService service = service();
EcrService ecr = ecrHolding("spark/custom", "7.5.0", DIGEST);
service.ecrService = ecr;
CreateApplicationRequest create = createRequest();
create.setImageConfiguration(image(CUSTOM_IMAGE));
String applicationId = service.createApplication(create).getApplicationId();
service.startApplication(applicationId);
// Floci does not check the application may pull another account's image, so it reads nothing of it.
assertNull(service.getApplication(applicationId).getPinnedImages());
assertNull(service.getApplication(applicationId).getImageConfiguration().getResolvedImageDigest());
verifyNoInteractions(ecr);
}
@Test
void anImageEcrDoesNotHoldIsResolvedForEachRunAndAnyOtherAnswerFailsTheStart() {
EmrServerlessService service = service();
for (String code : List.of("RepositoryNotFoundException", "ImageNotFoundException", "ServerException")) {
service.ecrService = ecrAnswering(new AwsException(code, "not held", 400));
CreateApplicationRequest create = createRequest();
create.setImageConfiguration(image(OWN_IMAGE));
String applicationId = service.createApplication(create).getApplicationId();
service.startApplication(applicationId);
assertEquals("STARTED", service.getApplication(applicationId).getState(), code);
assertNull(service.getApplication(applicationId).getPinnedImages(), code);
}
service.ecrService = ecrAnswering(new AwsException("InvalidParameterException", "Invalid tag.", 400));
CreateApplicationRequest create = createRequest();
create.setImageConfiguration(image(OWN_IMAGE));
String applicationId = service.createApplication(create).getApplicationId();
AwsException error = assertThrows(AwsException.class, () -> service.startApplication(applicationId));
assertEquals("InternalServerException", error.getErrorCode());
assertTrue(error.getMessage().contains("Invalid tag."), error.getMessage());
// The failed start leaves the application as it was.
assertEquals("CREATED", service.getApplication(applicationId).getState());
assertNull(service.getApplication(applicationId).getImageConfiguration().getResolvedImageDigest());
}
@Test
void aStoppedApplicationReportsNoDigestAndAStartThatResolvesNoneLeavesNone() {
EmrServerlessService service = service();
service.ecrService = ecrHolding("spark/custom", "7.5.0", DIGEST);
CreateApplicationRequest create = createRequest();
create.setImageConfiguration(image(OWN_IMAGE));
create.setWorkerTypeSpecifications(Map.of("Driver", workerType(OWN_IMAGE)));
String applicationId = service.createApplication(create).getApplicationId();
service.startApplication(applicationId);
assertEquals(DIGEST, service.getApplication(applicationId).getWorkerTypeSpecifications().get("Driver")
.getImageConfiguration().getResolvedImageDigest());
service.stopApplication(applicationId);
Application stopped = service.getApplication(applicationId);
assertNull(stopped.getImageConfiguration().getResolvedImageDigest());
assertNull(stopped.getWorkerTypeSpecifications().get("Driver").getImageConfiguration()
.getResolvedImageDigest());
UpdateApplicationRequest later = new UpdateApplicationRequest();
later.setReleaseLabel("emr-7.14.0");
service.updateApplication(applicationId, later);
service.startApplication(applicationId);
Application restarted = service.getApplication(applicationId);
assertNull(restarted.getPinnedImages());
assertNull(restarted.getImageConfiguration().getResolvedImageDigest());
}
@Test
void anUpdateTurningARunningApplicationsImageToResolutionPerWorkloadEndsItsPin() {
EmrServerlessService service = service();
service.ecrService = ecrHolding("spark/custom", "7.5.0", DIGEST, "spark/newer", "7.5.0", NEWER_DIGEST);
CreateApplicationRequest create = createRequest();
create.setImageConfiguration(image(OWN_IMAGE));
create.setWorkerTypeSpecifications(Map.of("Driver", workerType(OWN_IMAGE)));
String applicationId = service.createApplication(create).getApplicationId();
service.startApplication(applicationId);
ImageConfiguration perWorkload = image(OWN_NEWER_IMAGE);
perWorkload.setApplicationLevelDigestResolution(false);
UpdateApplicationRequest update = new UpdateApplicationRequest();
update.setImageConfiguration(perWorkload);
service.updateApplication(applicationId, update);
// New runs take the new image, resolved for each; the driver's image is still resolved at the start.
Map<String, ImageConfiguration> pinned = service.getApplication(applicationId).getPinnedImages();
assertEquals(Set.of("Driver"), pinned.keySet());
assertEquals(DIGEST, pinned.get("Driver").getResolvedImageDigest());
}
// An ECR answering every image query with error.
private static EcrService ecrAnswering(AwsException error) {
EcrService ecr = mock(EcrService.class);
when(ecr.describeImages(anyString(), anyList(), anyString(), anyString())).thenThrow(error);
return ecr;
}
// An ECR holding each repository's tag, given as repository, tag and digest in turn.
static EcrService ecrHolding(String... images) {
EcrService ecr = mock(EcrService.class);
for (int i = 0; i < images.length; i += 3) {
ImageDetail detail = new ImageDetail();
detail.setImageDigest(images[i + 2]);
String tag = images[i + 1];
when(ecr.describeImages(eq(images[i]),
argThat(ids -> ids.size() == 1 && tag.equals(ids.get(0).getImageTag())), eq(ACCOUNT_ID),
eq(REGION))).thenReturn(new EcrService.DescribeImagesResult(List.of(detail), List.of()));
}
return ecr;
}
@Test
void anUpdateLeavingTheImageUriOutRemovesTheImageConfiguration() {
EmrServerlessService service = service();