mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
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:
1 parent
6e9ac904c8
commit
931b2d26a7
15 files changed
+387
-34
No files matched your search
@@ -92,7 +92,7 @@ the optional `filter` fields.
|
||||
- **Cross-account / cross-region isolation.** Internally the registry namespaces repositories as `<account>/<region>/<repoName>`, so the same repository name in different accounts or regions cannot collide.
|
||||
- **Reconcile on first start.** When the registry container starts, Floci queries `GET /v2/_catalog` and recreates `Repository` metadata entries for any namespaces present in the registry but missing from local storage. This means image bytes are never orphaned across restarts.
|
||||
- **Upgrade from direct registry access.** Floci recreates an older backing container with the same volume and a loopback-only port binding. Repositories written through the former direct endpoint retain their physical paths and map to the default account and Region; their returned URI moves to port `4566`.
|
||||
- **Lambda and ECS integration.** Image-backed Lambda functions (`PackageType=Image`) and ECS task containers reference the same loopback `repositoryUri`. Floci rewrites real-AWS-shaped `<account>.dkr.ecr.<region>.amazonaws.com/...` URIs to the loopback registry at pull time, path style on `localhost` (`localhost:<flociPort>/<account>/<region>/<repo>`) in either URI style and with or without TLS, the one address every Docker daemon pulls from over plain HTTP, so CDK's `DockerImageFunction` (which generates AWS-shaped URIs in CloudFormation templates) works without any user-side rewriting.
|
||||
- **Lambda, ECS and EMR Serverless integration.** Image-backed Lambda functions (`PackageType=Image`), ECS task containers and the custom images of EMR Serverless applications (in its `docker` runner mode) reference the same loopback `repositoryUri`. Floci rewrites real-AWS-shaped `<account>.dkr.ecr.<region>.amazonaws.com/...` URIs to the loopback registry at pull time, path style on `localhost` (`localhost:<flociPort>/<account>/<region>/<repo>`) in either URI style and with or without TLS, the one address every Docker daemon pulls from over plain HTTP, so CDK's `DockerImageFunction` (which generates AWS-shaped URIs in CloudFormation templates) works without any user-side rewriting.
|
||||
- **Locally built images win.** An AWS-shaped URI that names an image already present on the Docker daemon is used as-is instead of being rewritten (`FLOCI_SERVICES_ECR_PREFER_LOCAL_IMAGES`, default `true`). Build the image under the exact URI your function or task definition declares (`docker build -t <account>.dkr.ecr.<region>.amazonaws.com/<repo>:<tag> .`) and it runs without a push to the emulated registry, and without the registry container being started. The check uses the reference Floci would launch, so with `FLOCI_DOCKER_IMAGE_REGISTRY_BASE` set the image must be present as `<base>/<account>.dkr.ecr.<region>.amazonaws.com/<repo>:<tag>`.
|
||||
|
||||
## Pull-time update exclusions
|
||||
@@ -143,7 +143,7 @@ services:
|
||||
|
||||
`docker login 000000000000.dkr.ecr.us-east-1.localhost:4566` works once Floci starts the registry sidecar.
|
||||
|
||||
When Floci runs in a container that publishes its port on another host port (for example `docker run -p 54321:4566`), the `repositoryUri`, the `GetAuthorizationToken` `proxyEndpoint` and the rewritten Lambda and ECS image URIs all name that host port (`000000000000.dkr.ecr.us-east-1.localhost:54321`, and `localhost:54321/...` for a rewrite), because the Docker daemon performs login, push and pull through it. Floci reads the published port from its own container through the mounted Docker socket, and uses `floci.port` (`4566`) when it does not run in a container or the port is not published.
|
||||
When Floci runs in a container that publishes its port on another host port (for example `docker run -p 54321:4566`), the `repositoryUri`, the `GetAuthorizationToken` `proxyEndpoint` and the rewritten Lambda, ECS and EMR Serverless image URIs all name that host port (`000000000000.dkr.ecr.us-east-1.localhost:54321`, and `localhost:54321/...` for a rewrite), because the Docker daemon performs login, push and pull through it. Floci reads the published port from its own container through the mounted Docker socket, and uses `floci.port` (`4566`) when it does not run in a container or the port is not published.
|
||||
|
||||
## Examples
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ EMR Serverless is an AWS service that provides serverless data analytics environ
|
||||
| `floci.services.emrserverless.job-run-duration-seconds` | How long a `BATCH` job run stays `RUNNING` before it succeeds; `0` makes it `SUCCESS` as soon as it starts | `0` |
|
||||
| `floci.services.emrserverless.runner-mode` | `immediate` moves job runs through their states without running anything; `docker` runs each Spark job run in a container (see [Running Spark job runs](#running-spark-job-runs)) | `immediate` |
|
||||
| `floci.services.emrserverless.docker-network` | Docker network for job run containers | the global default |
|
||||
| `floci.services.emrserverless.image-template` | Image for a `docker` job run, `%s` standing for the release label | `public.ecr.aws/emr-serverless/spark/%s:latest`, or `spark4/` in place of `spark/` for an `emr-spark-*` release |
|
||||
| `floci.services.emrserverless.image-template` | Image for a `docker` job run whose application names no custom image, `%s` standing for the release label | `public.ecr.aws/emr-serverless/spark/%s:latest`, or `spark4/` in place of `spark/` for an `emr-spark-*` release |
|
||||
| `floci.services.emrserverless.reconcile-containers-on-startup` | Remove the drivers a previous run of this Floci left on the Docker daemon before the first job run starts; turn it off when two Floci instances share a daemon with the same port and no resource namespace | `true` |
|
||||
|
||||
## Endpoints
|
||||
@@ -109,9 +109,10 @@ included; see [Step Functions: Amazon EMR Serverless tasks](step-functions.md#am
|
||||
## Running Spark job runs
|
||||
|
||||
With `runner-mode` set to `docker` (`FLOCI_SERVICES_EMRSERVERLESS_RUNNER_MODE=docker`), a Spark job
|
||||
run executes. Floci starts one container per run from the release's image, the base image AWS
|
||||
publishes for customizing EMR Serverless images (`public.ecr.aws/emr-serverless/spark/<release>`, and
|
||||
`spark4/<release>` for the AWS runtime for Apache Spark releases, `emr-spark-8.0.0` on), and runs
|
||||
run executes. Floci starts one container per run from the application's custom image, if it names one
|
||||
(see **Image** below), or else from the release's image, the base image AWS publishes for customizing
|
||||
EMR Serverless images (`public.ecr.aws/emr-serverless/spark/<release>`, and `spark4/<release>` for the
|
||||
AWS runtime for Apache Spark releases, `emr-spark-8.0.0` on), and runs
|
||||
`spark-submit` in local mode in it: the container holds the driver and its executors.
|
||||
|
||||
* **States**: a run is `SCHEDULED` while its image is pulled and its container starts (the first run
|
||||
@@ -159,13 +160,26 @@ publishes for customizing EMR Serverless images (`public.ecr.aws/emr-serverless/
|
||||
group is `logGroupName`, `/aws/emr-serverless` by default, and `<prefix>` the `logStreamNamePrefix`, if
|
||||
any; both are created as needed, in the run's account and Region. A `logTypes` sends only the driver's
|
||||
types it names, and none of the driver's output when it names only `SPARK_EXECUTOR`.
|
||||
* **Image**: `image-template` names another image, such as a mirror or a dated tag of the release's
|
||||
image: `registry.internal/emr-serverless/spark/%s:20250425`.
|
||||
* **Image**: an application's custom image runs in place of the release's: the `Driver` worker type's
|
||||
`imageConfiguration` in `workerTypeSpecifications`, or else the application's `imageConfiguration`,
|
||||
which applies to every worker type (local mode runs the executors in the driver's container, so an
|
||||
`Executor` image is not used). An `<account>.dkr.ecr.<region>.amazonaws.com/<repository>:<tag>` URI
|
||||
leads to Floci's [ECR](ecr.md), as a Lambda function's or an ECS task's image does, so the image is
|
||||
pushed to a repository there; the `repositoryUri` Floci's ECR hands out works too. The image is pulled
|
||||
again for every run, so a tag pushed again is what the next run gets; when the pull fails the image the
|
||||
Docker daemon already has runs, one built locally under that URI included, and without one the run is
|
||||
`FAILED` with "Job run could not start". `CreateApplication` refuses an image configuration without an
|
||||
`imageUri`, and `CreateApplication` and `UpdateApplication` an image whose ECR repository, AWS-shaped or
|
||||
a `repositoryUri` from Floci's ECR, is in another Region, both with `ValidationException` in Floci's own
|
||||
wording. An update that leaves `imageUri` out removes that image configuration. Without a custom image,
|
||||
`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`.
|
||||
|
||||
## Limitations and Differences from AWS
|
||||
|
||||
* **Jobs do not execute by default**: in the `immediate` runner mode `StartJobRun` records a job run and moves it through its states, but nothing runs. In the `docker` mode a Spark run executes in local mode in one container, so worker counts and sizes, initial and maximum capacity are not applied; a Hive run is `FAILED` without running, in Floci's own wording, as is a driver's failure. Of the monitoring configuration, the S3 log destination gets the driver's `stdout.gz` and `stderr.gz` once a run ends (no event logs, rotated files or uploads while it runs), and CloudWatch Logs the driver's output while it runs (there are no executor logs, local mode having no executors, and `encryptionKeyArn` is ignored).
|
||||
* **Unsourced errors**: AWS documents neither the error for a run submitted to an application whose auto-start is off nor the one for a run on a terminated application; Floci answers both with `ValidationException`. The same holds for a `BATCH` timeout outside 1 to 10080 minutes on `emr-7.11.0` or later (`ValidationException`) and for `GetJobRun` naming an attempt a run never made (`ResourceNotFoundException`), both in Floci's own wording. A run needs a `jobDriver`, as every `JobRun` carries one, and `jobDriver` is a union, so a run without a driver, or with one that sets both `sparkSubmit` and `hive` or neither, is refused with `ValidationException` too, in Floci's own wording.
|
||||
* **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 or on a job run.
|
||||
* **StopApplication with running jobs**: AWS requires running jobs to finish or be cancelled before an application stops. Floci does not enforce it; with the default duration of `0` no `BATCH` run is ever running.
|
||||
* **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.
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
+2
-2
@@ -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();
|
||||
}
|
||||
|
||||
+20
@@ -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,
|
||||
|
||||
+21
-3
@@ -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
|
||||
|
||||
+53
-1
@@ -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) {
|
||||
|
||||
+25
-6
@@ -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) {
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+22
@@ -725,4 +725,26 @@ class EcrRegistryManagerTest {
|
||||
"/var/lib/registry/docker/registry/v2/repositories/000000000000/us-east-1/team/app/_manifests",
|
||||
"/var/lib/registry/docker/registry/v2/repositories/000000000000/us-east-1/team/app/_uploads");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"123456789012.dkr.ecr.eu-west-1.amazonaws.com/spark/custom:7.5.0, eu-west-1",
|
||||
"123456789012.dkr.ecr.cn-north-1.amazonaws.com.cn/spark/custom:7.5.0, cn-north-1",
|
||||
"000000000000.dkr.ecr.us-east-1.localhost:4566/spark/custom:7.5.0, us-east-1",
|
||||
"000000000000.dkr.ecr.us-east-1.localhost.floci.io:4566/spark/custom:7.5.0, us-east-1",
|
||||
"localhost:4566/000000000000/us-west-2/spark/custom:7.5.0, us-west-2",
|
||||
"localhost.floci.io:4566/000000000000/us-west-2/spark/custom:7.5.0, us-west-2"
|
||||
})
|
||||
void anImageInAnEcrRepositoryHasItsRepositorysRegion(String image, String region) {
|
||||
assertEquals(Optional.of(region), EcrRegistryManager.imageRegion(image));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anImageOutsideEcrHasNoRegion() {
|
||||
for (String image : List.of("public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest", "python:3.12",
|
||||
"localhost:5000/spark/custom:7.5.0", "registry.internal/123456789012/us-east-1/spark:7.5.0")) {
|
||||
assertEquals(Optional.empty(), EcrRegistryManager.imageRegion(image), image);
|
||||
}
|
||||
assertEquals(Optional.empty(), EcrRegistryManager.imageRegion(null));
|
||||
}
|
||||
}
|
||||
+27
@@ -429,4 +429,31 @@ public class EmrServerlessIntegrationTest {
|
||||
equalTo("arn:aws:sso:::instance/ssoins-1234567890abcdef"))
|
||||
.body("application.jobLevelCostAllocationConfiguration.enabled", equalTo(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(12)
|
||||
void createApplicationRefusesACustomImageInAnotherRegion() {
|
||||
givenReq()
|
||||
.body("""
|
||||
{
|
||||
"releaseLabel": "emr-7.5.0",
|
||||
"type": "SPARK",
|
||||
"clientToken": "%s",
|
||||
"workerTypeSpecifications": {
|
||||
"Driver": {
|
||||
"imageConfiguration": {
|
||||
"imageUri": "000000000000.dkr.ecr.eu-west-1.amazonaws.com/spark/custom:7.5.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(UUID.randomUUID()))
|
||||
.when()
|
||||
.post("/applications")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", equalTo("Image 000000000000.dkr.ecr.eu-west-1.amazonaws.com/spark/custom:7.5.0 is in "
|
||||
+ "an Amazon ECR repository in eu-west-1; it must be in the application's Region, us-east-1."));
|
||||
}
|
||||
}
|
||||
+28
@@ -255,6 +255,7 @@ class EmrServerlessJobRunServiceTest {
|
||||
assertEquals(REGION, job.region());
|
||||
assertEquals("emr-7.5.0", job.releaseLabel());
|
||||
assertNull(job.imageTemplate());
|
||||
assertNull(job.customImage());
|
||||
assertNull(job.dockerNetwork());
|
||||
assertEquals(ROLE, job.executionRole());
|
||||
assertEquals(List.of("s3://bucket/jobs/app.jar"), job.application());
|
||||
@@ -264,6 +265,33 @@ class EmrServerlessJobRunServiceTest {
|
||||
assertNull(job.cloudWatchLogs());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRunnerGetsTheDriverWorkerTypesCustomImageElseTheApplicationsElseTheReleases() {
|
||||
FakeRunner runner = new FakeRunner();
|
||||
EmrServerlessJobRunService service = dockerService(runner);
|
||||
String applicationImage = "123456789012.dkr.ecr.us-east-1.amazonaws.com/spark/custom:7.5.0";
|
||||
String driverImage = "123456789012.dkr.ecr.us-east-1.amazonaws.com/spark/driver:7.5.0";
|
||||
CreateApplicationRequest wholeApplication = applicationRequest("custom", "emr-7.5.0", "SPARK");
|
||||
wholeApplication.setImageConfiguration(EmrServerlessServiceTest.image(applicationImage));
|
||||
// Local mode runs the executors in the driver's container, so an Executor image is not used.
|
||||
wholeApplication.setWorkerTypeSpecifications(
|
||||
Map.of("Executor", EmrServerlessServiceTest.workerType(driverImage)));
|
||||
CreateApplicationRequest perWorkerType = applicationRequest("per-worker-type", "emr-7.5.0", "SPARK");
|
||||
perWorkerType.setImageConfiguration(EmrServerlessServiceTest.image(applicationImage));
|
||||
perWorkerType.setWorkerTypeSpecifications(Map.of("Driver", EmrServerlessServiceTest.workerType(driverImage)));
|
||||
|
||||
service.startJobRun(applications.createApplication(wholeApplication).getApplicationId(), request(null, null));
|
||||
service.startJobRun(applications.createApplication(perWorkerType).getApplicationId(), request(null, null));
|
||||
service.startJobRun(applicationId, request(null, null));
|
||||
for (int i = 0; i < 3; i++) {
|
||||
runNext();
|
||||
}
|
||||
|
||||
assertEquals(applicationImage, runner.jobs.get(0).customImage());
|
||||
assertEquals(driverImage, runner.jobs.get(1).customImage());
|
||||
assertNull(runner.jobs.get(2).customImage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRunsDriverOutputGoesToCloudWatchWhenItsOwnOrTheApplicationsLoggingIsEnabled() {
|
||||
FakeRunner runner = new FakeRunner();
|
||||
|
||||
+113
@@ -2,10 +2,14 @@ package io.github.hectorvent.floci.services.emrserverless;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.PersistentStorage;
|
||||
import io.github.hectorvent.floci.services.emrserverless.model.Application;
|
||||
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.UpdateApplicationRequest;
|
||||
import io.github.hectorvent.floci.services.emrserverless.model.WorkerTypeSpecification;
|
||||
import io.github.hectorvent.floci.testing.InMemoryStorageFactory;
|
||||
import io.github.hectorvent.floci.testing.MutableClock;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -16,10 +20,13 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
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.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -28,6 +35,7 @@ class EmrServerlessServiceTest {
|
||||
private static final String REGION = "us-east-1";
|
||||
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";
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
@@ -90,4 +98,109 @@ class EmrServerlessServiceTest {
|
||||
assertEquals(app.getUpdatedAt(), reloaded.getUpdatedAt());
|
||||
assertEquals("create-00abc", reloaded.getClientToken());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUpdateLeavingTheImageUriOutRemovesTheImageConfiguration() {
|
||||
EmrServerlessService service = service();
|
||||
CreateApplicationRequest create = createRequest();
|
||||
create.setImageConfiguration(image(CUSTOM_IMAGE));
|
||||
create.setWorkerTypeSpecifications(Map.of("Driver", workerType(CUSTOM_IMAGE)));
|
||||
String applicationId = service.createApplication(create).getApplicationId();
|
||||
ImageConfiguration withoutUri = new ImageConfiguration();
|
||||
withoutUri.setApplicationLevelDigestResolution(true);
|
||||
UpdateApplicationRequest update = new UpdateApplicationRequest();
|
||||
update.setImageConfiguration(withoutUri);
|
||||
update.setWorkerTypeSpecifications(Map.of("Driver", workerType(null)));
|
||||
|
||||
Application updated = service.updateApplication(applicationId, update);
|
||||
|
||||
assertNull(updated.getImageConfiguration());
|
||||
assertNull(updated.getWorkerTypeSpecifications().get("Driver").getImageConfiguration());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNewApplicationsImageConfigurationNeedsAnImageUri() {
|
||||
EmrServerlessService service = service();
|
||||
CreateApplicationRequest application = createRequest();
|
||||
application.setImageConfiguration(image(null));
|
||||
CreateApplicationRequest workerType = createRequest();
|
||||
workerType.setWorkerTypeSpecifications(Map.of("Driver", workerType(null)));
|
||||
|
||||
AwsException noApplicationImage = assertThrows(AwsException.class,
|
||||
() -> service.createApplication(application));
|
||||
AwsException noDriverImage = assertThrows(AwsException.class, () -> service.createApplication(workerType));
|
||||
|
||||
assertEquals("ValidationException", noApplicationImage.getErrorCode());
|
||||
assertEquals("imageConfiguration.imageUri is required", noApplicationImage.getMessage());
|
||||
assertEquals("workerTypeSpecifications.Driver.imageConfiguration.imageUri is required",
|
||||
noDriverImage.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCustomImageMustBeInTheApplicationsRegion() {
|
||||
EmrServerlessService service = service();
|
||||
CreateApplicationRequest elsewhere = createRequest();
|
||||
elsewhere.setImageConfiguration(image("123456789012.dkr.ecr.us-west-2.amazonaws.com/spark/custom:7.5.0"));
|
||||
CreateApplicationRequest driverElsewhere = createRequest();
|
||||
driverElsewhere.setWorkerTypeSpecifications(
|
||||
Map.of("Driver", workerType("localhost:4566/000000000000/eu-west-1/spark/custom:7.5.0")));
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> service.createApplication(elsewhere));
|
||||
assertThrows(AwsException.class, () -> service.createApplication(driverElsewhere));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertEquals("Image 123456789012.dkr.ecr.us-west-2.amazonaws.com/spark/custom:7.5.0 is in an Amazon ECR "
|
||||
+ "repository in us-west-2; it must be in the application's Region, us-east-1.", refused.getMessage());
|
||||
// The repositoryUri Floci's ECR hands out, in the Region, and an image outside ECR, which has none.
|
||||
for (String imageUri : List.of("000000000000.dkr.ecr.us-east-1.localhost:4566/spark/custom:7.5.0",
|
||||
"python:3.12")) {
|
||||
CreateApplicationRequest accepted = createRequest();
|
||||
accepted.setImageConfiguration(image(imageUri));
|
||||
assertEquals(imageUri, service.createApplication(accepted).getImageConfiguration().getImageUri());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUpdateNamingAnImageInAnotherRegionChangesNothing() {
|
||||
EmrServerlessService service = service();
|
||||
CreateApplicationRequest create = createRequest();
|
||||
create.setImageConfiguration(image(CUSTOM_IMAGE));
|
||||
String applicationId = service.createApplication(create).getApplicationId();
|
||||
UpdateApplicationRequest update = new UpdateApplicationRequest();
|
||||
update.setReleaseLabel("emr-7.10.0");
|
||||
update.setImageConfiguration(image("123456789012.dkr.ecr.us-west-2.amazonaws.com/spark/custom:7.10.0"));
|
||||
|
||||
assertThrows(AwsException.class, () -> service.updateApplication(applicationId, update));
|
||||
|
||||
Application unchanged = service.getApplication(applicationId);
|
||||
assertEquals("emr-7.5.0", unchanged.getReleaseLabel());
|
||||
assertEquals(CUSTOM_IMAGE, unchanged.getImageConfiguration().getImageUri());
|
||||
}
|
||||
|
||||
private static EmrServerlessService service() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
when(config.defaultAccountId()).thenReturn(ACCOUNT_ID);
|
||||
return new EmrServerlessService(config, new InMemoryStorageFactory(ACCOUNT_ID),
|
||||
new RegionResolver(REGION, ACCOUNT_ID), new MutableClock());
|
||||
}
|
||||
|
||||
private static CreateApplicationRequest createRequest() {
|
||||
CreateApplicationRequest create = new CreateApplicationRequest();
|
||||
create.setReleaseLabel("emr-7.5.0");
|
||||
create.setType("SPARK");
|
||||
create.setClientToken(UUID.randomUUID().toString());
|
||||
return create;
|
||||
}
|
||||
|
||||
static ImageConfiguration image(String imageUri) {
|
||||
ImageConfiguration image = new ImageConfiguration();
|
||||
image.setImageUri(imageUri);
|
||||
return image;
|
||||
}
|
||||
|
||||
static WorkerTypeSpecification workerType(String imageUri) {
|
||||
WorkerTypeSpecification specification = new WorkerTypeSpecification();
|
||||
specification.setImageConfiguration(image(imageUri));
|
||||
return specification;
|
||||
}
|
||||
}
|
||||
+40
-4
@@ -7,12 +7,15 @@ 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.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
|
||||
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.lambda.launcher.ImageCacheService.LaunchImage;
|
||||
import io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentials;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.testing.MutableClock;
|
||||
@@ -50,6 +53,7 @@ import static org.mockito.Mockito.atLeastOnce;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -63,6 +67,7 @@ class EmrServerlessSparkRunnerTest {
|
||||
private final SparkJobRunner.Progress progress = mock(SparkJobRunner.Progress.class);
|
||||
private final S3Service s3 = mock(S3Service.class);
|
||||
private final ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
private final EcrRegistryManager ecr = mock(EcrRegistryManager.class);
|
||||
|
||||
@Test
|
||||
void sparkSubmitRunsLocallyOnFlocisS3ThenTheRunsOwnSettings() {
|
||||
@@ -145,6 +150,31 @@ class EmrServerlessSparkRunnerTest {
|
||||
// Its JVMs trust Floci's CA, the trust store going in with the CA bundle as the container is created.
|
||||
verify(spec).withJavaTrustStore();
|
||||
verify(lifecycle, never()).copyJavaTrustStore(anyString());
|
||||
// The release's image is not in an ECR repository, so it is pulled once, as the container is created.
|
||||
verify(lifecycle, never()).resolveImageForLaunch(anyString(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anImageInAnEcrRepositoryRunsFromFlocisRegistryPulledForEveryRun() {
|
||||
ContainerBuilder builder = mock(ContainerBuilder.class);
|
||||
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
|
||||
String custom = "123456789012.dkr.ecr.eu-west-1.amazonaws.com/spark/custom:7.5.0";
|
||||
String inFlocisRegistry = "localhost:5100/123456789012/eu-west-1/spark/custom:7.5.0";
|
||||
String pulled = "sha256:" + "3".repeat(64);
|
||||
when(builder.newContainer(anyString())).thenReturn(spec);
|
||||
when(builder.resolveImage(inFlocisRegistry)).thenReturn(inFlocisRegistry);
|
||||
when(ecr.rewriteImageUri(custom)).thenReturn(inFlocisRegistry);
|
||||
when(lifecycle.resolveImageForLaunch(inFlocisRegistry, ImagePullBehavior.DEFAULT, null))
|
||||
.thenReturn(new LaunchImage(pulled, "sha256:" + "4".repeat(64)));
|
||||
EmrServerlessSparkRunner runner = runner(builder);
|
||||
|
||||
runner.run(customImageJob(custom), progress);
|
||||
runner.run(customImageJob(custom), progress);
|
||||
|
||||
// By the id each pull resolved, which a push under the same tag cannot move.
|
||||
verify(lifecycle, times(2)).resolveImageForLaunch(inFlocisRegistry, ImagePullBehavior.DEFAULT, null);
|
||||
verify(builder, times(2)).newContainer(pulled);
|
||||
verify(builder, never()).newContainer(custom);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -511,7 +541,7 @@ class EmrServerlessSparkRunnerTest {
|
||||
when(docker.inspectContainerCmd("driver").exec().getState().getRunning()).thenReturn(false);
|
||||
when(docker.inspectContainerCmd("driver").exec().getState().getExitCodeLong()).thenReturn(0L);
|
||||
return new EmrServerlessSparkRunner(builder, lifecycle, logStreamer,
|
||||
mock(LaunchedContainerAwsEnv.class), mock(LambdaExecutionRoleCredentials.class), s3, config,
|
||||
mock(LaunchedContainerAwsEnv.class), mock(LambdaExecutionRoleCredentials.class), s3, ecr, config,
|
||||
new MutableClock(), Duration.ZERO);
|
||||
}
|
||||
|
||||
@@ -579,13 +609,19 @@ class EmrServerlessSparkRunnerTest {
|
||||
Map<String, String> sparkDefaults, Duration timeout, String logFolder,
|
||||
SparkJobRunner.CloudWatchLogs cloudWatchLogs) {
|
||||
return new SparkJobRunner.Job("emr-serverless", "00f0000000000001", "123456789012", "eu-west-1", "emr-7.5.0",
|
||||
imageTemplate, "floci-network", "arn:aws:iam::123456789012:role/job", sparkDefaults, application,
|
||||
null, timeout, logFolder, cloudWatchLogs);
|
||||
imageTemplate, null, "floci-network", "arn:aws:iam::123456789012:role/job", sparkDefaults,
|
||||
application, null, timeout, logFolder, cloudWatchLogs);
|
||||
}
|
||||
|
||||
private static SparkJobRunner.Job customImageJob(String customImage) {
|
||||
return new SparkJobRunner.Job("emr-serverless", "00f0000000000001", "123456789012", "eu-west-1", "emr-7.5.0",
|
||||
null, customImage, "floci-network", "arn:aws:iam::123456789012:role/job", Map.of(),
|
||||
List.of("s3://bucket/jobs/app.jar"), null, Duration.ZERO, null, null);
|
||||
}
|
||||
|
||||
private static SparkJobRunner.Job commandJob(List<String> command, Map<String, String> sparkDefaults) {
|
||||
return new SparkJobRunner.Job("emr", "s-1A2B3C4D5E6F7", "123456789012", "eu-west-1", "emr-7.5.0", null,
|
||||
"floci-network", "arn:aws:iam::123456789012:role/job", sparkDefaults, List.of(), command,
|
||||
null, "floci-network", "arn:aws:iam::123456789012:role/job", sparkDefaults, List.of(), command,
|
||||
Duration.ZERO, null, null);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user