diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 4f3b5eef24..10cd8c2c98 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -220,7 +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 | `Cluster` (created through `RunJobFlow`, once it is waiting or running, its master, core and task groups or fleets as `RunJobFlow`'s `InstanceGroups` or `InstanceFleets`; `AdditionalInfo`, `KerberosAttributes`, `OSReleaseLabel`, `EbsRootVolumeIops`, `EbsRootVolumeThroughput`, `PlacementGroupConfigs`, `LogEncryptionKmsKeyId` and `MonitoringConfiguration`, `Instances`' `Ec2SubnetIds`, additional security groups and `HadoopVersion` and a fleet's launch and resize specifications are accepted with a warning and not stored; task groups and fleets need unique names; a template that sets the read-only `Id` or `MasterPublicDNS` is refused; updated in place for `AutoTerminationPolicy`, `ManagedScalingPolicy`, `StepConcurrencyLevel`, `VisibleToAllUsers`, `Tags` (keeping tags added outside the stack), `TerminationProtected`, `UnhealthyNodeReplacement`, a core or task group's `InstanceCount` and `AutoScalingPolicy` and a core or task fleet's target capacities, a dropped one taking its default; any other change, within `Instances` included, replaces the cluster and terminates the old one once the update commits; a termination-protected cluster refuses the delete), `InstanceGroupConfig` (a `TASK` group, the one role the reference allows, added through `AddInstanceGroups`; `InstanceCount` and `AutoScalingPolicy` update in place, and a create-only change adds a new group; the delete removes its policy and shrinks it to nothing, as a group cannot be removed from its cluster), `InstanceFleetConfig` (a `TASK` fleet, the one type the reference allows, added through `AddInstanceFleet`; `TargetOnDemandCapacity` and `TargetSpotCapacity` update in place through `ModifyInstanceFleet`, a change to `InstanceTypeConfigs` or `ResizeSpecifications` is accepted with a warning and not applied, and a create-only change adds a new fleet; the delete shrinks the fleet to nothing, as a fleet cannot be removed from its cluster), `Step` (added through `AddJobFlowSteps`, `LogUri` and `EncryptionKeyArn` as its `StepMonitoringConfiguration`; every property is create-only, so a change adds a new step, and a step stays in its cluster's history when deleted, as the schema's delete handler calls nothing), `SecurityConfiguration` (created with `Name`, generated when the template gives none, and the `SecurityConfiguration` JSON, as an object or its text; both are create-only, so any change replaces it and deletes the old one once the update commits, and a change that keeps a template's own `Name` is refused, as for every custom-named resource), `Studio` (created with every property; a template that sets the read-only `Arn`, `StudioId` or `Url` is refused; updated in place through `UpdateStudio` for `Name`, `Description`, `SubnetIds` and `DefaultS3Location`, a dropped setting kept as it is, and for `Tags`, keeping tags added outside the stack; a change to `IdpAuthUrl` or `IdpRelayStateParameterName` is accepted with a warning and not applied, as no Studio API changes them; a rollback puts back the name, description, location and tags, but not subnets an update added, which `UpdateStudio` cannot take away; a change to a create-only property replaces the Studio and deletes the old one once the update commits), `StudioSessionMapping` (`Ref` is `StudioId|IdentityType|IdentityName`, the schema's primary identifier; `SessionPolicyArn` updates in place, and a change to any of the three others replaces the mapping) | +| EMR | `Cluster` (created through `RunJobFlow`, once it is waiting or running, its master, core and task groups or fleets as `RunJobFlow`'s `InstanceGroups` or `InstanceFleets`; `AdditionalInfo`, `KerberosAttributes`, `OSReleaseLabel`, `EbsRootVolumeIops`, `EbsRootVolumeThroughput`, `PlacementGroupConfigs`, `LogEncryptionKmsKeyId` and `MonitoringConfiguration`, `Instances`' `Ec2SubnetIds`, additional security groups and `HadoopVersion` are accepted with a warning and not stored; task groups and fleets need unique names; a template that sets the read-only `Id` or `MasterPublicDNS` is refused; updated in place for `AutoTerminationPolicy`, `ManagedScalingPolicy`, `StepConcurrencyLevel`, `VisibleToAllUsers`, `Tags` (keeping tags added outside the stack), `TerminationProtected`, `UnhealthyNodeReplacement`, a core or task group's `InstanceCount` and `AutoScalingPolicy` and a core or task fleet's target capacities, a dropped one taking its default; any other change, within `Instances` included, replaces the cluster and terminates the old one once the update commits; a termination-protected cluster refuses the delete), `InstanceGroupConfig` (a `TASK` group, the one role the reference allows, added through `AddInstanceGroups`; `InstanceCount` and `AutoScalingPolicy` update in place, and a create-only change adds a new group; the delete removes its policy and shrinks it to nothing, as a group cannot be removed from its cluster), `InstanceFleetConfig` (a `TASK` fleet, the one type the reference allows, added through `AddInstanceFleet`; `TargetOnDemandCapacity`, `TargetSpotCapacity`, `InstanceTypeConfigs` and `ResizeSpecifications` update in place through `ModifyInstanceFleet`, and a create-only change adds a new fleet; a rollback puts them back, but not an instance type the update added, which every later `ModifyInstanceFleet` must include, nor resize specifications where the fleet had none, which no request can clear, and dropped configs or resize specifications are kept for the same reason; the delete shrinks the fleet to nothing, as a fleet cannot be removed from its cluster), `Step` (added through `AddJobFlowSteps`, `LogUri` and `EncryptionKeyArn` as its `StepMonitoringConfiguration`; every property is create-only, so a change adds a new step, and a step stays in its cluster's history when deleted, as the schema's delete handler calls nothing), `SecurityConfiguration` (created with `Name`, generated when the template gives none, and the `SecurityConfiguration` JSON, as an object or its text; both are create-only, so any change replaces it and deletes the old one once the update commits, and a change that keeps a template's own `Name` is refused, as for every custom-named resource), `Studio` (created with every property; a template that sets the read-only `Arn`, `StudioId` or `Url` is refused; updated in place through `UpdateStudio` for `Name`, `Description`, `SubnetIds` and `DefaultS3Location`, a dropped setting kept as it is, and for `Tags`, keeping tags added outside the stack; a change to `IdpAuthUrl` or `IdpRelayStateParameterName` is accepted with a warning and not applied, as no Studio API changes them; a rollback puts back the name, description, location and tags, but not subnets an update added, which `UpdateStudio` cannot take away; a change to a create-only property replaces the Studio and deletes the old one once the update commits), `StudioSessionMapping` (`Ref` is `StudioId|IdentityType|IdentityName`, the schema's primary identifier; `SessionPolicyArn` updates in place, and a change to any of the three others replaces the mapping) | | 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` | diff --git a/docs/services/emr.md b/docs/services/emr.md index bc63ac5b83..7345ae7642 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -205,8 +205,16 @@ without its `InstanceType`, both required, is refused with the framework's `Vali neither bid price, the defaults the API reference gives, and its `EbsConfiguration` as one `EbsBlockDevice` per volume. The reference names no devices, so Floci names them `/dev/sdb`, `/dev/sdc` and on. A config attaching more than 25 volumes to an instance is refused with `ValidationException` "There is a limit of 25 volumes per instance.", the -Management Guide's own limit and sentence; AWS's error for it is not documented. `ModifyInstanceFleet` changes a -fleet's target capacities only; the `InstanceTypeConfigs` it takes are not applied. +Management Guide's own limit and sentence; AWS's error for it is not documented. A fleet keeps its +`LaunchSpecifications`, `ResizeSpecifications` and `Context`, which `ListInstanceFleets` gives back, and +`ModifyInstanceFleet` changes the target capacities, `ResizeSpecifications`, `InstanceTypeConfigs` and `Context` it +gives; Floci provisions nothing the specifications would steer, so they change no instance. The configs replace the +fleet's own, as the Management Guide's "Reconfiguring instance fleets" warns: "Not including fields can result in +overwriting specifications you declared at launch". They must name every instance type the fleet has, as "You must +include all instance types that are part of your instance fleet in the modify request"; one that leaves a type out is +refused with `InvalidRequestException`, AWS's error for it not being documented. Its configs are checked as +`AddInstanceFleet` checks them, and on both calls specifications that are not an object, or a `Context` that is not a +string, are refused with `SerializationException`, as every member of the wrong JSON type is. An instance group keeps its `EbsConfiguration` and `CustomAmiId`, from `RunJobFlow` or `AddInstanceGroups`, and `ListInstanceGroups` gives them back as its `EbsBlockDevices`, one per volume named as a fleet's are, its `EbsOptimized` and its `CustomAmiId`, under the same limit of 25 volumes per instance; its instances' EC2 descriptions diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisioner.java index 024393129e..8a1be7ba18 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisioner.java @@ -1,5 +1,6 @@ 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.ArrayNode; @@ -8,6 +9,7 @@ import io.floci.aws.core.common.AwsException; import io.floci.aws.services.cloudformation.model.StackResource; import io.floci.aws.services.emr.EmrHandler; import io.floci.aws.services.emr.EmrService; +import io.floci.aws.services.emr.EmrService.InstanceFleetModification; import io.floci.aws.services.emr.EmrService.InstanceGroupModification; import io.floci.aws.services.emr.model.EmrCluster; import io.floci.aws.services.emr.model.EmrInstanceFleet; @@ -109,8 +111,6 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner { /** The members of {@code Instances} Floci's RunJobFlow keeps nothing of, accepted with a warning. */ private static final List INSTANCES_NOT_STORED = List.of("Ec2SubnetIds", "AdditionalMasterSecurityGroups", "AdditionalSlaveSecurityGroups", "HadoopVersion"); - /** The members of an instance fleet Floci's RunJobFlow keeps nothing of. */ - private static final List FLEET_NOT_STORED = List.of("LaunchSpecifications", "ResizeSpecifications"); private static final String GROUPS = "groups"; private static final String FLEETS = "fleets"; private static final Duration READY_TIMEOUT = Duration.ofMinutes(15); @@ -298,7 +298,7 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner { } } - /** Warns of each property, or member of {@code Instances} or its fleets, RunJobFlow keeps nothing of. */ + /** Warns of each property, or member of {@code Instances}, RunJobFlow keeps nothing of. */ private static void warnNotStored(String logicalId, JsonNode template) { List ignored = new ArrayList<>(); for (String name : CLUSTER_NOT_STORED) { @@ -312,14 +312,6 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner { ignored.add("Instances." + name); } } - List fleets = new ArrayList<>(List.of(instances.path("MasterInstanceFleet"), - instances.path("CoreInstanceFleet"))); - instances.path("TaskInstanceFleets").forEach(fleets::add); - for (String name : FLEET_NOT_STORED) { - if (fleets.stream().anyMatch(fleet -> fleet.has(name))) { - ignored.add("an instance fleet's " + name); - } - } if (!ignored.isEmpty()) { LOG.warnv("EMR cluster {0}: {1} accepted and not stored", logicalId, String.join(", ", ignored)); } @@ -380,11 +372,9 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner { if (copy.has("Configurations")) { copy.set("Configurations", configurations(copy.get("Configurations"))); } - copy.path("InstanceTypeConfigs").forEach(type -> { - if (type instanceof ObjectNode typeConfig && typeConfig.has("Configurations")) { - typeConfig.set("Configurations", configurations(typeConfig.get("Configurations"))); - } - }); + if (copy.has("InstanceTypeConfigs")) { + copy.set("InstanceTypeConfigs", apiInstanceTypeConfigs(copy.get("InstanceTypeConfigs"))); + } into.add(copy); } @@ -807,10 +797,11 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner { } /** - * An instance fleet is added through AddInstanceFleet; its target capacities change in place through - * ModifyInstanceFleet, and any create-only change adds a new fleet. Floci's ModifyInstanceFleet changes the - * capacities alone, so a change to {@code InstanceTypeConfigs} or {@code ResizeSpecifications} is accepted with a - * warning and not applied. A rollback puts back the capacities it had changed. + * An instance fleet is added through AddInstanceFleet; its target capacities, {@code InstanceTypeConfigs} and + * {@code ResizeSpecifications} change in place through ModifyInstanceFleet, and any create-only change adds a new + * fleet. A rollback puts back what the update had changed, but not what ModifyInstanceFleet cannot take away: an + * instance type the update added, which every later request must include, and resize specifications where the + * fleet had none. Dropped resize specifications are kept for the same reason. */ private void provisionInstanceFleet(StackResource r, JsonNode props, ProvisionContext ctx, boolean stub) { JsonNode template = new CfnPropertyTypes.HandlerReader(ctx.engine()).read(INSTANCE_FLEET, props); @@ -824,28 +815,39 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner { EmrInstanceFleet live = emrService.listInstanceFleets(clusterId).stream() .filter(fleet -> id.equals(fleet.getId())).findFirst() .orElseThrow(() -> notFound(INSTANCE_FLEET, id)); + ArrayNode configs = changed(changes, "InstanceTypeConfigs") && template.has("InstanceTypeConfigs") + ? apiInstanceTypeConfigs(template.get("InstanceTypeConfigs")) : null; + JsonNode resize = changed(changes, "ResizeSpecifications") ? template.get("ResizeSpecifications") : null; for (String name : List.of("InstanceTypeConfigs", "ResizeSpecifications")) { - PropertyChanges.Kind kind = changes.kindOf(name); - if (kind != null && kind != PropertyChanges.Kind.UNCHANGED) { - LOG.warnv("EMR instance fleet {0}: {1} is not applied, as ModifyInstanceFleet changes the " - + "target capacities alone", id, name); + if (changed(changes, name) && !template.has(name)) { + LOG.warnv("EMR instance fleet {0}: the dropped {1} are kept, as ModifyInstanceFleet cannot take " + + "them away", id, name); } } int onDemand = template.path("TargetOnDemandCapacity").asInt(0); int spot = template.path("TargetSpotCapacity").asInt(0); + // Checked before anything changes, as ModifyInstanceFleet checks its request. + InstanceFleetModification modification = fleetModification(onDemand, spot, configs, resize); ObjectNode snapshot = MAPPER.createObjectNode(); snapshot.put("clusterId", clusterId); snapshot.put("fleetId", id); snapshot.put("region", ctx.region()); snapshot.put("onDemand", live.getTargetOnDemandCapacity()); snapshot.put("spot", live.getTargetSpotCapacity()); + if (configs != null) { + snapshot.set("configs", configsOf(live)); + } + if (resize != null && live.getResizeSpecifications() != null) { + snapshot.set("resize", rawJson(live.getResizeSpecifications(), null)); + } publishCapacity(r, id, clusterId); r.getAttributes().put("InstanceFleetId", id); r.getAttributes().put(CAPACITY_SNAPSHOT_ATTR, snapshot.toString()); AtomicBoolean changed = new AtomicBoolean(); CfnRollback.guarded(r, ctx, false, () -> { }, () -> restoreCapacity(snapshot, changed.get(), false), () -> { - if (onDemand != live.getTargetOnDemandCapacity() || spot != live.getTargetSpotCapacity()) { - emrService.modifyInstanceFleet(clusterId, id, onDemand, spot); + if (onDemand != live.getTargetOnDemandCapacity() || spot != live.getTargetSpotCapacity() + || configs != null || resize != null) { + emrService.modifyInstanceFleet(clusterId, id, modification); changed.set(true); } }); @@ -857,16 +859,87 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner { fleet.set(name, template.get(name).deepCopy()); } } - fleet.path("InstanceTypeConfigs").forEach(type -> { - if (type instanceof ObjectNode typeConfig && typeConfig.has("Configurations")) { - typeConfig.set("Configurations", configurations(typeConfig.get("Configurations"))); - } - }); + if (fleet.has("InstanceTypeConfigs")) { + fleet.set("InstanceTypeConfigs", apiInstanceTypeConfigs(fleet.get("InstanceTypeConfigs"))); + } String id = emrService.addInstanceFleet(clusterId, emrHandler.instanceFleetFrom(fleet)); publishCapacity(r, id, clusterId); r.getAttributes().put("InstanceFleetId", id); } + private static boolean changed(PropertyChanges changes, String name) { + PropertyChanges.Kind kind = changes.kindOf(name); + return kind != null && kind != PropertyChanges.Kind.UNCHANGED; + } + + /** A template's InstanceTypeConfigs as the API takes them: their ConfigurationProperties as Properties. */ + private static ArrayNode apiInstanceTypeConfigs(JsonNode templateConfigs) { + ArrayNode configs = MAPPER.createArrayNode(); + for (JsonNode type : templateConfigs) { + JsonNode config = type.deepCopy(); + if (config instanceof ObjectNode typeConfig && typeConfig.has("Configurations")) { + typeConfig.set("Configurations", configurations(typeConfig.get("Configurations"))); + } + configs.add(config); + } + return configs; + } + + /** The ModifyInstanceFleet change, read and checked as ModifyInstanceFleet reads its request. */ + private static InstanceFleetModification fleetModification(int onDemand, int spot, ArrayNode configs, + JsonNode resize) { + ObjectNode request = MAPPER.createObjectNode(); + request.put("TargetOnDemandCapacity", onDemand); + request.put("TargetSpotCapacity", spot); + if (configs != null) { + request.set("InstanceTypeConfigs", configs); + } + if (resize != null) { + request.set("ResizeSpecifications", resize); + } + return EmrHandler.instanceFleetModificationFrom(request); + } + + /** + * A fleet's InstanceTypeConfigs as stored, or, for one stored with its instance types alone, a config naming each, + * so a rollback puts back what the fleet had rather than keeping the update's. + */ + private static ArrayNode configsOf(EmrInstanceFleet fleet) { + if (fleet.getInstanceTypeConfigs() != null) { + return (ArrayNode) rawJson(fleet.getInstanceTypeConfigs(), null); + } + ArrayNode configs = MAPPER.createArrayNode(); + fleet.getInstanceTypes().forEach(type -> configs.addObject().put("InstanceType", type)); + return configs; + } + + /** Adds to {@code configs} the live fleet's configs of the types they lack: ModifyInstanceFleet needs them all. */ + private void keepAddedInstanceTypes(String clusterId, String fleetId, ArrayNode configs) { + List named = new ArrayList<>(); + configs.forEach(config -> named.add(config.path("InstanceType").asText())); + for (EmrInstanceFleet fleet : emrService.listInstanceFleets(clusterId)) { + if (fleetId.equals(fleet.getId())) { + List added = EmrService.instanceTypesLeftOut(fleet.getInstanceTypes(), named); + for (JsonNode config : configsOf(fleet)) { + if (added.contains(config.path("InstanceType").asText())) { + configs.add(config); + } + } + } + } + } + + private static JsonNode rawJson(String text, JsonNode none) { + if (text == null) { + return none; + } + try { + return MAPPER.readTree(text); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Unreadable stored EMR JSON", e); + } + } + private void applyGroupPolicy(String clusterId, String groupId, JsonNode policy) { if (policy == null) { emrService.removeAutoScalingPolicy(clusterId, groupId); @@ -880,8 +953,13 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner { String clusterId = snapshot.path("clusterId").asText(); if (snapshot.has("fleetId")) { if (first) { - emrService.modifyInstanceFleet(clusterId, snapshot.path("fleetId").asText(), - snapshot.path("onDemand").asInt(), snapshot.path("spot").asInt()); + String fleetId = snapshot.path("fleetId").asText(); + ArrayNode configs = snapshot.get("configs") instanceof ArrayNode prior ? prior.deepCopy() : null; + if (configs != null) { + keepAddedInstanceTypes(clusterId, fleetId, configs); + } + emrService.modifyInstanceFleet(clusterId, fleetId, fleetModification(snapshot.path("onDemand").asInt(), + snapshot.path("spot").asInt(), configs, snapshot.get("resize"))); } return; } diff --git a/src/main/java/io/floci/aws/services/emr/EmrHandler.java b/src/main/java/io/floci/aws/services/emr/EmrHandler.java index 971107b4ba..3c28f798fd 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrHandler.java +++ b/src/main/java/io/floci/aws/services/emr/EmrHandler.java @@ -1364,12 +1364,38 @@ public class EmrHandler { private Response handleModifyInstanceFleet(JsonNode request) { JsonNode fleet = request.path("InstanceFleet"); + service.modifyInstanceFleet(text(request, "ClusterId"), fleet.path("InstanceFleetId").asText(null), + instanceFleetModificationFrom(fleet)); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + /** + * The change a ModifyInstanceFleet request's {@code InstanceFleet} describes, read and checked as + * ModifyInstanceFleet reads it, for this handler and for CloudFormation's {@code AWS::EMR::InstanceFleetConfig}: + * its configs' required InstanceType and their volume limit, as AddInstanceFleet checks them, and its members' + * JSON types. + */ + public static EmrService.InstanceFleetModification instanceFleetModificationFrom(JsonNode fleet) { JsonNode onDemand = fleet.path("TargetOnDemandCapacity"); JsonNode spot = fleet.path("TargetSpotCapacity"); - service.modifyInstanceFleet(text(request, "ClusterId"), fleet.path("InstanceFleetId").asText(null), + JsonNode configs = fleet.path("InstanceTypeConfigs"); + List instanceTypes = null; + if (!configs.isMissingNode() && !configs.isNull()) { + if (!configs.isArray()) { + throw malformed("InstanceTypeConfigs must be a list"); + } + List violations = new ArrayList<>(); + instanceTypes = instanceTypes(configs, "instanceFleet", violations); + if (!violations.isEmpty()) { + throw SmithyValidationErrors.validationException(violations); + } + requireFleetEbsVolumeLimit(fleet); + } + return new EmrService.InstanceFleetModification( onDemand.isMissingNode() || onDemand.isNull() ? null : onDemand.asInt(), - spot.isMissingNode() || spot.isNull() ? null : spot.asInt()); - return Response.ok(objectMapper.createObjectNode()).build(); + spot.isMissingNode() || spot.isNull() ? null : spot.asInt(), + object(fleet, "ResizeSpecifications"), instanceTypes == null ? null : configs.toString(), + instanceTypes, string(fleet, "Context")); } /** Each BootstrapActionConfig given to RunJobFlow, as the Command shape: Name, ScriptPath and Args. */ @@ -1681,6 +1707,15 @@ public class EmrHandler { node.put("ProvisionedSpotCapacity", f.getProvisionedSpotCapacity()); node.set("InstanceTypeSpecifications", instanceTypeSpecifications(f)); node.putObject("Status").put("State", f.getState()); + if (f.getLaunchSpecifications() != null) { + setRawJson(node, "LaunchSpecifications", f.getLaunchSpecifications()); + } + if (f.getResizeSpecifications() != null) { + setRawJson(node, "ResizeSpecifications", f.getResizeSpecifications()); + } + if (f.getContext() != null) { + node.put("Context", f.getContext()); + } return node; } @@ -1968,9 +2003,24 @@ public class EmrHandler { if (fleet.getInstanceFleetType() == null) { violations.add(SmithyValidationErrors.notNull(path + ".instanceFleetType")); } + fleet.setInstanceTypes(instanceTypes(f.path("InstanceTypeConfigs"), path, violations)); + fleet.setInstanceTypeConfigs(rawArray(f.path("InstanceTypeConfigs"))); + fleet.setTargetOnDemandCapacity(f.path("TargetOnDemandCapacity").asInt(0)); + fleet.setTargetSpotCapacity(f.path("TargetSpotCapacity").asInt(0)); + fleet.setLaunchSpecifications(object(f, "LaunchSpecifications")); + fleet.setResizeSpecifications(object(f, "ResizeSpecifications")); + fleet.setContext(string(f, "Context")); + return fleet; + } + + /** + * The instance types of a fleet's InstanceTypeConfigs at {@code path}; a config without its required InstanceType + * adds to {@code violations}, as the framework refuses such a request. + */ + private static List instanceTypes(JsonNode configs, String path, List violations) { List instanceTypes = new ArrayList<>(); int position = 1; - for (JsonNode config : f.path("InstanceTypeConfigs")) { + for (JsonNode config : configs) { String instanceType = config.path("InstanceType").asText(null); if (instanceType == null) { violations.add(SmithyValidationErrors.notNull( @@ -1979,11 +2029,22 @@ public class EmrHandler { instanceTypes.add(instanceType); position++; } - fleet.setInstanceTypes(instanceTypes); - fleet.setInstanceTypeConfigs(rawArray(f.path("InstanceTypeConfigs"))); - fleet.setTargetOnDemandCapacity(f.path("TargetOnDemandCapacity").asInt(0)); - fleet.setTargetSpotCapacity(f.path("TargetSpotCapacity").asInt(0)); - return fleet; + return instanceTypes; + } + + /** + * A member an object where the model has one, as raw JSON; another JSON type is refused with + * SerializationException, as {@link #string} refuses one. + */ + private static String object(JsonNode request, String member) { + JsonNode value = request.path(member); + if (value.isMissingNode() || value.isNull()) { + return null; + } + if (!value.isObject()) { + throw malformed(member + " must be an object"); + } + return value.toString(); } // The cluster's EC2 attributes, its availability zone among them: the one Placement names, the first of its diff --git a/src/main/java/io/floci/aws/services/emr/EmrService.java b/src/main/java/io/floci/aws/services/emr/EmrService.java index 2e0cf18eb0..b54d2016bb 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrService.java @@ -1803,9 +1803,40 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear }); } + /** + * What a ModifyInstanceFleet request changes, each member null when it leaves it as it is: the target capacities, + * the ResizeSpecifications, the InstanceTypeConfigs (raw JSON) with their instance types, and the Context. + */ + public record InstanceFleetModification(Integer targetOnDemandCapacity, Integer targetSpotCapacity, + String resizeSpecifications, String instanceTypeConfigs, + List instanceTypes, String context) { + } + + /** + * The instance types of {@code types} that {@code named} leaves out, each once, in their order: those a + * ModifyInstanceFleet request must still name, or that it adds to a fleet's own. + */ + public static List instanceTypesLeftOut(List types, List named) { + return types.stream().filter(type -> !named.contains(type)).distinct().toList(); + } + /** Resizes an instance fleet; a null target leaves that capacity as it is. */ public void modifyInstanceFleet(String clusterId, String instanceFleetId, Integer targetOnDemandCapacity, Integer targetSpotCapacity) { + modifyInstanceFleet(clusterId, instanceFleetId, new InstanceFleetModification(targetOnDemandCapacity, + targetSpotCapacity, null, null, null, null)); + } + + /** + * Changes a fleet's target capacities, and the ResizeSpecifications, InstanceTypeConfigs and Context the request + * gives, which ListInstanceFleets gives back. The configs replace the fleet's own, as the Management Guide's + * "Reconfiguring instance fleets" has it: "Not including fields can result in overwriting specifications you + * declared at launch". They must name every instance type the fleet has: "You must include all instance types + * that are part of your instance fleet in the modify request". A type they add joins the fleet's after its own. + */ + public void modifyInstanceFleet(String clusterId, String instanceFleetId, InstanceFleetModification modification) { + Integer targetOnDemandCapacity = modification.targetOnDemandCapacity(); + Integer targetSpotCapacity = modification.targetSpotCapacity(); run(() -> { EmrCluster cluster = requireCluster(clusterId); if (instanceFleetId == null) { @@ -1837,10 +1868,30 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear && (onDemand != fleet.getTargetOnDemandCapacity() || spot != fleet.getTargetSpotCapacity())) { throw invalid("The target capacity of a master instance fleet cannot be modified."); } + List instanceTypes = null; + if (modification.instanceTypes() != null) { + List missing = instanceTypesLeftOut(fleet.getInstanceTypes(), modification.instanceTypes()); + if (!missing.isEmpty()) { + throw invalid("The instance type configs must include every instance type of instance fleet " + + instanceFleetId + "; missing " + String.join(", ", missing) + "."); + } + instanceTypes = new ArrayList<>(fleet.getInstanceTypes()); + instanceTypes.addAll(instanceTypesLeftOut(modification.instanceTypes(), fleet.getInstanceTypes())); + } fleet.setTargetOnDemandCapacity(onDemand); fleet.setTargetSpotCapacity(spot); fleet.setProvisionedOnDemandCapacity(onDemand); fleet.setProvisionedSpotCapacity(spot); + if (modification.resizeSpecifications() != null) { + fleet.setResizeSpecifications(modification.resizeSpecifications()); + } + if (instanceTypes != null) { + fleet.setInstanceTypeConfigs(modification.instanceTypeConfigs()); + fleet.setInstanceTypes(instanceTypes); + } + if (modification.context() != null) { + fleet.setContext(modification.context()); + } clusterStore.put(clusterId, cluster); resizeNodes(cluster); }); diff --git a/src/main/java/io/floci/aws/services/emr/model/EmrInstanceFleet.java b/src/main/java/io/floci/aws/services/emr/model/EmrInstanceFleet.java index 3843ee47d1..2663f7d83a 100644 --- a/src/main/java/io/floci/aws/services/emr/model/EmrInstanceFleet.java +++ b/src/main/java/io/floci/aws/services/emr/model/EmrInstanceFleet.java @@ -19,6 +19,11 @@ public class EmrInstanceFleet { private int provisionedOnDemandCapacity; private int provisionedSpotCapacity; private String state; + /** The LaunchSpecifications as given, raw JSON; null when none. */ + private String launchSpecifications; + /** The ResizeSpecifications as given, or as ModifyInstanceFleet last set them, raw JSON; null when none. */ + private String resizeSpecifications; + private String context; public EmrInstanceFleet() {} @@ -59,4 +64,17 @@ public class EmrInstanceFleet { public String getState() { return state; } public void setState(String state) { this.state = state; } + + public String getLaunchSpecifications() { return launchSpecifications; } + public void setLaunchSpecifications(String launchSpecifications) { + this.launchSpecifications = launchSpecifications; + } + + public String getResizeSpecifications() { return resizeSpecifications; } + public void setResizeSpecifications(String resizeSpecifications) { + this.resizeSpecifications = resizeSpecifications; + } + + public String getContext() { return context; } + public void setContext(String context) { this.context = context; } } diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisionerTest.java index 7d8f74a14e..a4d1ea6de4 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisionerTest.java @@ -6,6 +6,7 @@ import io.floci.aws.core.common.AwsException; import io.floci.aws.services.cloudformation.model.StackResource; import io.floci.aws.services.emr.EmrHandler; import io.floci.aws.services.emr.EmrService; +import io.floci.aws.services.emr.EmrService.InstanceFleetModification; import io.floci.aws.services.emr.EmrService.InstanceGroupModification; import io.floci.aws.services.emr.model.EmrCluster; import io.floci.aws.services.emr.model.EmrInstanceFleet; @@ -14,6 +15,7 @@ import io.floci.aws.services.emr.model.SecurityConfiguration; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -22,6 +24,7 @@ import static io.floci.aws.services.cloudformation.provisioners.ProvisionContext import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +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; @@ -30,6 +33,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; 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; @@ -424,11 +428,62 @@ class EmrCfnProvisionerTest { provisioner.provision(r, json(fleetProps(4)), ctx("if-TASK", fleetProps(1))); provisioner.rollbackUpdate(r); - verify(emr).modifyInstanceFleet(CLUSTER_ID, "if-TASK", 4, 0); - verify(emr).modifyInstanceFleet(CLUSTER_ID, "if-TASK", 1, 0); + verify(emr).modifyInstanceFleet(CLUSTER_ID, "if-TASK", + new InstanceFleetModification(4, 0, null, null, null, null)); + verify(emr).modifyInstanceFleet(CLUSTER_ID, "if-TASK", + new InstanceFleetModification(1, 0, null, null, null, null)); assertEquals("if-TASK", r.getAttributes().get("InstanceFleetId")); } + @Test + void anInstanceFleetsConfigsAndResizeSpecificationsChangeInPlaceAndARollbackKeepsAnAddedType() { + String before = """ + {"ClusterId": "%s", "InstanceFleetType": "TASK", "Name": "tasks", "TargetOnDemandCapacity": 1, + "InstanceTypeConfigs": [{"InstanceType": "m5.xlarge"}]} + """.formatted(CLUSTER_ID); + String after = """ + {"ClusterId": "%s", "InstanceFleetType": "TASK", "Name": "tasks", "TargetOnDemandCapacity": 1, + "InstanceTypeConfigs": [{"InstanceType": "m5.xlarge", "WeightedCapacity": 2, + "Configurations": [{"Classification": "spark", "ConfigurationProperties": {"a": "b"}}]}, + {"InstanceType": "r5.xlarge"}], + "ResizeSpecifications": {"SpotResizeSpecification": {"TimeoutDurationMinutes": 20}}} + """.formatted(CLUSTER_ID); + StackResource r = typed("AWS::EMR::InstanceFleetConfig", "if-TASK"); + when(emr.describeCluster(CLUSTER_ID)).thenReturn(emrCluster(CLUSTER_ID, "WAITING")); + EmrInstanceFleet live = new EmrInstanceFleet(); + live.setId("if-TASK"); + live.setTargetOnDemandCapacity(1); + live.setInstanceTypeConfigs("[{\"InstanceType\":\"m5.xlarge\"}]"); + EmrInstanceFleet updated = new EmrInstanceFleet(); + updated.setId("if-TASK"); + updated.setInstanceTypeConfigs("[{\"InstanceType\":\"m5.xlarge\",\"WeightedCapacity\":2}," + + "{\"InstanceType\":\"r5.xlarge\"}]"); + updated.setInstanceTypes(new ArrayList<>(List.of("m5.xlarge", "r5.xlarge"))); + when(emr.listInstanceFleets(CLUSTER_ID)).thenReturn(List.of(live), List.of(updated)); + + provisioner.provision(r, json(after), ctx("if-TASK", before)); + provisioner.rollbackUpdate(r); + + ArgumentCaptor modifications = + ArgumentCaptor.forClass(InstanceFleetModification.class); + verify(emr, times(2)).modifyInstanceFleet(eq(CLUSTER_ID), eq("if-TASK"), modifications.capture()); + InstanceFleetModification update = modifications.getAllValues().get(0); + assertEquals(json("{\"SpotResizeSpecification\":{\"TimeoutDurationMinutes\":20}}"), + json(update.resizeSpecifications())); + assertEquals(json(""" + [{"InstanceType": "m5.xlarge", "WeightedCapacity": 2, + "Configurations": [{"Classification": "spark", "Properties": {"a": "b"}}]}, + {"InstanceType": "r5.xlarge"}]"""), json(update.instanceTypeConfigs())); + assertEquals(List.of("m5.xlarge", "r5.xlarge"), update.instanceTypes()); + // The configs go back, but r5.xlarge stays: ModifyInstanceFleet refuses configs that leave a type out. The + // fleet had no resize specifications, which no request can clear, so they stay too. + InstanceFleetModification restore = modifications.getAllValues().get(1); + assertNull(restore.resizeSpecifications()); + assertEquals(json("[{\"InstanceType\":\"m5.xlarge\"},{\"InstanceType\":\"r5.xlarge\"}]"), + json(restore.instanceTypeConfigs())); + assertEquals(List.of("m5.xlarge", "r5.xlarge"), restore.instanceTypes()); + } + @Test void anInstanceGroupOrFleetDeleteShrinksItAndOneWhoseClusterEndedIsLeftAlone() { when(emr.describeCluster(CLUSTER_ID)).thenReturn(emrCluster(CLUSTER_ID, "WAITING")); @@ -481,4 +536,66 @@ class EmrCfnProvisionerTest { verify(emr).modifyInstanceFleet(CLUSTER_ID, "if-TASK", 0, 0); } + + @Test + void droppedFleetConfigsAreKeptAndAFleetStoredWithItsTypesAloneGetsThemBackOnRollback() { + String before = """ + {"ClusterId": "%s", "InstanceFleetType": "TASK", "Name": "tasks", "TargetOnDemandCapacity": 1, + "InstanceTypeConfigs": [{"InstanceType": "m5.xlarge"}]} + """.formatted(CLUSTER_ID); + String dropped = """ + {"ClusterId": "%s", "InstanceFleetType": "TASK", "Name": "tasks", "TargetOnDemandCapacity": 2} + """.formatted(CLUSTER_ID); + String weighted = """ + {"ClusterId": "%s", "InstanceFleetType": "TASK", "Name": "tasks", "TargetOnDemandCapacity": 1, + "InstanceTypeConfigs": [{"InstanceType": "m5.xlarge", "WeightedCapacity": 4}]} + """.formatted(CLUSTER_ID); + when(emr.describeCluster(CLUSTER_ID)).thenReturn(emrCluster(CLUSTER_ID, "WAITING")); + EmrInstanceFleet live = new EmrInstanceFleet(); + live.setId("if-TASK"); + live.setTargetOnDemandCapacity(1); + live.setInstanceTypes(new ArrayList<>(List.of("m5.xlarge"))); + when(emr.listInstanceFleets(CLUSTER_ID)).thenReturn(List.of(live)); + + // Dropping the configs resizes the fleet and leaves its configs as they are. + provisioner.provision(typed("AWS::EMR::InstanceFleetConfig", "if-TASK"), json(dropped), + ctx("if-TASK", before)); + verify(emr).modifyInstanceFleet(CLUSTER_ID, "if-TASK", + new InstanceFleetModification(2, 0, null, null, null, null)); + + // A fleet stored with its instance types alone gets a config naming each back, not the update's weight. + StackResource r = typed("AWS::EMR::InstanceFleetConfig", "if-TASK"); + provisioner.provision(r, json(weighted), ctx("if-TASK", before)); + provisioner.rollbackUpdate(r); + ArgumentCaptor modifications = + ArgumentCaptor.forClass(InstanceFleetModification.class); + verify(emr, times(3)).modifyInstanceFleet(eq(CLUSTER_ID), eq("if-TASK"), modifications.capture()); + assertEquals(json("[{\"InstanceType\":\"m5.xlarge\"}]"), + json(modifications.getAllValues().get(2).instanceTypeConfigs())); + } + + @Test + void aFleetUpdateWhoseConfigsBreakTheVolumeLimitIsRefusedBeforeAnythingChanges() { + String before = """ + {"ClusterId": "%s", "InstanceFleetType": "TASK", "Name": "tasks", "TargetOnDemandCapacity": 1, + "InstanceTypeConfigs": [{"InstanceType": "m5.xlarge"}]} + """.formatted(CLUSTER_ID); + String tooMany = """ + {"ClusterId": "%s", "InstanceFleetType": "TASK", "Name": "tasks", "TargetOnDemandCapacity": 3, + "InstanceTypeConfigs": [{"InstanceType": "m5.xlarge", "EbsConfiguration": {"EbsBlockDeviceConfigs": [ + {"VolumeSpecification": {"VolumeType": "gp3", "SizeInGB": 10}, "VolumesPerInstance": 26}]}}]} + """.formatted(CLUSTER_ID); + when(emr.describeCluster(CLUSTER_ID)).thenReturn(emrCluster(CLUSTER_ID, "WAITING")); + EmrInstanceFleet live = new EmrInstanceFleet(); + live.setId("if-TASK"); + live.setTargetOnDemandCapacity(1); + live.setInstanceTypeConfigs("[{\"InstanceType\":\"m5.xlarge\"}]"); + when(emr.listInstanceFleets(CLUSTER_ID)).thenReturn(List.of(live)); + + AwsException refused = assertThrows(AwsException.class, () -> provisioner.provision( + typed("AWS::EMR::InstanceFleetConfig", "if-TASK"), json(tooMany), ctx("if-TASK", before))); + + assertEquals("There is a limit of 25 volumes per instance.", refused.getMessage()); + verify(emr, never()).modifyInstanceFleet(eq(CLUSTER_ID), eq("if-TASK"), any(InstanceFleetModification.class)); + } } diff --git a/src/test/java/io/floci/aws/services/emr/EmrInstanceTypeSpecificationsIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrInstanceTypeSpecificationsIntegrationTest.java index 8129aa269d..0d1923c311 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrInstanceTypeSpecificationsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrInstanceTypeSpecificationsIntegrationTest.java @@ -97,6 +97,88 @@ class EmrInstanceTypeSpecificationsIntegrationTest { .body(specifications + "[0].WeightedCapacity", equalTo(1)); } + @Test + void aFleetsLaunchAndResizeSpecificationsAndContextAreKeptAndModifyInstanceFleetChangesThem() { + String id = cluster(""" + [{"InstanceFleetType": "MASTER", "TargetOnDemandCapacity": 1, + "InstanceTypeConfigs": [{"InstanceType": "m5.xlarge"}]}, + {"InstanceFleetType": "CORE", "TargetOnDemandCapacity": 1, "TargetSpotCapacity": 2, + "InstanceTypeConfigs": [{"InstanceType": "m5.xlarge"}], "Context": "etl", + "LaunchSpecifications": {"OnDemandSpecification": {"AllocationStrategy": "lowest-price"}, + "SpotSpecification": {"TimeoutDurationMinutes": 10, "TimeoutAction": "SWITCH_TO_ON_DEMAND", + "AllocationStrategy": "capacity-optimized"}}, + "ResizeSpecifications": {"SpotResizeSpecification": {"TimeoutDurationMinutes": 20}, + "OnDemandResizeSpecification": {"TimeoutDurationMinutes": 30}}}]"""); + String core = "InstanceFleets.find { it.InstanceFleetType == 'CORE' }"; + String coreId = emr("ListInstanceFleets", "{\"ClusterId\":\"" + id + "\"}").then().statusCode(200) + .body(core + ".Context", equalTo("etl")) + .body(core + ".LaunchSpecifications.SpotSpecification.TimeoutAction", equalTo("SWITCH_TO_ON_DEMAND")) + .body(core + ".LaunchSpecifications.OnDemandSpecification.AllocationStrategy", equalTo("lowest-price")) + .body(core + ".ResizeSpecifications.OnDemandResizeSpecification.TimeoutDurationMinutes", equalTo(30)) + .extract().path(core + ".Id"); + + emr("ModifyInstanceFleet", """ + {"ClusterId": "%s", "InstanceFleet": {"InstanceFleetId": "%s", "TargetSpotCapacity": 3, + "Context": "nightly", "InstanceTypeConfigs": [{"InstanceType": "m5.xlarge", "WeightedCapacity": 2, + "Configurations": [{"Classification": "spark", + "Properties": {"maximizeResourceAllocation": "true"}}]}], + "ResizeSpecifications": {"SpotResizeSpecification": {"TimeoutDurationMinutes": 45}}}} + """.formatted(id, coreId)).then().statusCode(200); + + emr("ListInstanceFleets", "{\"ClusterId\":\"" + id + "\"}").then().statusCode(200) + .body(core + ".TargetSpotCapacity", equalTo(3)) + .body(core + ".Context", equalTo("nightly")) + .body(core + ".InstanceTypeSpecifications.InstanceType", equalTo(List.of("m5.xlarge"))) + .body(core + ".InstanceTypeSpecifications[0].WeightedCapacity", equalTo(2)) + .body(core + ".InstanceTypeSpecifications[0].Configurations[0].Classification", equalTo("spark")) + .body(core + ".ResizeSpecifications.SpotResizeSpecification.TimeoutDurationMinutes", equalTo(45)) + .body(core + ".LaunchSpecifications.SpotSpecification.TimeoutDurationMinutes", equalTo(10)); + emr("ModifyInstanceFleet", """ + {"ClusterId": "%s", "InstanceFleet": {"InstanceFleetId": "%s", + "InstanceTypeConfigs": [{"WeightedCapacity": 2}]}} + """.formatted(id, coreId)).then().statusCode(400) + .body("__type", equalTo("ValidationException")); + // The Management Guide: "You must include all instance types that are part of your instance fleet". + emr("ModifyInstanceFleet", """ + {"ClusterId": "%s", "InstanceFleet": {"InstanceFleetId": "%s", + "InstanceTypeConfigs": [{"InstanceType": "r5.2xlarge"}]}} + """.formatted(id, coreId)).then().statusCode(400) + .body("__type", equalTo("InvalidRequestException")) + .body("message", equalTo("The instance type configs must include every instance type of instance " + + "fleet " + coreId + "; missing m5.xlarge.")); + } + + @Test + void aFleetMemberOfTheWrongJsonTypeIsRefusedAndLeavesTheFleetAsItWas() { + String id = cluster(""" + [{"InstanceFleetType": "MASTER", "TargetOnDemandCapacity": 1, + "InstanceTypeConfigs": [{"InstanceType": "m5.xlarge"}]}]"""); + String fleet = """ + {"ClusterId": "%s", "InstanceFleet": {"InstanceFleetType": "TASK", "TargetSpotCapacity": 1, + "InstanceTypeConfigs": [{"InstanceType": "c5.xlarge"}], %s}}"""; + emr("AddInstanceFleet", fleet.formatted(id, "\"LaunchSpecifications\": \"fast\"")) + .then().statusCode(400).body("__type", equalTo("SerializationException")); + emr("AddInstanceFleet", fleet.formatted(id, "\"Context\": 7")) + .then().statusCode(400).body("__type", equalTo("SerializationException")); + String task = emr("AddInstanceFleet", fleet.formatted(id, "\"Context\": \"etl\"")) + .then().statusCode(200).extract().path("InstanceFleetId"); + + emr("ModifyInstanceFleet", """ + {"ClusterId": "%s", "InstanceFleet": {"InstanceFleetId": "%s", "TargetSpotCapacity": 2, + "ResizeSpecifications": "slow"}}""".formatted(id, task)) + .then().statusCode(400).body("__type", equalTo("SerializationException")); + emr("ModifyInstanceFleet", """ + {"ClusterId": "%s", "InstanceFleet": {"InstanceFleetId": "%s", "InstanceTypeConfigs": "c5.xlarge"}} + """.formatted(id, task)) + .then().statusCode(400).body("__type", equalTo("SerializationException")); + + String added = "InstanceFleets.find { it.Id == '" + task + "' }"; + emr("ListInstanceFleets", "{\"ClusterId\":\"" + id + "\"}").then().statusCode(200) + .body(added + ".TargetSpotCapacity", equalTo(1)) + .body(added + ".Context", equalTo("etl")) + .body("InstanceFleets", hasSize(2)); + } + /** The Management Guide: "There is a limit of 25 volumes per instance." */ @Test void aConfigAttachingMoreThan25VolumesPerInstanceIsRefused() { diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index e6a71073d6..6dc06b0290 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -238,8 +238,8 @@ 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::EMR::Cluster: 'created through `RunJobFlow`, once it is waiting or running, its master, core and task groups or fleets as `RunJobFlow`''s `InstanceGroups` or `InstanceFleets`; `AdditionalInfo`, `KerberosAttributes`, `OSReleaseLabel`, `EbsRootVolumeIops`, `EbsRootVolumeThroughput`, `PlacementGroupConfigs`, `LogEncryptionKmsKeyId` and `MonitoringConfiguration`, `Instances`'' `Ec2SubnetIds`, additional security groups and `HadoopVersion` and a fleet''s launch and resize specifications are accepted with a warning and not stored; task groups and fleets need unique names; a template that sets the read-only `Id` or `MasterPublicDNS` is refused; updated in place for `AutoTerminationPolicy`, `ManagedScalingPolicy`, `StepConcurrencyLevel`, `VisibleToAllUsers`, `Tags` (keeping tags added outside the stack), `TerminationProtected`, `UnhealthyNodeReplacement`, a core or task group''s `InstanceCount` and `AutoScalingPolicy` and a core or task fleet''s target capacities, a dropped one taking its default; any other change, within `Instances` included, replaces the cluster and terminates the old one once the update commits; a termination-protected cluster refuses the delete' - AWS::EMR::InstanceFleetConfig: 'a `TASK` fleet, the one type the reference allows, added through `AddInstanceFleet`; `TargetOnDemandCapacity` and `TargetSpotCapacity` update in place through `ModifyInstanceFleet`, a change to `InstanceTypeConfigs` or `ResizeSpecifications` is accepted with a warning and not applied, and a create-only change adds a new fleet; the delete shrinks the fleet to nothing, as a fleet cannot be removed from its cluster' + AWS::EMR::Cluster: 'created through `RunJobFlow`, once it is waiting or running, its master, core and task groups or fleets as `RunJobFlow`''s `InstanceGroups` or `InstanceFleets`; `AdditionalInfo`, `KerberosAttributes`, `OSReleaseLabel`, `EbsRootVolumeIops`, `EbsRootVolumeThroughput`, `PlacementGroupConfigs`, `LogEncryptionKmsKeyId` and `MonitoringConfiguration`, `Instances`'' `Ec2SubnetIds`, additional security groups and `HadoopVersion` are accepted with a warning and not stored; task groups and fleets need unique names; a template that sets the read-only `Id` or `MasterPublicDNS` is refused; updated in place for `AutoTerminationPolicy`, `ManagedScalingPolicy`, `StepConcurrencyLevel`, `VisibleToAllUsers`, `Tags` (keeping tags added outside the stack), `TerminationProtected`, `UnhealthyNodeReplacement`, a core or task group''s `InstanceCount` and `AutoScalingPolicy` and a core or task fleet''s target capacities, a dropped one taking its default; any other change, within `Instances` included, replaces the cluster and terminates the old one once the update commits; a termination-protected cluster refuses the delete' + AWS::EMR::InstanceFleetConfig: 'a `TASK` fleet, the one type the reference allows, added through `AddInstanceFleet`; `TargetOnDemandCapacity`, `TargetSpotCapacity`, `InstanceTypeConfigs` and `ResizeSpecifications` update in place through `ModifyInstanceFleet`, and a create-only change adds a new fleet; a rollback puts them back, but not an instance type the update added, which every later `ModifyInstanceFleet` must include, nor resize specifications where the fleet had none, which no request can clear, and dropped configs or resize specifications are kept for the same reason; the delete shrinks the fleet to nothing, as a fleet cannot be removed from its cluster' AWS::EMR::InstanceGroupConfig: 'a `TASK` group, the one role the reference allows, added through `AddInstanceGroups`; `InstanceCount` and `AutoScalingPolicy` update in place, and a create-only change adds a new group; the delete removes its policy and shrinks it to nothing, as a group cannot be removed from its cluster' AWS::EMR::SecurityConfiguration: 'created with `Name`, generated when the template gives none, and the `SecurityConfiguration` JSON, as an object or its text; both are create-only, so any change replaces it and deletes the old one once the update commits, and a change that keeps a template''s own `Name` is refused, as for every custom-named resource' AWS::EMR::Step: 'added through `AddJobFlowSteps`, `LogUri` and `EncryptionKeyArn` as its `StepMonitoringConfiguration`; every property is create-only, so a change adds a new step, and a step stays in its cluster''s history when deleted, as the schema''s delete handler calls nothing'