feat(emr-serverless): run a job run in its application's custom image (#6975)

In the docker runner mode an application's imageConfiguration, and a
worker type's, was stored and returned, but every run started from the
release's public image. So a job whose libraries are baked into its own
image, the user guide's "Customizing an EMR Serverless image", could not
run. Now a run starts from the application's custom image:

- the Driver worker type's imageConfiguration, else the application's,
  which "EMR Serverless applies ... to all worker types". Local mode
  runs the executors in the driver's container, so an Executor image is
  not used;
- an <account>.dkr.ecr.<region>.amazonaws.com URI leads to Floci's ECR,
  as a Lambda function's or an ECS task's image does, and the
  repositoryUri Floci's ECR hands out works too;
- the image is pulled for every run, as an ECS task's is, so a tag
  pushed again is what the next run gets ("New workloads submitted after
  the update automatically will use the new image"), and the driver
  starts from the image id that pull resolved. When the pull fails, the
  image the Docker daemon has runs; without one the run is FAILED.

SparkJobRunner.Job carries the custom image beside the template, which
classic EMR's steps leave null.

The image configurations, the application's and each worker type's,
are checked as the user guide and the model describe them, in Floci's
own wording as no source gives AWS's:

- CreateApplication refuses one without imageUri, "This field is
  required when you create a new application";
- CreateApplication and UpdateApplication refuse an image whose ECR
  repository, AWS-shaped or a repositoryUri from Floci's ECR, is in
  another Region: "The Amazon ECR repository must be in the same AWS
  Region that you use to launch EMR Serverless applications";
- UpdateApplication with one that leaves imageUri out removes it: "If
  you leave this field blank in an update, Amazon EMR will remove the
  image configuration."

EcrRegistryManager.imageRegion reads the Region from either URI form.
Floci does not check imageUri against the model's pattern, which would
refuse the repository URIs its own ECR hands out, nor the image's
release or size, and reports no resolvedImageDigest; the service doc
lists these.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-30 07:23:11 -05:00
1 parent 6e9ac904c8
commit 931b2d26a7
15 files changed
+387 -34

No files matched your search

@@ -1107,7 +1107,8 @@ public interface EmulatorConfig {
/**
* {@code immediate} follows the job run states without running anything; {@code docker} runs
* each Spark job run's {@code spark-submit} in a container of the release's EMR Serverless image.
* each Spark job run's {@code spark-submit} in a container of the application's custom image, or
* else of the release's EMR Serverless image.
*/
@WithDefault("immediate")
String runnerMode();
@@ -1115,9 +1116,10 @@ public interface EmulatorConfig {
Optional<String> dockerNetwork();
/**
* The image a {@code docker} job run uses, with {@code %s} standing for the application's
* release label, for example "registry.internal/emr-serverless/spark/%s:20250425". If omitted,
* Floci uses the release's public image on Amazon ECR Public.
* The image a {@code docker} job run uses when its application names no custom image, with
* {@code %s} standing for the application's release label, for example
* "registry.internal/emr-serverless/spark/%s:20250425". If omitted, Floci uses the release's public
* image on Amazon ECR Public.
*/
Optional<String> imageTemplate();
@@ -473,8 +473,8 @@ public class EcrRegistryDataPlane {
storageRepositoryName, repository, backendUri,
tag(path)));
}
// A loopback host is the address Floci itself hands the Docker daemon for the ECS and
// Lambda images it pulls, path style in either URI style (see rewriteImageUri).
// A loopback host is the address Floci itself hands the Docker daemon for the ECS, Lambda
// and EMR Serverless images it pulls, path style in either URI style (see rewriteImageUri).
if (!"path".equalsIgnoreCase(uriStyle) && !isLoopbackHost(host)) {
return Optional.empty();
}
@@ -68,6 +68,14 @@ public class EcrRegistryManager {
private static final Pattern AWS_ECR_URI = Pattern.compile(
"^([0-9]{12})\\.dkr\\.ecr\\.([a-z0-9-]+)\\." + AwsPartitions.dnsSuffixRegex() + "/(.+)$");
/**
* The Region of an image in an ECR repository: in {@code <account>.dkr.ecr.<region>.<host>/<repo>}, AWS's
* form and Floci's {@code repositoryUri} in the default URI style, or in
* {@code localhost:<port>/<account>/<region>/<repo>}, Floci's in the path style.
*/
private static final Pattern ECR_IMAGE_REGION = Pattern.compile("^(?:[0-9]{12}\\.dkr\\.ecr\\.([a-z0-9-]+)\\.[^/]+"
+ "|localhost(?:\\.floci\\.io)?:[0-9]+/[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.
@@ -153,6 +161,18 @@ public class EcrRegistryManager {
return rewritten;
}
/**
* 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.
*/
public static Optional<String> imageRegion(String image) {
Matcher m = image != null ? ECR_IMAGE_REGION.matcher(image) : null;
if (m == null || !m.matches()) {
return Optional.empty();
}
return Optional.of(m.group(1) != null ? m.group(1) : m.group(2));
}
private boolean isPresentOnDaemon(String image) {
try {
lifecycleManager.getDockerClient().inspectImageCmd(image).exec();
@@ -1317,7 +1317,7 @@ public class EmrService implements Resettable {
List<String> command = application == null ? EmrSparkSteps.command(step) : null;
SparkJobRunner.Job job = application == null && command == null ? null
: new SparkJobRunner.Job(SERVICE, step.getId(), accountId, region, cluster.getReleaseLabel(),
cluster.getBootstrapImage() != null ? cluster.getBootstrapImage() : imageTemplate,
cluster.getBootstrapImage() != null ? cluster.getBootstrapImage() : imageTemplate, null,
dockerNetwork, executionRole(cluster, step, accountId),
EmrSparkSteps.sparkDefaults(cluster.getConfigurations(), SNAPSHOT_MAPPER),
application != null ? application : List.of(), command, Duration.ZERO,
@@ -25,6 +25,7 @@ import io.github.hectorvent.floci.services.emrserverless.model.JobRunRecord;
import io.github.hectorvent.floci.services.emrserverless.model.JobRunSummary;
import io.github.hectorvent.floci.services.emrserverless.model.RuntimeConfiguration;
import io.github.hectorvent.floci.services.emrserverless.model.StartJobRunRequest;
import io.github.hectorvent.floci.services.emrserverless.model.WorkerTypeSpecification;
import io.github.hectorvent.floci.services.iam.IamService;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
@@ -89,6 +90,8 @@ public class EmrServerlessJobRunService implements Resettable {
// "If you don't specify the optional values, then CloudWatch publishes the logs to a default log group".
private static final String DEFAULT_LOG_GROUP = "/aws/emr-serverless";
private static final String SPARK_DRIVER = "SPARK_DRIVER";
// The worker type a Spark application's driver runs as.
private static final String DRIVER_WORKER_TYPE = "Driver";
// No source gives AWS's wording for these; they are Floci's.
static final String HIVE_NOT_RUN = "Floci runs Spark job runs only, and this is a Hive job run.";
static final String INTERRUPTED = "Floci stopped while the job run was in progress.";
@@ -478,9 +481,9 @@ public class EmrServerlessJobRunService implements Resettable {
Duration timeout = MODE_STREAMING.equals(run.getMode()) || minutes == null || minutes == 0
? Duration.ZERO : Duration.ofMinutes(minutes);
SparkJobRunner.Job job = new SparkJobRunner.Job(SERVICE, run.getJobRunId(), arn.accountId(), arn.region(),
run.getReleaseLabel(), imageTemplate, dockerNetwork, run.getExecutionRole(), sparkDefaults(app, run),
application(run.getJobDriver().getSparkSubmit()), null, timeout, driverLogFolder(app, run),
driverCloudWatchLogs(app, run));
run.getReleaseLabel(), imageTemplate, customImage(app), dockerNetwork, run.getExecutionRole(),
sparkDefaults(app, run), application(run.getJobDriver().getSparkSubmit()), null, timeout,
driverLogFolder(app, run), driverCloudWatchLogs(app, run));
executing.add(run.getJobRunId());
long launchedIn = generation;
runExecutor.execute(() -> execute(job, launchedIn));
@@ -498,6 +501,21 @@ public class EmrServerlessJobRunService implements Resettable {
RequestScopes.runAs(job.accountId(), job.region(), () -> ended(job.runId(), ended, launchedIn));
}
/**
* The custom image a run's driver starts from, or null for the release's: the {@code Driver} worker type's,
* else the application's, which "EMR Serverless applies ... to all worker types". Local mode runs the
* executors in the driver's container, so an {@code Executor} image is not used.
*/
static String customImage(Application app) {
WorkerTypeSpecification driver = app.getWorkerTypeSpecifications() != null
? app.getWorkerTypeSpecifications().get(DRIVER_WORKER_TYPE) : null;
if (driver != null && driver.getImageConfiguration() != null
&& driver.getImageConfiguration().getImageUri() != null) {
return driver.getImageConfiguration().getImageUri();
}
return app.getImageConfiguration() != null ? app.getImageConfiguration().getImageUri() : null;
}
/**
* What follows Floci's own settings on a run's {@code spark-submit} command line: its
* {@code sparkSubmitParameters}, split as a shell would split them, then its entry point and the
@@ -11,11 +11,14 @@ import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
import io.github.hectorvent.floci.services.emrserverless.model.Application;
import io.github.hectorvent.floci.services.emrserverless.model.ApplicationSummary;
import io.github.hectorvent.floci.services.emrserverless.model.CreateApplicationRequest;
import io.github.hectorvent.floci.services.emrserverless.model.ImageConfiguration;
import io.github.hectorvent.floci.services.emrserverless.model.ListApplicationsRequest;
import io.github.hectorvent.floci.services.emrserverless.model.UpdateApplicationRequest;
import io.github.hectorvent.floci.services.emrserverless.model.WorkerTypeSpecification;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -84,6 +87,7 @@ public class EmrServerlessService {
if (request.getClientToken() == null || request.getClientToken().isBlank()) {
throw new AwsException("ValidationException", "clientToken is required", 400);
}
validateImages(request.getImageConfiguration(), request.getWorkerTypeSpecifications(), true);
String region = regionResolver.getRegion();
if (request.getClientToken() != null) {
@@ -170,6 +174,7 @@ public class EmrServerlessService {
}
public synchronized Application updateApplication(String applicationId, UpdateApplicationRequest request) {
validateImages(request.getImageConfiguration(), request.getWorkerTypeSpecifications(), false);
Application app = getApplication(applicationId);
String state = app.getState();
@@ -199,9 +204,14 @@ public class EmrServerlessService {
app.setArchitecture(request.getArchitecture());
}
if (request.getImageConfiguration() != null) {
app.setImageConfiguration(request.getImageConfiguration());
app.setImageConfiguration(imageOrNone(request.getImageConfiguration()));
}
if (request.getWorkerTypeSpecifications() != null) {
for (WorkerTypeSpecification specification : request.getWorkerTypeSpecifications().values()) {
if (specification != null) {
specification.setImageConfiguration(imageOrNone(specification.getImageConfiguration()));
}
}
app.setWorkerTypeSpecifications(request.getWorkerTypeSpecifications());
}
if (request.getMonitoringConfiguration() != null) {
@@ -427,6 +437,48 @@ public class EmrServerlessService {
return violations;
}
/**
* Refuses an image configuration, the application's or a worker type's, that a new application leaves
* without an {@code imageUri} ("This field is required when you create a new application"), or whose image
* is in an ECR repository of another Region ("The Amazon ECR repository must be in the same AWS Region that
* you use to launch EMR Serverless applications"). No source words either refusal, so both are Floci's. An
* image outside ECR has no Region to compare.
*/
private void validateImages(ImageConfiguration image, Map<String, WorkerTypeSpecification> workerTypes,
boolean creating) {
validateImage("imageConfiguration", image, creating);
if (workerTypes != null) {
workerTypes.forEach((workerType, specification) -> validateImage(
"workerTypeSpecifications." + workerType + ".imageConfiguration",
specification != null ? specification.getImageConfiguration() : null, creating));
}
}
private void validateImage(String member, ImageConfiguration image, boolean creating) {
if (image == null) {
return;
}
String uri = image.getImageUri();
if (uri == null) {
if (creating) {
throw new AwsException("ValidationException", member + ".imageUri is required", 400);
}
return;
}
String region = regionResolver.getRegion();
Optional<String> imageRegion = EcrRegistryManager.imageRegion(uri);
if (imageRegion.isPresent() && !imageRegion.get().equals(region)) {
throw new AwsException("ValidationException", "Image " + uri + " is in an Amazon ECR repository in "
+ imageRegion.get() + "; it must be in the application's Region, " + region + ".", 400);
}
}
// An update's image configuration, or none when it leaves imageUri out: "If you leave this field blank in an
// update, Amazon EMR will remove the image configuration."
private static ImageConfiguration imageOrNone(ImageConfiguration image) {
return image != null && image.getImageUri() != null ? image : null;
}
/** At most 50 tags, each key and value within TagKey and TagValue and free of the reserved prefix. */
static void validateTags(Map<String, String> tags) {
if (tags.size() > MAX_TAGS) {
@@ -6,6 +6,7 @@ import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.EmulatorConfig.EcsServiceConfig.ImagePullBehavior;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.S3Uri;
@@ -16,6 +17,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
import io.github.hectorvent.floci.services.iam.model.SessionCreds;
import io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentials;
import io.github.hectorvent.floci.services.s3.S3Service;
@@ -94,6 +96,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
private final LaunchedContainerAwsEnv awsEnv;
private final LambdaExecutionRoleCredentials roleCredentials;
private final S3Service s3Service;
private final EcrRegistryManager ecrRegistryManager;
private final EmulatorConfig config;
private final Clock clock;
private final Duration pollInterval;
@@ -102,21 +105,23 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
public EmrServerlessSparkRunner(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
ContainerLogStreamer logStreamer, LaunchedContainerAwsEnv awsEnv,
LambdaExecutionRoleCredentials roleCredentials, S3Service s3Service,
EmulatorConfig config, Clock clock) {
this(containerBuilder, lifecycleManager, logStreamer, awsEnv, roleCredentials, s3Service, config, clock,
POLL_INTERVAL);
EcrRegistryManager ecrRegistryManager, EmulatorConfig config, Clock clock) {
this(containerBuilder, lifecycleManager, logStreamer, awsEnv, roleCredentials, s3Service, ecrRegistryManager,
config, clock, POLL_INTERVAL);
}
EmrServerlessSparkRunner(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
ContainerLogStreamer logStreamer, LaunchedContainerAwsEnv awsEnv,
LambdaExecutionRoleCredentials roleCredentials, S3Service s3Service,
EmulatorConfig config, Clock clock, Duration pollInterval) {
EcrRegistryManager ecrRegistryManager, EmulatorConfig config, Clock clock,
Duration pollInterval) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.logStreamer = logStreamer;
this.awsEnv = awsEnv;
this.roleCredentials = roleCredentials;
this.s3Service = s3Service;
this.ecrRegistryManager = ecrRegistryManager;
this.config = config;
this.clock = clock;
this.pollInterval = pollInterval;
@@ -138,8 +143,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
// The deployment that started the driver, which removeLeftoverDrivers() goes by.
labels.put(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config));
String endpoint = awsEnv.flociEndpoint();
ContainerBuilder.Builder container = containerBuilder.newContainer(
image(job.imageTemplate(), job.releaseLabel()))
ContainerBuilder.Builder container = containerBuilder.newContainer(launchImage(job))
.withName(ContainerStorageHelper.dockerName(config, job.service() + "-" + job.runId()))
.withEnv(awsEnv.sdkBaselineEnv(job.region(), Optional.empty(), credentials, job.accountId()));
if (job.command() == null) {
@@ -304,6 +308,21 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
return template.formatted(releaseLabel);
}
/**
* The image a run's driver starts from: the release's, or the template's, or the application's custom
* image. A custom image's ECR URI leads to Floci's own registry, as a Lambda function's or an ECS task's
* does, and the image is pulled for every run, as an ECS task's is, so a tag pushed again is what the next
* run gets ("New workloads submitted after the update automatically will use the new image"). The driver
* starts from the image id that pull resolved, which a later push cannot move.
*/
private String launchImage(Job job) {
if (job.customImage() == null) {
return image(job.imageTemplate(), job.releaseLabel());
}
String image = containerBuilder.resolveImage(ecrRegistryManager.rewriteImageUri(job.customImage()));
return lifecycleManager.resolveImageForLaunch(image, ImagePullBehavior.DEFAULT, null).imageId();
}
/**
* {@code spark-submit}'s arguments: local mode, S3A on Floci's S3 for {@code s3://} and {@code s3a://}
* paths, then the run's {@code spark-defaults} and its own options, which win over what comes before
@@ -50,8 +50,10 @@ public interface SparkJobRunner {
/**
* What a run needs: the service it belongs to and its id there, which name its container; its account
* and Region; its release, and the image template and Docker network to run it in (a null template is
* the release's public EMR Serverless image, a null network the global default); the execution role
* whose credentials it gets; the {@code spark-defaults} properties that apply to it;
* the release's public EMR Serverless image, a null network the global default); {@code customImage}, when
* not null, the image the run's application names, which it runs in place of the template's, resolved
* again for each run; the execution role whose credentials it gets; the {@code spark-defaults} properties
* that apply to it;
* {@code application}, what follows Floci's own settings on {@code spark-submit}'s command line (the
* run's options, then its application and that application's arguments); or {@code command}, when not
* null, what the container runs in place of {@code spark-submit}, where a {@code spark-submit} it starts
@@ -62,9 +64,9 @@ public interface SparkJobRunner {
* its driver's output goes while it runs (null for nowhere but Floci's log).
*/
record Job(String service, String runId, String accountId, String region, String releaseLabel,
String imageTemplate, String dockerNetwork, String executionRole, Map<String, String> sparkDefaults,
List<String> application, List<String> command, Duration timeout, String logFolder,
CloudWatchLogs cloudWatchLogs) {
String imageTemplate, String customImage, String dockerNetwork, String executionRole,
Map<String, String> sparkDefaults, List<String> application, List<String> command, Duration timeout,
String logFolder, CloudWatchLogs cloudWatchLogs) {
}
/**