feat(cloudformation): provision AWS::EMRServerless::Application (#9148)

A template can now create an EMR Serverless application. It was not
served, so the stack reported CREATE_COMPLETE with nothing behind it.
The provisioner goes through the services the EMR Serverless API uses,
so a stack and a direct call see the same application, and it does what
AWS's own resource handler does:

- The properties are read as the handler's model validation reads them,
  against the registry schema, now in the vendored property types; an
  Architecture outside its enum and a read-only ApplicationId or Arn
  are refused.
- Ref is the application id; Fn::GetAtt gives ApplicationId and Arn.
- A create sends every property to CreateApplication, the Key/Value
  lists of InitialCapacity and LogTypeMap as the API's maps.
- An update sends UpdateApplication the settings the template changed
  and drives the tags to the template's, removing any other. A dropped
  setting stays as it is, but for InitialCapacity, which the handler
  sends as an empty map, and so clears.
- Name and Type are create-only: a change replaces the application, and
  the old one is deleted once the update commits.
- A later resource's failure puts back the settings and tags the update
  changed; a failure of the update itself puts back what it had changed
  by then, nothing when UpdateApplication refused it, and a restore that
  fails keeps its snapshot for ContinueUpdateRollback.
- Neither an update nor a delete stops a STARTED application, so one
  the API refuses fails the resource, as on AWS.

The vendored create-only properties and schema surface also take AWS's
new AWS::CertificateManager::Certificate properties, RootHierarchyType
and CertificateUsage, which their drift checks on this change asked
for; the ACM provisioner accepts and ignores both.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-21 13:59:46 -04:00
1 parent 26c090d4d1
commit 858bf8d2db
12 files changed
+1323 -3

No files matched your search

@@ -76,6 +76,7 @@ import io.floci.aws.services.cloudformation.provisioners.EksCfnProvisioner;
import io.floci.aws.services.cloudformation.provisioners.ElastiCacheCfnProvisioner;
import io.floci.aws.services.cloudformation.provisioners.ElastiCacheServerlessCfnProvisioner;
import io.floci.aws.services.cloudformation.provisioners.ElbV2CfnProvisioner;
import io.floci.aws.services.cloudformation.provisioners.EmrServerlessCfnProvisioner;
import io.floci.aws.services.cloudformation.provisioners.EventsArchiveCfnProvisioner;
import io.floci.aws.services.cloudformation.provisioners.EventsCfnProvisioner;
import io.floci.aws.services.cloudformation.provisioners.EventsV2CfnProvisioner;
@@ -153,6 +154,8 @@ import io.floci.aws.services.elasticache.ElastiCacheMemcachedService;
import io.floci.aws.services.elasticache.ElastiCacheServerlessService;
import io.floci.aws.services.elasticache.ElastiCacheService;
import io.floci.aws.services.elbv2.ElbV2Service;
import io.floci.aws.services.emrserverless.EmrServerlessJobRunService;
import io.floci.aws.services.emrserverless.EmrServerlessService;
import io.floci.aws.services.eventbridge.EventBridgeService;
import io.floci.aws.services.eventbridgev2.EventBridgeV2Service;
import io.floci.aws.services.firehose.FirehoseService;
@@ -277,6 +280,8 @@ final class CfnProvisionerFixture {
private CloudTrailService cloudTrailService;
private SchedulerService schedulerService;
private CodeDeployService codeDeployService;
private EmrServerlessService emrServerlessService;
private EmrServerlessJobRunService emrServerlessJobRunService;
private TransferService transferService;
// Services that back a provisioner without being a constructor argument of the
// dispatcher. They exist only so inferredProvisioners() can wire their provisioner.
@@ -563,6 +568,9 @@ final class CfnProvisionerFixture {
if (codeDeployService != null) {
discovered.add(new CodeDeployCfnProvisioner(codeDeployService));
}
if (emrServerlessService != null && emrServerlessJobRunService != null) {
discovered.add(new EmrServerlessCfnProvisioner(emrServerlessService, emrServerlessJobRunService));
}
if (transferService != null) {
discovered.add(new TransferCfnProvisioner(transferService));
}
@@ -793,6 +801,16 @@ final class CfnProvisionerFixture {
return this;
}
public Builder emrServerless(EmrServerlessService v) {
this.emrServerlessService = v;
return this;
}
public Builder emrServerlessJobRuns(EmrServerlessJobRunService v) {
this.emrServerlessJobRunService = v;
return this;
}
public Builder transfer(TransferService v) {
this.transferService = v;
return this;
@@ -0,0 +1,119 @@
package io.floci.aws.services.cloudformation;
import io.floci.aws.testing.CfnStackWaits;
import io.floci.aws.testing.CfnTestStack;
import io.floci.aws.testing.EmrServerlessRequests;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.services.cloudformation.model.Stack;
import static io.floci.aws.testing.CfnStackWaits.output;
import static org.hamcrest.Matchers.aMapWithSize;
import static org.hamcrest.Matchers.anEmptyMap;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
/**
* Provisions {@code AWS::EMRServerless::Application} through a stack and reads the application back through EMR
* Serverless: the template's settings reach it in the API's shape, {@code Ref} and {@code Fn::GetAtt} name it, an
* update changes it in place, a later resource's failure puts it back, a new {@code Name} replaces it, and deleting
* the stack deletes it.
*/
@QuarkusTest
class EmrServerlessApplicationCfnIntegrationTest {
@RegisterExtension
final CfnTestStack stack = new CfnTestStack("emr-serverless-app-cfn-it");
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void createUpdateRollBackReplaceAndDeleteAnApplication() {
Stack created = stack.create(template("etl", 30, "v1", true, false));
String id = output(created, "Ref");
assertEquals(id, output(created, "ApplicationId"));
assertEquals("arn:aws:emr-serverless:us-east-1:000000000000:/applications/" + id, output(created, "Arn"));
getApplication(id).statusCode(200)
.body("application.name", equalTo("etl"))
.body("application.type", equalTo("SPARK"))
.body("application.state", equalTo("CREATED"))
.body("application.autoStopConfiguration.idleTimeoutMinutes", equalTo(30))
.body("application.initialCapacity.Driver.workerCount", equalTo(2))
.body("application.initialCapacity.Driver.workerConfiguration.cpu", equalTo("2 vCPU"))
.body("application.monitoringConfiguration.cloudWatchLoggingConfiguration.logTypes.SPARK_DRIVER[0]",
equalTo("STDOUT"))
.body("application.runtimeConfiguration[0].properties", hasEntry("spark.driver.cores", "2"))
.body("application.tags", aMapWithSize(1))
.body("application.tags.stage", equalTo("v1"));
// The update drops InitialCapacity, which clears it, and changes the idle timeout and the tag in place.
Stack updated = stack.update(template("etl", 45, "v2", false, false), "UPDATE_COMPLETE");
assertEquals(id, output(updated, "Ref"));
getApplication(id).statusCode(200)
.body("application.autoStopConfiguration.idleTimeoutMinutes", equalTo(45))
.body("application.initialCapacity", anEmptyMap())
.body("application.tags.stage", equalTo("v2"));
stack.update(template("etl", 60, "v3", false, true), "UPDATE_ROLLBACK_COMPLETE");
getApplication(id).statusCode(200)
.body("application.autoStopConfiguration.idleTimeoutMinutes", equalTo(45))
.body("application.tags.stage", equalTo("v2"));
// Name is create-only: a new one replaces the application, and the committed update deletes the old one.
Stack replaced = stack.update(template("etl-2", 45, "v2", false, false), "UPDATE_COMPLETE");
String replacement = output(replaced, "Ref");
assertNotEquals(id, replacement);
getApplication(replacement).statusCode(200).body("application.name", equalTo("etl-2"));
getApplication(id).statusCode(200).body("application.state", equalTo("TERMINATED"));
CfnStackWaits.deleteStack(stack.name());
getApplication(replacement).statusCode(200).body("application.state", equalTo("TERMINATED"));
}
private static String template(String name, int idleMinutes, String stage, boolean initialCapacity,
boolean laterFails) {
return """
{
"Resources": {
"App": {
"Type": "AWS::EMRServerless::Application",
"Properties": {
"Name": "%s",
"ReleaseLabel": "emr-7.5.0",
"Type": "SPARK",
"AutoStopConfiguration": {"Enabled": true, "IdleTimeoutMinutes": %d},%s
"MonitoringConfiguration": {"CloudWatchLoggingConfiguration": {"Enabled": true,
"LogTypeMap": [{"Key": "SPARK_DRIVER", "Value": ["STDOUT"]}]}},
"RuntimeConfiguration": [{"Classification": "spark-defaults",
"Properties": {"spark.driver.cores": "2"}}],
"Tags": [{"Key": "stage", "Value": "%s"}]
}
}%s
},
"Outputs": {
"Ref": {"Value": {"Ref": "App"}},
"ApplicationId": {"Value": {"Fn::GetAtt": ["App", "ApplicationId"]}},
"Arn": {"Value": {"Fn::GetAtt": ["App", "Arn"]}}
}
}
""".formatted(name, idleMinutes, initialCapacity ? """
"InitialCapacity": [{"Key": "Driver", "Value": {"WorkerCount": 2,
"WorkerConfiguration": {"Cpu": "2 vCPU", "Memory": "4 GB"}}}],""" : "", stage,
laterFails ? CfnStackWaits.failingResourceAfter("App") : "");
}
private static ValidatableResponse getApplication(String id) {
return EmrServerlessRequests.emrServerless("us-east-1").when().get("/applications/" + id).then();
}
}
@@ -0,0 +1,427 @@
package io.floci.aws.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.emrserverless.EmrServerlessJobRunService;
import io.floci.aws.services.emrserverless.EmrServerlessService;
import io.floci.aws.services.emrserverless.model.Application;
import io.floci.aws.services.emrserverless.model.AutoStopConfiguration;
import io.floci.aws.services.emrserverless.model.CreateApplicationRequest;
import io.floci.aws.services.emrserverless.model.InitialCapacityConfig;
import io.floci.aws.services.emrserverless.model.SchedulerConfiguration;
import io.floci.aws.services.emrserverless.model.UpdateApplicationRequest;
import io.floci.aws.services.emrserverless.model.WorkerConfiguration;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
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.verifyNoInteractions;
import static org.mockito.Mockito.when;
/** {@code AWS::EMRServerless::Application} in isolation, with the EMR Serverless services mocked. */
class EmrServerlessCfnProvisionerTest {
private static final String ID = "00fexampleapp01";
private static final String ARN = "arn:aws:emr-serverless:us-east-1:000000000000:/applications/" + ID;
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final EmrServerlessService.ResourceArn RESOURCE =
new EmrServerlessService.ResourceArn(ARN, ID, null, null);
private final EmrServerlessService applications = mock(EmrServerlessService.class);
private final EmrServerlessJobRunService jobRuns = mock(EmrServerlessJobRunService.class);
private final EmrServerlessCfnProvisioner provisioner = new EmrServerlessCfnProvisioner(applications, jobRuns);
private static ProvisionContext ctx(String priorPhysicalId, String priorProperties) {
return new ProvisionContext(CloudFormationTemplateEngine.standalone("000000000000", "us-east-1", "my-stack",
MAPPER, null), "us-east-1", "000000000000", "my-stack", priorPhysicalId, event -> { },
priorProperties == null ? null : json(priorProperties));
}
private static StackResource resource() {
StackResource r = new StackResource();
r.setLogicalId("App");
r.setResourceType("AWS::EMRServerless::Application");
r.setAttributes(new HashMap<>());
return r;
}
/** The resource as the create that made application {@link #ID} left it. */
private static StackResource provisioned() {
StackResource r = resource();
r.setPhysicalId(ID);
r.getAttributes().put("ApplicationId", ID);
r.getAttributes().put("Arn", ARN);
return r;
}
private static Application app(String id, Map<String, String> tags) {
Application app = new Application();
app.setApplicationId(id);
app.setArn("arn:aws:emr-serverless:us-east-1:000000000000:/applications/" + id);
app.setReleaseLabel("emr-7.5.0");
app.setType("SPARK");
app.setState("CREATED");
app.setTags(new LinkedHashMap<>(tags));
return app;
}
/** Application {@link #ID} stopping after 15 idle minutes with two pre-initialized drivers. */
private static Application live() {
Application live = app(ID, Map.of("team", "data"));
AutoStopConfiguration autoStop = new AutoStopConfiguration();
autoStop.setEnabled(true);
autoStop.setIdleTimeoutMinutes(15);
live.setAutoStopConfiguration(autoStop);
WorkerConfiguration worker = new WorkerConfiguration();
worker.setCpu("2 vCPU");
worker.setMemory("4 GB");
InitialCapacityConfig capacity = new InitialCapacityConfig();
capacity.setWorkerCount(2L);
capacity.setWorkerConfiguration(worker);
live.setInitialCapacity(Map.of("Driver", capacity));
return live;
}
private static JsonNode json(String text) {
try {
return MAPPER.readTree(text);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(text, e);
}
}
/** Tags in the order given, as key, value, key, value. */
private static Map<String, String> tags(String... keysAndValues) {
Map<String, String> tags = new LinkedHashMap<>();
for (int i = 0; i < keysAndValues.length; i += 2) {
tags.put(keysAndValues[i], keysAndValues[i + 1]);
}
return tags;
}
/** What ListTagsForResource answers for application {@link #ID}, the first time and then every time after. */
private void stubTags(Map<String, String> first, Map<String, String> after) {
when(applications.resourceArn(ARN)).thenReturn(RESOURCE);
when(applications.listTags(RESOURCE)).thenReturn(first, after);
}
private static final String PRIOR = """
{"ReleaseLabel": "emr-7.5.0", "Type": "SPARK",
"AutoStopConfiguration": {"Enabled": true, "IdleTimeoutMinutes": 15},
"InitialCapacity": [{"Key": "Driver",
"Value": {"WorkerCount": 2, "WorkerConfiguration": {"Cpu": "2 vCPU", "Memory": "4 GB"}}}],
"Tags": [{"Key": "team", "Value": "data"}]}
""";
private static final String UPDATED = """
{"ReleaseLabel": "emr-7.5.0", "Type": "SPARK",
"AutoStopConfiguration": {"Enabled": true, "IdleTimeoutMinutes": 30},
"Tags": [{"Key": "stage", "Value": "prod"}]}
""";
@Test
void createsTheApplicationWithTheTemplateInTheApiShape() {
when(applications.createApplication(any())).thenReturn(app(ID, Map.of()));
StackResource r = resource();
provisioner.provision(r, json("""
{"Name": "etl", "ReleaseLabel": "emr-7.5.0", "Type": "SPARK", "Architecture": "ARM64",
"InitialCapacity": [{"Key": "Driver",
"Value": {"WorkerCount": "2", "WorkerConfiguration": {"Cpu": "2 vCPU", "Memory": "4 GB"}}}],
"AutoStopConfiguration": {"Enabled": "true", "IdleTimeoutMinutes": "30"},
"MonitoringConfiguration": {"CloudWatchLoggingConfiguration": {"Enabled": true,
"LogTypeMap": [{"Key": "SPARK_DRIVER", "Value": ["STDOUT", "STDERR"]}]}},
"RuntimeConfiguration": [{"Classification": "spark-defaults",
"Properties": {"spark.driver.cores": "2"}}],
"WorkerTypeSpecifications": {"Driver": {"ImageConfiguration":
{"ImageUri": "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest"}}},
"SchedulerConfiguration": {"MaxConcurrentRuns": "5"},
"Tags": [{"Key": "team", "Value": "data"}]}
"""), ctx(null, null));
ArgumentCaptor<CreateApplicationRequest> created = ArgumentCaptor.forClass(CreateApplicationRequest.class);
verify(applications).createApplication(created.capture());
CreateApplicationRequest request = created.getValue();
assertEquals("etl", request.getName());
assertEquals("SPARK", request.getType());
assertEquals("emr-7.5.0", request.getReleaseLabel());
assertEquals("ARM64", request.getArchitecture());
assertEquals(2L, request.getInitialCapacity().get("Driver").getWorkerCount());
assertEquals("4 GB", request.getInitialCapacity().get("Driver").getWorkerConfiguration().getMemory());
assertEquals(Boolean.TRUE, request.getAutoStopConfiguration().getEnabled());
assertEquals(30, request.getAutoStopConfiguration().getIdleTimeoutMinutes());
assertEquals(json("""
{"cloudWatchLoggingConfiguration": {"enabled": true,
"logTypes": {"SPARK_DRIVER": ["STDOUT", "STDERR"]}}}
"""), MAPPER.valueToTree(request.getMonitoringConfiguration()));
assertEquals(json("""
[{"classification": "spark-defaults", "properties": {"spark.driver.cores": "2"}}]
"""), MAPPER.valueToTree(request.getRuntimeConfiguration()));
assertEquals("public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest",
request.getWorkerTypeSpecifications().get("Driver").getImageConfiguration().getImageUri());
assertEquals(json("{\"maxConcurrentRuns\": 5}"), MAPPER.valueToTree(request.getSchedulerConfiguration()));
assertEquals(Map.of("team", "data"), request.getTags());
assertFalse(request.getClientToken().isBlank());
assertEquals(ID, r.getPhysicalId());
assertEquals(ID, r.getAttributes().get("ApplicationId"));
assertEquals("arn:aws:emr-serverless:us-east-1:000000000000:/applications/" + ID, r.getAttributes().get("Arn"));
}
@Test
void aTemplateTheHandlersModelValidationRefusesFailsBeforeAnyCall() {
AwsException missing = assertThrows(AwsException.class,
() -> provisioner.provision(resource(), json("{\"Type\": \"SPARK\"}"), ctx(null, null)));
AwsException extraneous = assertThrows(AwsException.class, () -> provisioner.provision(resource(), json("""
{"ReleaseLabel": "emr-7.5.0", "Type": "SPARK", "AutoStopConfiguration": {"Idle": 5}}
"""), ctx(null, null)));
AwsException architecture = assertThrows(AwsException.class, () -> provisioner.provision(resource(),
json("{\"ReleaseLabel\": \"emr-7.5.0\", \"Type\": \"SPARK\", \"Architecture\": \"AMD64\"}"),
ctx(null, null)));
AwsException readOnly = assertThrows(AwsException.class, () -> provisioner.provision(resource(),
json("{\"ReleaseLabel\": \"emr-7.5.0\", \"Type\": \"SPARK\", \"ApplicationId\": \"00fmine\"}"),
ctx(null, null)));
assertEquals("Model validation failed (#: required key [ReleaseLabel] not found)", missing.getMessage());
assertEquals("Model validation failed (#/AutoStopConfiguration: extraneous key [Idle] is not permitted)",
extraneous.getMessage());
assertEquals("Model validation failed (#/Architecture: AMD64 is not a valid enum value)",
architecture.getMessage());
assertEquals("ApplicationId is a ReadOnly property which cannot be specified in the template",
readOnly.getMessage());
verifyNoInteractions(applications, jobRuns);
}
@Test
void anUpdateSendsWhatTheTemplateChangedClearsADroppedInitialCapacityAndTakesTheTagsToTheTemplates() {
when(applications.findLive(ID)).thenReturn(Optional.of(live()));
stubTags(tags("team", "data", "owner", "ops"), tags());
StackResource r = provisioned();
provisioner.provision(r, json(UPDATED), ctx(ID, PRIOR));
ArgumentCaptor<UpdateApplicationRequest> updated = ArgumentCaptor.forClass(UpdateApplicationRequest.class);
verify(jobRuns).updateApplication(eq(ID), updated.capture());
UpdateApplicationRequest request = updated.getValue();
assertEquals(30, request.getAutoStopConfiguration().getIdleTimeoutMinutes());
assertEquals(Map.of(), request.getInitialCapacity());
assertNull(request.getReleaseLabel());
assertNull(request.getArchitecture());
verify(applications).untagResource(RESOURCE, List.of("team", "owner"));
verify(applications).tagResource(RESOURCE, Map.of("stage", "prod"));
verify(applications, never()).createApplication(any());
assertEquals(ID, r.getPhysicalId());
assertTrue(r.getAttributes().containsKey(EmrServerlessCfnProvisioner.SNAPSHOT_ATTR));
}
@Test
void aRollbackPutsBackTheSettingsAndTagsTheUpdateChanged() {
when(applications.findLive(ID)).thenReturn(Optional.of(live()));
stubTags(tags("team", "data"), tags("stage", "prod"));
StackResource r = provisioned();
provisioner.provision(r, json(UPDATED), ctx(ID, PRIOR));
assertTrue(provisioner.rollbackUpdate(r));
ArgumentCaptor<UpdateApplicationRequest> updates = ArgumentCaptor.forClass(UpdateApplicationRequest.class);
verify(jobRuns, times(2)).updateApplication(eq(ID), updates.capture());
UpdateApplicationRequest restore = updates.getAllValues().get(1);
assertEquals(15, restore.getAutoStopConfiguration().getIdleTimeoutMinutes());
assertEquals(2L, restore.getInitialCapacity().get("Driver").getWorkerCount());
assertNull(restore.getReleaseLabel());
verify(applications).untagResource(RESOURCE, List.of("stage"));
verify(applications).tagResource(RESOURCE, Map.of("team", "data"));
assertFalse(r.getAttributes().containsKey(EmrServerlessCfnProvisioner.SNAPSHOT_ATTR));
}
@Test
void aSettingTheApplicationDidNotHoldIsClearedOnRollbackWhereAnEmptyValueClearsIt() {
Application live = app(ID, Map.of());
when(applications.findLive(ID)).thenReturn(Optional.of(live));
stubTags(tags(), tags());
StackResource r = provisioned();
provisioner.provision(r, json("""
{"ReleaseLabel": "emr-7.5.0", "Type": "SPARK",
"ImageConfiguration": {"ImageUri": "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest"},
"AutoStartConfiguration": {"Enabled": false}}
"""), ctx(ID, "{\"ReleaseLabel\": \"emr-7.5.0\", \"Type\": \"SPARK\"}"));
provisioner.rollbackUpdate(r);
ArgumentCaptor<UpdateApplicationRequest> updates = ArgumentCaptor.forClass(UpdateApplicationRequest.class);
verify(jobRuns, times(2)).updateApplication(eq(ID), updates.capture());
UpdateApplicationRequest restore = updates.getAllValues().get(1);
assertNull(restore.getImageConfiguration().getImageUri());
assertNull(restore.getAutoStartConfiguration());
}
@Test
void anUpdateUpdateApplicationRefusesChangedNothingSoNothingIsPutBack() {
when(applications.findLive(ID)).thenReturn(Optional.of(live()));
AwsException refused = new AwsException("ValidationException", "refused", 400);
// A STARTED application refuses the restore's stopped-only settings as well.
when(jobRuns.updateApplication(eq(ID), any())).thenThrow(refused);
StackResource r = provisioned();
AwsException thrown = assertThrows(AwsException.class,
() -> provisioner.provision(r, json(UPDATED), ctx(ID, PRIOR)));
assertEquals(refused, thrown);
verify(jobRuns, times(1)).updateApplication(eq(ID), any());
verify(applications, never()).listTags(any());
assertNull(r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
}
@Test
void aTagFailureAfterTheSettingsChangedPutsTheSettingsAndTagsBackBeforeItPropagates() {
when(applications.findLive(ID)).thenReturn(Optional.of(live()));
stubTags(tags("team", "data"), tags());
AwsException tagging = new AwsException("ValidationException", "tagging", 400);
doThrow(tagging).doNothing().when(applications).tagResource(eq(RESOURCE), any());
StackResource r = provisioned();
AwsException thrown = assertThrows(AwsException.class,
() -> provisioner.provision(r, json(UPDATED), ctx(ID, PRIOR)));
assertEquals(tagging, thrown);
ArgumentCaptor<UpdateApplicationRequest> updates = ArgumentCaptor.forClass(UpdateApplicationRequest.class);
verify(jobRuns, times(2)).updateApplication(eq(ID), updates.capture());
assertEquals(15, updates.getAllValues().get(1).getAutoStopConfiguration().getIdleTimeoutMinutes());
verify(applications).tagResource(RESOURCE, Map.of("team", "data"));
assertNull(r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
}
@Test
void aSchedulerChangeIsPutBackWithTheMembersTheUpdateSentSoAStartedApplicationTakesIt() {
Application live = app(ID, Map.of());
SchedulerConfiguration scheduler = new SchedulerConfiguration();
scheduler.setProperty("maxConcurrentRuns", 15);
scheduler.setProperty("queueTimeoutMinutes", 360);
live.setSchedulerConfiguration(scheduler);
when(applications.findLive(ID)).thenReturn(Optional.of(live));
stubTags(tags(), tags());
StackResource r = provisioned();
provisioner.provision(r, json("""
{"ReleaseLabel": "emr-7.5.0", "Type": "SPARK", "SchedulerConfiguration": {"MaxConcurrentRuns": 10}}
"""), ctx(ID, "{\"ReleaseLabel\": \"emr-7.5.0\", \"Type\": \"SPARK\"}"));
provisioner.rollbackUpdate(r);
ArgumentCaptor<UpdateApplicationRequest> updates = ArgumentCaptor.forClass(UpdateApplicationRequest.class);
verify(jobRuns, times(2)).updateApplication(eq(ID), updates.capture());
assertEquals(json("{\"maxConcurrentRuns\": 10}"),
MAPPER.valueToTree(updates.getAllValues().get(0).getSchedulerConfiguration()));
assertEquals(json("{\"maxConcurrentRuns\": 15}"),
MAPPER.valueToTree(updates.getAllValues().get(1).getSchedulerConfiguration()));
}
@Test
void aSchedulerTheUpdateSetWhereQueuingWasOffIsLeftAsTheUpdateLeftIt() {
Application live = app(ID, Map.of());
live.setSchedulerOff(true);
when(applications.findLive(ID)).thenReturn(Optional.of(live));
stubTags(tags(), tags());
StackResource r = provisioned();
provisioner.provision(r, json("""
{"ReleaseLabel": "emr-7.5.0", "Type": "SPARK", "SchedulerConfiguration": {"MaxConcurrentRuns": 10},
"AutoStopConfiguration": {"Enabled": false}}
"""), ctx(ID, "{\"ReleaseLabel\": \"emr-7.5.0\", \"Type\": \"SPARK\"}"));
provisioner.rollbackUpdate(r);
verify(jobRuns, times(1)).updateApplication(eq(ID), any());
}
@Test
void anUndoThatFailedLeavesItsSnapshotForContinueUpdateRollback() {
StackResource previous = provisioned();
StackResource attempted = provisioned();
attempted.getAttributes().put(EmrServerlessCfnProvisioner.SNAPSHOT_ATTR, "{}");
StackResource undone = provisioned();
undone.getAttributes().put(EmrServerlessCfnProvisioner.SNAPSHOT_ATTR, "{}");
provisioner.mergeFailedUpdateResourceTracking(previous, undone);
assertFalse(previous.getAttributes().containsKey(EmrServerlessCfnProvisioner.SNAPSHOT_ATTR));
attempted.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, "Could not restore");
provisioner.mergeFailedUpdateResourceTracking(previous, attempted);
assertEquals("{}", previous.getAttributes().get(EmrServerlessCfnProvisioner.SNAPSHOT_ATTR));
}
@Test
void anUpdateOfAnApplicationThatIsGoneFailsAsTheHandlerDoes() {
when(applications.findLive(ID)).thenReturn(Optional.empty());
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(provisioned(), json(UPDATED), ctx(ID, PRIOR)));
assertEquals("Resource of type 'AWS::EMRServerless::Application' with identifier '" + ID
+ "' was not found.", e.getMessage());
verifyNoInteractions(jobRuns);
}
@Test
void changingTheNameReplacesTheApplicationAndLeavesTheOldOneForTheCleanup() {
when(applications.createApplication(any())).thenReturn(app("00fnewapp02", Map.of()));
StackResource r = provisioned();
provisioner.provision(r, json("{\"Name\": \"b\", \"ReleaseLabel\": \"emr-7.5.0\", \"Type\": \"SPARK\"}"),
ctx(ID, "{\"Name\": \"a\", \"ReleaseLabel\": \"emr-7.5.0\", \"Type\": \"SPARK\"}"));
assertEquals("00fnewapp02", r.getPhysicalId());
assertTrue(provisioner.hasReplacementUpdate(r));
assertEquals(ID, provisioner.updateCleanupPhysicalId(r));
verify(applications, never()).findLive(any());
verifyNoInteractions(jobRuns);
}
@Test
void aStubFromBeforeTheTypeHadAProvisionerIsTakenOverByACreate() {
when(applications.createApplication(any())).thenReturn(app(ID, Map.of()));
StackResource r = resource();
r.setPhysicalId("App-0a1b2c3d");
r.getAttributes().put("Arn", CfnResourceDispatcher.STUB_ARN_PREFIX + "App");
provisioner.provision(r, json("{\"ReleaseLabel\": \"emr-7.5.0\", \"Type\": \"SPARK\"}"),
ctx("App-0a1b2c3d", "{\"ReleaseLabel\": \"emr-7.5.0\", \"Type\": \"SPARK\"}"));
assertEquals(ID, r.getPhysicalId());
assertEquals(ARN, r.getAttributes().get("Arn"));
verify(applications, never()).findLive(any());
}
@Test
void theDeleteRemovesALiveApplicationAndLeavesAGoneOneAlone() {
when(applications.whileLive(eq(ID), any())).thenAnswer(inv -> {
inv.<Consumer<Application>>getArgument(1).accept(live());
return true;
});
provisioner.delete("AWS::EMRServerless::Application", ID, "us-east-1");
provisioner.delete("AWS::EMRServerless::Application", "00fgoneapp03", "us-east-1");
verify(applications).deleteApplication(ID);
verify(applications, never()).deleteApplication("00fgoneapp03");
}
}