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

@@ -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() {