diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 367c8c987d..0c81f0d14d 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -220,6 +220,7 @@ cross-resource references. | ECS | `Cluster`, `TaskDefinition`, `Service`, `CapacityProvider`, `ClusterCapacityProviderAssociations` | | EFS | `FileSystem` (metadata only, there is no NFS data plane), `MountTarget` (`SecurityGroups` update in place, every other property replaces), `AccessPoint` (`AccessPointTags` update in place, every other property replaces) | | EKS | `Cluster` (created with `Name`, `Version`, `RoleArn`, `Tags`, `EncryptionConfig`, `ResourcesVpcConfig`, `Logging`, `AccessConfig` and `KubernetesNetworkConfig.IpFamily` and `ServiceIpv4Cidr`, a replacement included; a change to `EncryptionConfig`, `IpFamily` or `ServiceIpv4Cidr` replaces the cluster with the new value applied; `ElasticLoadBalancing`, `ServiceIpv6Cidr` and `ResourcesVpcConfig.ControlPlaneEgressMode` are accepted and ignored; updated in place for `Tags`, keeping tags added outside the stack, for `Logging`, for `AccessConfig.AuthenticationMode` (a mode cannot be moved back, so a stack update that does so fails, and a stack rollback restores it) and for `ResourcesVpcConfig` endpoint access and `PublicAccessCidrs`; a change to `Name`, `RoleArn`, `EncryptionConfig`, `BootstrapSelfManagedAddons`, `OutpostConfig`, `AccessConfig.BootstrapClusterCreatorAdminPermissions`, `KubernetesNetworkConfig.IpFamily` or `KubernetesNetworkConfig.ServiceIpv4Cidr` replaces the cluster, as the registry marks them create-only, and deletes the old one once the update commits; a change to `Version` is accepted with a warning and not applied, as the emulator has no `UpdateClusterVersion`; a change to the subnets or security groups of `ResourcesVpcConfig` fails the resource, as the emulator's `UpdateClusterConfig` does not change them), `Nodegroup` (created with `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets` and `Tags`; updated in place for `Tags`, keeping tags added outside the stack; a change to `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets`, `AmiType`, `CapacityType`, `DiskSize`, `InstanceTypes` or `RemoteAccess` replaces the nodegroup, as the registry marks them create-only, and deletes the old one once the update commits; `ScalingConfig`, `Labels`, `Taints`, `UpdateConfig`, `Version`, `ReleaseVersion`, `ForceUpdateEnabled`, `LaunchTemplate`, `NodeRepairConfig` and `WarmPoolConfig` are accepted and not applied, whether changed or dropped, with a warning, as the emulator cannot update a nodegroup in place) | +| EMR on EKS | `VirtualCluster` (created with `Name`, `ContainerProvider`, `SecurityConfigurationId`, `SessionEnabled` and `Tags`; a template that sets the read-only `Arn` or `Id` is refused; updated in place for `Tags` alone, which end as the template lists them, any other but an `aws:` one removed; a change to any other property replaces the virtual cluster, as the registry marks them create-only, and terminates the old one once the update commits; an update of a virtual cluster that is terminated or gone fails) | | EMR Serverless | `Application` (created with every property, `Name` and `Type` included; updated in place through `UpdateApplication` for the settings a template changes, a dropped setting kept as it is but for `InitialCapacity`, which is cleared, and for `Tags`, which end as the template lists them, any other removed; a change to `Name` or `Type` replaces the application and deletes the old one once the update commits; neither an update nor a delete stops a `STARTED` application, so one it refuses fails the resource, as on AWS) | | RDS | `DBInstance` (starts a real container), `DBCluster` (starts a real container), `DBSubnetGroup`, `DBParameterGroup`, `DBClusterParameterGroup`, `DBProxy`, `DBProxyTargetGroup` | | Aurora DSQL | `Cluster` | diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrContainersCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrContainersCfnProvisioner.java new file mode 100644 index 0000000000..fcdf8e2951 --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrContainersCfnProvisioner.java @@ -0,0 +1,224 @@ +package io.floci.aws.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.cloudformation.model.StackResource; +import io.floci.aws.services.emrcontainers.EmrContainersService; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * CloudFormation provisioning for {@code AWS::EMRContainers::VirtualCluster}, through the service the EMR on EKS API + * itself uses. {@code Ref} is the virtual cluster's id; {@code Fn::GetAtt} gives {@code Id} and {@code Arn}. + * + *

It does what AWS's resource handler does (aws-cloudformation-resource-providers-emrcontainers): the properties are + * read as the handler's model validation reads them, a template that sets the read-only {@code Arn} is refused in the + * handler's words, and a create sends the rest to CreateVirtualCluster. {@code Name}, {@code ContainerProvider}, + * {@code SecurityConfigurationId} and {@code SessionEnabled} are create-only, so a change to any of them replaces the + * virtual cluster; an update otherwise changes the tags alone, driving them to the template's and removing any other + * but an {@code aws:} one. An update of a virtual cluster that is terminated or gone fails as the handler's does, and + * the delete of one is taken as done, as the handler takes DeleteVirtualCluster's answer for it. + */ +@ApplicationScoped +public class EmrContainersCfnProvisioner implements CfnResourceProvisioner { + + private static final String TYPE = "AWS::EMRContainers::VirtualCluster"; + /** The tags an in-place update is about to change, for {@link #rollbackUpdate} to put back. */ + static final String SNAPSHOT_ATTR = "__FlociEmrContainersVirtualClusterUpdateSnapshot"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + /** The schema's read-only properties, which a user cannot set. */ + private static final List READ_ONLY = List.of("Arn", "Id"); + private static final String SYSTEM_TAG_PREFIX = "aws:"; + + private final EmrContainersService service; + + @Inject + public EmrContainersCfnProvisioner(EmrContainersService service) { + this.service = service; + } + + @Override + public Set resourceTypes() { + return Set.of(TYPE); + } + + @Override + public boolean hasReplacementUpdate(StackResource resource) { + return ReplacementCleanup.hasReplacement(resource); + } + + @Override + public String updateCleanupPhysicalId(StackResource resource) { + return ReplacementCleanup.cleanupPhysicalId(resource); + } + + @Override + public UpdateCleanupResult completeUpdate(StackResource resource) { + resource.getAttributes().remove(SNAPSHOT_ATTR); + return ReplacementCleanup.complete(resource, this::delete); + } + + /** + * An in-place update whose own undo failed leaves its snapshot on the attempted resource, which the engine discards + * for the previous one: carried over, it lets ContinueUpdateRollback try the restore again. + */ + @Override + public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) { + CfnRollback.carryFailedUndoSnapshot(previous, attempted, SNAPSHOT_ATTR); + } + + @Override + public void clearUpdate(StackResource resource) { + resource.getAttributes().remove(SNAPSHOT_ATTR); + ReplacementCleanup.clear(resource); + } + + /** + * A replacement or a stub migration is undone through the cleanup record, and an in-place update from the tag + * snapshot taken before it. The snapshot is spent only once the restore succeeded, so one that throws leaves it for + * ContinueUpdateRollback to retry. + */ + @Override + public boolean rollbackUpdate(StackResource resource) { + if (ReplacementCleanup.rollback(resource, this::delete)) { + return true; + } + JsonNode snapshot = CfnRollback.updateSnapshot(resource, SNAPSHOT_ATTR); + if (snapshot == null) { + return false; + } + restoreTags(snapshot); + resource.getAttributes().remove(SNAPSHOT_ATTR); + return true; + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + // A snapshot describes the update in flight; one an earlier update left behind is stale. + r.getAttributes().remove(SNAPSHOT_ATTR); + if (ctx.isUpdate()) { + ReplacementCleanup.endRollbackRetry(r); + } + Map attributesBefore = new HashMap<>(r.getAttributes()); + JsonNode template = new CfnPropertyTypes.HandlerReader(ctx.engine()).read(TYPE, props); + for (String readOnly : READ_ONLY) { + if (template.has(readOnly)) { + throw new AwsException("InvalidRequest", + readOnly + " is a ReadOnly property which cannot be specified in the template", 400); + } + } + Map tags = new LinkedHashMap<>(); + template.path("Tags").forEach(tag -> tags.put(tag.path("Key").asText(), tag.path("Value").asText())); + // A stack from before this type had a provisioner, or deployed while EMR on EKS was disabled, holds the + // dispatcher's stub, which names no virtual cluster: taking over its id is a create. + boolean stub = CfnResourceDispatcher.isStub(ctx.priorPhysicalId(), attributesBefore); + if (ctx.isUpdate() && !stub && !ctx.changes(TYPE, props).requiresReplacement()) { + updateTagsInPlace(r, ctx, tags); + } else { + ObjectNode request = MAPPER.createObjectNode(); + request.set("name", template.path("Name")); + request.set("containerProvider", CfnApiShapeConverter.convert(template.get("ContainerProvider"), + CfnApiShapeConverter.OMIT_NULL_PROPERTIES)); + request.put("clientToken", UUID.randomUUID().toString()); + if (!tags.isEmpty()) { + request.set("tags", MAPPER.valueToTree(tags)); + } + if (template.has("SecurityConfigurationId")) { + request.set("securityConfigurationId", template.get("SecurityConfigurationId")); + } + if (template.has("SessionEnabled")) { + request.set("sessionEnabled", template.get("SessionEnabled")); + } + ObjectNode created = service.createVirtualCluster(request); + publish(r, created.path("id").asText(), created.path("arn").asText()); + } + ReplacementCleanup.record(r, ctx, attributesBefore); + } + + /** + * The update AWS's handler makes for the one property that is not create-only: the tags, from the virtual cluster + * the prior physical id names, which has to be running. They are snapshotted first, so a later resource's failure + * puts them back, and a failure here puts them back, once their reconcile began, before it propagates. + */ + private void updateTagsInPlace(StackResource r, ProvisionContext ctx, Map tags) { + String id = ctx.priorPhysicalId(); + JsonNode cluster = liveCluster(id); + String arn = cluster.path("arn").asText(); + ObjectNode snapshot = MAPPER.createObjectNode(); + snapshot.put("arn", arn); + snapshot.set("tags", cluster.path("tags").isObject() ? cluster.get("tags") : MAPPER.createObjectNode()); + publish(r, id, arn); + r.getAttributes().put(SNAPSHOT_ATTR, snapshot.toString()); + AtomicBoolean tagsTouched = new AtomicBoolean(); + CfnRollback.guarded(r, ctx, false, () -> { }, () -> { + if (tagsTouched.get()) { + restoreTags(snapshot); + } + }, () -> { + tagsTouched.set(true); + reconcileTags(arn, tags); + }); + } + + /** The virtual cluster {@code id}, failing as the handler's check of it does when it is terminated or gone. */ + private JsonNode liveCluster(String id) { + AwsException notFound = new AwsException("NotFound", + "Resource of type '" + TYPE + "' with identifier '" + id + "' was not found.", 404); + JsonNode cluster; + try { + cluster = service.describeVirtualCluster(id).path("virtualCluster"); + } catch (AwsException e) { + if ("ResourceNotFoundException".equals(e.getErrorCode())) { + throw notFound; + } + throw e; + } + if ("TERMINATED".equals(cluster.path("state").asText())) { + throw notFound; + } + return cluster; + } + + private void restoreTags(JsonNode snapshot) { + Map tags = new LinkedHashMap<>(); + snapshot.path("tags").properties().forEach(tag -> tags.put(tag.getKey(), tag.getValue().asText())); + reconcileTags(snapshot.path("arn").asText(), tags); + } + + /** Drives the virtual cluster's tags to {@code desired}, removing every other but an {@code aws:} one. */ + private void reconcileTags(String arn, Map desired) { + List held = service.listTags(arn).keySet().stream() + .filter(key -> !key.regionMatches(true, 0, SYSTEM_TAG_PREFIX, 0, SYSTEM_TAG_PREFIX.length())) + .toList(); + CfnRollback.reconcileTags(held, desired, dropped -> service.untagResource(arn, dropped), + added -> service.tagResource(arn, added)); + } + + private static void publish(StackResource r, String id, String arn) { + r.setPhysicalId(id); + r.getAttributes().put("Id", id); + r.getAttributes().put("Arn", arn); + } + + /** + * Deletes the virtual cluster; one that is gone is taken as deleted, and one already terminated stays as it is, as + * DeleteVirtualCluster leaves it. + */ + @Override + public void delete(String resourceType, String physicalId, String region) { + CfnDeletes.safeDelete("EMR on EKS virtual cluster", physicalId, () -> { + service.describeVirtualCluster(physicalId); + service.deleteVirtualCluster(physicalId); + }, "ResourceNotFoundException"); + } +} diff --git a/src/main/resources/aws/cfn-property-types.json b/src/main/resources/aws/cfn-property-types.json index 434cfd697b..4d57fbde96 100644 --- a/src/main/resources/aws/cfn-property-types.json +++ b/src/main/resources/aws/cfn-property-types.json @@ -12,6 +12,7 @@ "AWS::EC2::LaunchTemplate": "AWS::EC2::LaunchTemplate", "AWS::ECS::TaskDefinition": "AWS::ECS::TaskDefinition", "AWS::EKS::Cluster": "AWS::EKS::Cluster", + "AWS::EMRContainers::VirtualCluster": "AWS::EMRContainers::VirtualCluster", "AWS::EMRServerless::Application": "AWS::EMRServerless::Application", "AWS::Events::Rule": "AWS::Events::Rule", "AWS::Lambda::Function": "AWS::Lambda::Function", @@ -1950,6 +1951,97 @@ "Enabled": "Boolean" } }, + "AWS::EMRContainers::VirtualCluster": { + "type": "structure", + "members": { + "Arn": "String", + "ContainerProvider": "AWS::EMRContainers::VirtualCluster/ContainerProvider", + "Id": "AWS::EMRContainers::VirtualCluster.Id", + "Name": "AWS::EMRContainers::VirtualCluster.Name", + "Tags": "AWS::EMRContainers::VirtualCluster.Tags", + "SecurityConfigurationId": "AWS::EMRContainers::VirtualCluster.SecurityConfigurationId", + "SessionEnabled": "Boolean" + }, + "required": [ + "Name", + "ContainerProvider" + ] + }, + "AWS::EMRContainers::VirtualCluster.Id": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "AWS::EMRContainers::VirtualCluster.Name": { + "type": "string", + "minLength": 1, + "maxLength": 64, + "pattern": "[\\.\\-_/#A-Za-z0-9]+" + }, + "AWS::EMRContainers::VirtualCluster.SecurityConfigurationId": { + "type": "string", + "minLength": 1, + "maxLength": 64, + "pattern": "[0-9a-z]+" + }, + "AWS::EMRContainers::VirtualCluster.Tags": { + "type": "list", + "member": "AWS::EMRContainers::VirtualCluster/Tag" + }, + "AWS::EMRContainers::VirtualCluster/ContainerInfo": { + "type": "structure", + "members": { + "EksInfo": "AWS::EMRContainers::VirtualCluster/EksInfo" + }, + "required": [ + "EksInfo" + ] + }, + "AWS::EMRContainers::VirtualCluster/ContainerProvider": { + "type": "structure", + "members": { + "Type": "String", + "Id": "AWS::EMRContainers::VirtualCluster/ContainerProvider.Id", + "Info": "AWS::EMRContainers::VirtualCluster/ContainerInfo" + }, + "required": [ + "Type", + "Id", + "Info" + ] + }, + "AWS::EMRContainers::VirtualCluster/ContainerProvider.Id": { + "type": "string", + "minLength": 1, + "maxLength": 100, + "pattern": "^[0-9A-Za-z][A-Za-z0-9\\-_]*" + }, + "AWS::EMRContainers::VirtualCluster/EksInfo": { + "type": "structure", + "members": { + "Namespace": "AWS::EMRContainers::VirtualCluster/EksInfo.Namespace" + }, + "required": [ + "Namespace" + ] + }, + "AWS::EMRContainers::VirtualCluster/EksInfo.Namespace": { + "type": "string", + "minLength": 1, + "maxLength": 63, + "pattern": "[a-z0-9]([-a-z0-9]*[a-z0-9])?" + }, + "AWS::EMRContainers::VirtualCluster/Tag": { + "type": "structure", + "members": { + "Key": "String", + "Value": "String" + }, + "required": [ + "Value", + "Key" + ] + }, "AWS::EMRServerless::Application": { "type": "structure", "members": { diff --git a/src/main/resources/cloudformation/create-only-properties.json b/src/main/resources/cloudformation/create-only-properties.json index 53704904d0..513779b904 100644 --- a/src/main/resources/cloudformation/create-only-properties.json +++ b/src/main/resources/cloudformation/create-only-properties.json @@ -528,6 +528,12 @@ "AmiType", "Subnets" ], + "AWS::EMRContainers::VirtualCluster": [ + "ContainerProvider", + "Name", + "SecurityConfigurationId", + "SessionEnabled" + ], "AWS::EMRServerless::Application": [ "Name", "Type" diff --git a/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java index 66d021a952..7766c1af8f 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java @@ -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.EmrContainersCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.EmrServerlessCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.EventsArchiveCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.EventsCfnProvisioner; @@ -154,6 +155,7 @@ 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.emrcontainers.EmrContainersService; import io.floci.aws.services.emrserverless.EmrServerlessJobRunService; import io.floci.aws.services.emrserverless.EmrServerlessService; import io.floci.aws.services.eventbridge.EventBridgeService; @@ -280,6 +282,7 @@ final class CfnProvisionerFixture { private CloudTrailService cloudTrailService; private SchedulerService schedulerService; private CodeDeployService codeDeployService; + private EmrContainersService emrContainersService; private EmrServerlessService emrServerlessService; private EmrServerlessJobRunService emrServerlessJobRunService; private TransferService transferService; @@ -568,6 +571,9 @@ final class CfnProvisionerFixture { if (codeDeployService != null) { discovered.add(new CodeDeployCfnProvisioner(codeDeployService)); } + if (emrContainersService != null) { + discovered.add(new EmrContainersCfnProvisioner(emrContainersService)); + } if (emrServerlessService != null && emrServerlessJobRunService != null) { discovered.add(new EmrServerlessCfnProvisioner(emrServerlessService, emrServerlessJobRunService)); } @@ -801,6 +807,11 @@ final class CfnProvisionerFixture { return this; } + public Builder emrContainers(EmrContainersService v) { + this.emrContainersService = v; + return this; + } + public Builder emrServerless(EmrServerlessService v) { this.emrServerlessService = v; return this; diff --git a/src/test/java/io/floci/aws/services/cloudformation/EmrContainersVirtualClusterCfnIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/EmrContainersVirtualClusterCfnIntegrationTest.java new file mode 100644 index 0000000000..9dc39a4b5b --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/EmrContainersVirtualClusterCfnIntegrationTest.java @@ -0,0 +1,102 @@ +package io.floci.aws.services.cloudformation; + +import io.floci.aws.testing.CfnStackWaits; +import io.floci.aws.testing.CfnTestStack; +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 io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.aMapWithSize; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * Provisions {@code AWS::EMRContainers::VirtualCluster} through a stack and reads the virtual cluster back through + * EMR on EKS: {@code Ref} and {@code Fn::GetAtt} name it, a tag change updates it in place, a later resource's failure + * puts the tag back, a new namespace replaces it, and deleting the stack terminates it. + */ +@QuarkusTest +class EmrContainersVirtualClusterCfnIntegrationTest { + + private static final String EMR_CONTAINERS_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/emr-containers/aws4_request"; + + @RegisterExtension + final CfnTestStack stack = new CfnTestStack("emr-containers-vc-cfn-it"); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void createRetagRollBackReplaceAndDeleteAVirtualCluster() { + Stack created = stack.create(template("spark", "v1", false)); + String id = output(created, "Ref"); + assertEquals(id, output(created, "Id")); + assertEquals("arn:aws:emr-containers:us-east-1:000000000000:/virtualclusters/" + id, output(created, "Arn")); + describe(id).statusCode(200) + .body("virtualCluster.name", equalTo("jobs")) + .body("virtualCluster.state", equalTo("RUNNING")) + .body("virtualCluster.containerProvider.id", equalTo("eks-cfn")) + .body("virtualCluster.containerProvider.info.eksInfo.namespace", equalTo("spark")) + .body("virtualCluster.tags", aMapWithSize(1)) + .body("virtualCluster.tags.stage", equalTo("v1")); + + Stack retagged = stack.update(template("spark", "v2", false), "UPDATE_COMPLETE"); + assertEquals(id, output(retagged, "Ref")); + describe(id).statusCode(200).body("virtualCluster.tags.stage", equalTo("v2")); + + stack.update(template("spark", "v3", true), "UPDATE_ROLLBACK_COMPLETE"); + describe(id).statusCode(200).body("virtualCluster.tags.stage", equalTo("v2")); + + // ContainerProvider is create-only: a new namespace replaces the virtual cluster, and the committed update + // terminates the old one. + Stack replaced = stack.update(template("etl", "v2", false), "UPDATE_COMPLETE"); + String replacement = output(replaced, "Ref"); + assertNotEquals(id, replacement); + describe(replacement).statusCode(200) + .body("virtualCluster.containerProvider.info.eksInfo.namespace", equalTo("etl")); + describe(id).statusCode(200).body("virtualCluster.state", equalTo("TERMINATED")); + + CfnStackWaits.deleteStack(stack.name()); + + describe(replacement).statusCode(200).body("virtualCluster.state", equalTo("TERMINATED")); + } + + private static String template(String namespace, String stage, boolean laterFails) { + return """ + { + "Resources": { + "Cluster": { + "Type": "AWS::EMRContainers::VirtualCluster", + "Properties": { + "Name": "jobs", + "ContainerProvider": {"Type": "EKS", "Id": "eks-cfn", "Info": {"EksInfo": {"Namespace": "%s"}}}, + "Tags": [{"Key": "stage", "Value": "%s"}] + } + }%s + }, + "Outputs": { + "Ref": {"Value": {"Ref": "Cluster"}}, + "Id": {"Value": {"Fn::GetAtt": ["Cluster", "Id"]}}, + "Arn": {"Value": {"Fn::GetAtt": ["Cluster", "Arn"]}} + } + } + """.formatted(namespace, stage, laterFails ? CfnStackWaits.failingResourceAfter("Cluster") : ""); + } + + private static ValidatableResponse describe(String id) { + return given() + .header("Authorization", EMR_CONTAINERS_AUTH) + .contentType("application/json") + .when().get("/virtualclusters/" + id).then(); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrContainersCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrContainersCfnProvisionerTest.java new file mode 100644 index 0000000000..d8baefc541 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrContainersCfnProvisionerTest.java @@ -0,0 +1,237 @@ +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 com.fasterxml.jackson.databind.node.ObjectNode; +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.emrcontainers.EmrContainersService; +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 static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +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.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +/** {@code AWS::EMRContainers::VirtualCluster} in isolation, with the EMR on EKS service mocked. */ +class EmrContainersCfnProvisionerTest { + + private static final String ID = "vc0123456789abcdefghijklm"; + private static final String ARN = "arn:aws:emr-containers:us-east-1:000000000000:/virtualclusters/" + ID; + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String TEMPLATE = """ + {"Name": "spark", "ContainerProvider": {"Type": "EKS", "Id": "eks-1", + "Info": {"EksInfo": {"Namespace": "jobs"}}}, "Tags": [{"Key": "stage", "Value": "prod"}]} + """; + private static final String PRIOR = """ + {"Name": "spark", "ContainerProvider": {"Type": "EKS", "Id": "eks-1", + "Info": {"EksInfo": {"Namespace": "jobs"}}}, "Tags": [{"Key": "team", "Value": "data"}]} + """; + + private final EmrContainersService service = mock(EmrContainersService.class); + private final EmrContainersCfnProvisioner provisioner = new EmrContainersCfnProvisioner(service); + + 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("Cluster"); + r.setResourceType("AWS::EMRContainers::VirtualCluster"); + r.setAttributes(new HashMap<>()); + return r; + } + + private static StackResource provisioned() { + StackResource r = resource(); + r.setPhysicalId(ID); + r.getAttributes().put("Id", ID); + r.getAttributes().put("Arn", ARN); + return r; + } + + 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 tags(String... keysAndValues) { + Map tags = new LinkedHashMap<>(); + for (int i = 0; i < keysAndValues.length; i += 2) { + tags.put(keysAndValues[i], keysAndValues[i + 1]); + } + return tags; + } + + private void stubCluster(String state, Map tags) { + ObjectNode cluster = MAPPER.createObjectNode().put("id", ID).put("arn", ARN).put("state", state); + cluster.set("tags", MAPPER.valueToTree(tags)); + ObjectNode described = MAPPER.createObjectNode(); + described.set("virtualCluster", cluster); + when(service.describeVirtualCluster(ID)).thenReturn(described); + } + + @Test + void createsTheVirtualClusterWithTheTemplateInTheApiShape() { + when(service.createVirtualCluster(any())).thenReturn( + MAPPER.createObjectNode().put("id", ID).put("name", "spark").put("arn", ARN)); + StackResource r = resource(); + + provisioner.provision(r, json(""" + {"Name": "spark", "ContainerProvider": {"Type": "EKS", "Id": "eks-1", + "Info": {"EksInfo": {"Namespace": "jobs"}}}, "SecurityConfigurationId": "abc123", + "SessionEnabled": "true", "Tags": [{"Key": "stage", "Value": "prod"}]} + """), ctx(null, null)); + + ArgumentCaptor created = ArgumentCaptor.forClass(ObjectNode.class); + verify(service).createVirtualCluster(created.capture()); + ObjectNode request = created.getValue(); + assertFalse(request.path("clientToken").asText().isBlank()); + request.remove("clientToken"); + assertEquals(json(""" + {"name": "spark", "containerProvider": {"type": "EKS", "id": "eks-1", + "info": {"eksInfo": {"namespace": "jobs"}}}, "tags": {"stage": "prod"}, + "securityConfigurationId": "abc123", "sessionEnabled": true} + """), request); + assertEquals(ID, r.getPhysicalId()); + assertEquals(ID, r.getAttributes().get("Id")); + assertEquals(ARN, r.getAttributes().get("Arn")); + } + + @Test + void aTemplateTheHandlerRefusesFailsBeforeAnyCall() { + AwsException missing = assertThrows(AwsException.class, + () -> provisioner.provision(resource(), json("{\"Name\": \"spark\"}"), ctx(null, null))); + ObjectNode withArn = (ObjectNode) json(TEMPLATE); + withArn.put("Arn", ARN); + AwsException readOnly = assertThrows(AwsException.class, + () -> provisioner.provision(resource(), withArn, ctx(null, null))); + + assertEquals("Model validation failed (#: required key [ContainerProvider] not found)", missing.getMessage()); + assertEquals("Arn is a ReadOnly property which cannot be specified in the template", readOnly.getMessage()); + verifyNoInteractions(service); + } + + @Test + void anUpdateDrivesTheTagsToTheTemplatesKeepingAnAwsOne() { + stubCluster("RUNNING", tags("team", "data")); + when(service.listTags(ARN)).thenReturn(tags("team", "data", "aws:cloudformation:stack-name", "my-stack")); + StackResource r = provisioned(); + + provisioner.provision(r, json(TEMPLATE), ctx(ID, PRIOR)); + + verify(service).untagResource(ARN, List.of("team")); + verify(service).tagResource(ARN, Map.of("stage", "prod")); + verify(service, never()).createVirtualCluster(any()); + assertEquals(ID, r.getPhysicalId()); + assertTrue(r.getAttributes().containsKey(EmrContainersCfnProvisioner.SNAPSHOT_ATTR)); + } + + @Test + void aRollbackPutsBackTheTagsTheUpdateChanged() { + stubCluster("RUNNING", tags("team", "data")); + when(service.listTags(ARN)).thenReturn(tags("team", "data"), tags("stage", "prod")); + StackResource r = provisioned(); + provisioner.provision(r, json(TEMPLATE), ctx(ID, PRIOR)); + + assertTrue(provisioner.rollbackUpdate(r)); + + verify(service).untagResource(ARN, List.of("stage")); + verify(service).tagResource(ARN, Map.of("team", "data")); + assertFalse(r.getAttributes().containsKey(EmrContainersCfnProvisioner.SNAPSHOT_ATTR)); + } + + @Test + void aTagFailurePutsTheTagsBackBeforeItPropagates() { + stubCluster("RUNNING", tags("team", "data")); + when(service.listTags(ARN)).thenReturn(tags("team", "data"), tags()); + AwsException tagging = new AwsException("ValidationException", "tagging", 400); + doThrow(tagging).doNothing().when(service).tagResource(any(), any()); + StackResource r = provisioned(); + + AwsException thrown = assertThrows(AwsException.class, + () -> provisioner.provision(r, json(TEMPLATE), ctx(ID, PRIOR))); + + assertEquals(tagging, thrown); + verify(service).tagResource(ARN, Map.of("team", "data")); + assertFalse(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)); + } + + @Test + void anUpdateOfAVirtualClusterThatIsTerminatedOrGoneFailsAsTheHandlerDoes() { + stubCluster("TERMINATED", tags()); + AwsException terminated = assertThrows(AwsException.class, + () -> provisioner.provision(provisioned(), json(TEMPLATE), ctx(ID, PRIOR))); + when(service.describeVirtualCluster(ID)) + .thenThrow(new AwsException("ResourceNotFoundException", "Virtual cluster doesn't exist.", 404)); + AwsException gone = assertThrows(AwsException.class, + () -> provisioner.provision(provisioned(), json(TEMPLATE), ctx(ID, PRIOR))); + + String message = "Resource of type 'AWS::EMRContainers::VirtualCluster' with identifier '" + ID + + "' was not found."; + assertEquals(message, terminated.getMessage()); + assertEquals(message, gone.getMessage()); + verify(service, never()).tagResource(any(), any()); + } + + @Test + void aNewNamespaceReplacesTheVirtualClusterAndLeavesTheOldOneForTheCleanup() { + when(service.createVirtualCluster(any())).thenReturn(MAPPER.createObjectNode().put("id", "vcnew") + .put("name", "spark").put("arn", ARN.replace(ID, "vcnew"))); + StackResource r = provisioned(); + + provisioner.provision(r, json(TEMPLATE.replace("\"jobs\"", "\"etl\"")), ctx(ID, PRIOR)); + + assertEquals("vcnew", r.getPhysicalId()); + assertTrue(provisioner.hasReplacementUpdate(r)); + assertEquals(ID, provisioner.updateCleanupPhysicalId(r)); + verify(service, never()).describeVirtualCluster(any()); + } + + @Test + void anUndoThatFailedLeavesItsSnapshotForContinueUpdateRollback() { + StackResource previous = provisioned(); + StackResource attempted = provisioned(); + attempted.getAttributes().put(EmrContainersCfnProvisioner.SNAPSHOT_ATTR, "{}"); + attempted.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, "Could not restore"); + + provisioner.mergeFailedUpdateResourceTracking(previous, attempted); + + assertEquals("{}", previous.getAttributes().get(EmrContainersCfnProvisioner.SNAPSHOT_ATTR)); + } + + @Test + void theDeleteTerminatesTheVirtualClusterAndTakesAGoneOneAsDeleted() { + stubCluster("RUNNING", tags()); + when(service.describeVirtualCluster("vcgone")) + .thenThrow(new AwsException("ResourceNotFoundException", "Virtual cluster doesn't exist.", 404)); + + provisioner.delete("AWS::EMRContainers::VirtualCluster", ID, "us-east-1"); + provisioner.delete("AWS::EMRContainers::VirtualCluster", "vcgone", "us-east-1"); + + verify(service).deleteVirtualCluster(ID); + verify(service, never()).deleteVirtualCluster("vcgone"); + } +} diff --git a/src/test/resources/cloudformation/schema-surface.tsv b/src/test/resources/cloudformation/schema-surface.tsv index 00d8b06729..107efd8d19 100644 --- a/src/test/resources/cloudformation/schema-surface.tsv +++ b/src/test/resources/cloudformation/schema-surface.tsv @@ -108,6 +108,7 @@ AWS::EFS::FileSystem Arn,FileSystemId AvailabilityZoneName,BackupPolicy,BypassPo AWS::EFS::MountTarget Id FileSystemId,IpAddress,IpAddressType,Ipv6Address,SecurityGroups,SubnetId AWS::EKS::Cluster Arn,CertificateAuthorityData,ClusterSecurityGroupId,EncryptionConfigKeyArn,Endpoint,Id,OpenIdConnectIssuerUrl AccessConfig,ActiveCertificateAuthorityId,BootstrapSelfManagedAddons,CertificateAuthority,ComputeConfig,ControlPlaneScalingConfig,DeletionProtection,EncryptionConfig,Force,KubeApiServerConfig,KubeControllerManagerConfig,KubeSchedulerConfig,KubernetesNetworkConfig,Logging,Name,OutpostConfig,RemoteNetworkConfig,ResourcesVpcConfig,RoleArn,RollbackConfig,StorageConfig,Tags,UpgradePolicy,Version,ZonalShiftConfig AWS::EKS::Nodegroup Arn,Id AmiType,CapacityType,ClusterName,DiskSize,ForceUpdateEnabled,InstanceTypes,Labels,LaunchTemplate,NodeRepairConfig,NodeRole,NodegroupName,ReleaseVersion,RemoteAccess,ScalingConfig,Subnets,Tags,Taints,UpdateConfig,Version,WarmPoolConfig +AWS::EMRContainers::VirtualCluster Arn,Id ContainerProvider,Name,SecurityConfigurationId,SessionEnabled,Tags AWS::EMRServerless::Application ApplicationId,Arn Architecture,AutoStartConfiguration,AutoStopConfiguration,IdentityCenterConfiguration,ImageConfiguration,InitialCapacity,InteractiveConfiguration,MaximumCapacity,MonitoringConfiguration,Name,NetworkConfiguration,ReleaseLabel,RuntimeConfiguration,SchedulerConfiguration,Tags,Type,WorkerTypeSpecifications AWS::ElastiCache::CacheCluster ConfigurationEndpoint,RedisEndpoint AZMode,AutoMinorVersionUpgrade,CacheNodeType,CacheParameterGroupName,CacheSubnetGroupName,ClusterName,Engine,EngineVersion,IpDiscovery,LogDeliveryConfigurations,NetworkType,NotificationTopicArn,NumCacheNodes,Port,PreferredAvailabilityZone,PreferredAvailabilityZones,PreferredMaintenanceWindow,SnapshotArns,SnapshotName,SnapshotRetentionLimit,SnapshotWindow,Tags,TransitEncryptionEnabled,VpcSecurityGroupIds AWS::ElastiCache::ReplicationGroup ConfigurationEndPoint,EffectiveDurability,PrimaryEndPoint,ReadEndPoint,ReaderEndPoint AtRestEncryptionEnabled,AuthToken,AutoMinorVersionUpgrade,AutomaticFailoverEnabled,CacheNodeType,CacheParameterGroupName,CacheSubnetGroupName,ClusterMode,DataTieringEnabled,Durability,Engine,EngineVersion,GlobalReplicationGroupId,IpDiscovery,KmsKeyId,LogDeliveryConfigurations,MultiAZEnabled,NetworkType,NodeGroupConfiguration,NotificationTopicArn,NumCacheClusters,NumNodeGroups,Port,PreferredCacheClusterAZs,PreferredMaintenanceWindow,PrimaryClusterId,ReplicasPerNodeGroup,ReplicationGroupDescription,ReplicationGroupId,SecurityGroupIds,SnapshotArns,SnapshotName,SnapshotRetentionLimit,SnapshotWindow,SnapshottingClusterId,Tags,TransitEncryptionEnabled,TransitEncryptionMode,UserGroupIds diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 5f33ee3c62..0bba27a23f 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -109,6 +109,7 @@ AWS::EFS::FileSystem EfsCfnProvisioner AWS::EFS::MountTarget EfsCfnProvisioner AWS::EKS::Cluster EksCfnProvisioner AWS::EKS::Nodegroup EksCfnProvisioner +AWS::EMRContainers::VirtualCluster EmrContainersCfnProvisioner AWS::EMRServerless::Application EmrServerlessCfnProvisioner AWS::ElastiCache::CacheCluster ElastiCacheCfnProvisioner AWS::ElastiCache::ReplicationGroup ElastiCacheCfnProvisioner diff --git a/tools/aws/regen_cfn_property_types.py b/tools/aws/regen_cfn_property_types.py index 710a1ea25a..6561b25ac7 100644 --- a/tools/aws/regen_cfn_property_types.py +++ b/tools/aws/regen_cfn_property_types.py @@ -52,7 +52,7 @@ FETCH_TIMEOUT_SECONDS = 60 # The resource types whose provisioners read their properties through CfnPropertyTypes. RESOURCE_TYPES = ["AWS::AutoScaling::LaunchConfiguration", "AWS::DSQL::Cluster", "AWS::EC2::Instance", "AWS::EC2::LaunchTemplate", "AWS::ECS::TaskDefinition", "AWS::EKS::Cluster", - "AWS::EMRServerless::Application", "AWS::Events::Rule", + "AWS::EMRContainers::VirtualCluster", "AWS::EMRServerless::Application", "AWS::Events::Rule", "AWS::Lambda::Function", "AWS::Lambda::LayerVersion", "AWS::SES::ConfigurationSetEventDestination"] diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index b85f29d518..fbaa664bc1 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -27,6 +27,7 @@ order: - AWS::ECS - AWS::EFS - AWS::EKS + - AWS::EMRContainers - AWS::EMRServerless - AWS::RDS - AWS::DSQL @@ -157,6 +158,7 @@ service_labels: AWS::ECS: ECS AWS::EFS: EFS AWS::EKS: EKS + AWS::EMRContainers: EMR on EKS AWS::EMRServerless: EMR Serverless AWS::ElasticLoadBalancingV2: Elastic Load Balancing v2 AWS::Events: EventBridge @@ -230,6 +232,7 @@ notes: AWS::Transfer::User: 'management plane only; Ref returns the user ARN; Arn attribute supported; Policy and PosixProfile are not supported; a ServerId or UserName change replaces the user' AWS::EKS::Cluster: 'created with `Name`, `Version`, `RoleArn`, `Tags`, `EncryptionConfig`, `ResourcesVpcConfig`, `Logging`, `AccessConfig` and `KubernetesNetworkConfig.IpFamily` and `ServiceIpv4Cidr`, a replacement included; a change to `EncryptionConfig`, `IpFamily` or `ServiceIpv4Cidr` replaces the cluster with the new value applied; `ElasticLoadBalancing`, `ServiceIpv6Cidr` and `ResourcesVpcConfig.ControlPlaneEgressMode` are accepted and ignored; updated in place for `Tags`, keeping tags added outside the stack, for `Logging`, for `AccessConfig.AuthenticationMode` (a mode cannot be moved back, so a stack update that does so fails, and a stack rollback restores it) and for `ResourcesVpcConfig` endpoint access and `PublicAccessCidrs`; a change to `Name`, `RoleArn`, `EncryptionConfig`, `BootstrapSelfManagedAddons`, `OutpostConfig`, `AccessConfig.BootstrapClusterCreatorAdminPermissions`, `KubernetesNetworkConfig.IpFamily` or `KubernetesNetworkConfig.ServiceIpv4Cidr` replaces the cluster, as the registry marks them create-only, and deletes the old one once the update commits; a change to `Version` is accepted with a warning and not applied, as the emulator has no `UpdateClusterVersion`; a change to the subnets or security groups of `ResourcesVpcConfig` fails the resource, as the emulator''s `UpdateClusterConfig` does not change them' AWS::EKS::Nodegroup: 'created with `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets` and `Tags`; updated in place for `Tags`, keeping tags added outside the stack; a change to `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets`, `AmiType`, `CapacityType`, `DiskSize`, `InstanceTypes` or `RemoteAccess` replaces the nodegroup, as the registry marks them create-only, and deletes the old one once the update commits; `ScalingConfig`, `Labels`, `Taints`, `UpdateConfig`, `Version`, `ReleaseVersion`, `ForceUpdateEnabled`, `LaunchTemplate`, `NodeRepairConfig` and `WarmPoolConfig` are accepted and not applied, whether changed or dropped, with a warning, as the emulator cannot update a nodegroup in place' + AWS::EMRContainers::VirtualCluster: 'created with `Name`, `ContainerProvider`, `SecurityConfigurationId`, `SessionEnabled` and `Tags`; a template that sets the read-only `Arn` or `Id` is refused; updated in place for `Tags` alone, which end as the template lists them, any other but an `aws:` one removed; a change to any other property replaces the virtual cluster, as the registry marks them create-only, and terminates the old one once the update commits; an update of a virtual cluster that is terminated or gone fails' AWS::EMRServerless::Application: 'created with every property, `Name` and `Type` included; updated in place through `UpdateApplication` for the settings a template changes, a dropped setting kept as it is but for `InitialCapacity`, which is cleared, and for `Tags`, which end as the template lists them, any other removed; a change to `Name` or `Type` replaces the application and deletes the old one once the update commits; neither an update nor a delete stops a `STARTED` application, so one it refuses fails the resource, as on AWS' AWS::IAM::User: 'template `LoginProfile` and `PermissionsBoundary` are ignored; an API-created login profile is removed on delete' AWS::ApiGateway::Authorizer: 'created with `Name`, `Type`, `AuthorizerUri`, `IdentitySource`, `AuthorizerResultTtlInSeconds` and `ProviderARNs`; updated in place for those, keeping the id; a template that drops `AuthorizerResultTtlInSeconds`, `IdentitySource` or `ProviderARNs` restores the TTL of 300 and clears the identity source and the pools, a dropped `AuthorizerUri` keeps the current one, and dropping `IdentitySource` from a `TOKEN` or `COGNITO_USER_POOLS` authorizer fails the resource, as AWS requires it there; a change to `RestApiId` replaces the authorizer, as the registry marks it create-only, and deletes the old one once the update commits; `AuthorizerCredentials`, `AuthType` and `IdentityValidationExpression` are not stored'