diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index bc2b673164..7ce97b7d01 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`, a group's `EbsConfiguration` and `CustomAmiId` 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` 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 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 cbce7bf0cf..bc63ac5b83 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -207,6 +207,22 @@ The reference names no devices, so Floci names them `/dev/sdb`, `/dev/sdc` and o 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. +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 +give its `CustomAmiId` as their image, over the cluster's. `ListInstances` gives each instance its `PublicIpAddress`, +the one its `PublicDnsName` names, in 203.0.113.0/24, RFC 5737's documentation range, for a cluster's first 254 +instances and past them in 100.64.0.0/10, RFC 6598's shared address space. It gives an `EbsVolumes` entry for each +device its group or instance type config gives it, with a volume id of Floci's own that differs between clusters. +`ModifyInstanceGroups` keeps a group's `ShrinkPolicy`, which `ListInstanceGroups` gives back, and a shrink it comes with +follows its `InstanceResizePolicy`: it ends the "Specific list of instances to be terminated when shrinking an instance +group" first, then the group's last instances, passing the "Specific list of instances to be protected when shrinking an +instance group". Those instances end as `EC2InstanceIdsToTerminate` ends them, so their ids are not taken again, and a +later entry of the same request for the group counts from what an earlier one leaves. An id to terminate that is not +one of the group's running instances is refused with `ValidationException`, as `EC2InstanceIdsToTerminate` refuses it, +and so is a shrink the protected instances leave short, rather than ending one of them; AWS's answer to either is not +documented, so the wording is Floci's. Its `DecommissionTimeout` changes nothing, as Floci's nodes have no +decommissioning to wait for. `ModifyInstanceGroups` keeps the `Configurations` it gives a group, which `ListInstanceGroups` gives back with the group's `ConfigurationsVersion`. With `ReconfigurationType` `MERGE` they are merged into the group's own, as the Release Guide's "Reconfigure an instance group in a running cluster" has it: "This option only adds or modifies the new 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 e43481fc7c..024393129e 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 @@ -109,8 +109,7 @@ 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 group, and of an instance fleet, Floci's RunJobFlow keeps nothing of. */ - private static final List GROUP_NOT_STORED = List.of("EbsConfiguration", "CustomAmiId"); + /** 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"; @@ -299,7 +298,7 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner { } } - /** Warns of each property, or member of {@code Instances}, its groups or fleets, RunJobFlow keeps nothing of. */ + /** Warns of each property, or member of {@code Instances} or its fleets, RunJobFlow keeps nothing of. */ private static void warnNotStored(String logicalId, JsonNode template) { List ignored = new ArrayList<>(); for (String name : CLUSTER_NOT_STORED) { @@ -313,17 +312,9 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner { ignored.add("Instances." + name); } } - List groups = new ArrayList<>(List.of(instances.path("MasterInstanceGroup"), - instances.path("CoreInstanceGroup"))); - instances.path("TaskInstanceGroups").forEach(groups::add); List fleets = new ArrayList<>(List.of(instances.path("MasterInstanceFleet"), instances.path("CoreInstanceFleet"))); instances.path("TaskInstanceFleets").forEach(fleets::add); - for (String name : GROUP_NOT_STORED) { - if (groups.stream().anyMatch(group -> group.has(name))) { - ignored.add("an instance group's " + name); - } - } for (String name : FLEET_NOT_STORED) { if (fleets.stream().anyMatch(fleet -> fleet.has(name))) { ignored.add("an instance fleet's " + name); 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 9c491bd6f4..971107b4ba 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrHandler.java +++ b/src/main/java/io/floci/aws/services/emr/EmrHandler.java @@ -1003,7 +1003,7 @@ public class EmrHandler { if (!violations.isEmpty()) { throw SmithyValidationErrors.validationException(violations); } - requireEbsVolumeLimit(fleetNode); + requireFleetEbsVolumeLimit(fleetNode); return fleet; } @@ -1065,13 +1065,14 @@ public class EmrHandler { } long first = EmrService.firstIndex(listed, set); PrimitiveIterator.OfLong ordinals = set.ordinalsFrom(skip + 1); + ArrayNode devices = ebsBlockDevices(ebsConfigurationOf(cluster, set)); for (long k = skip + 1; k <= set.count(); k++) { if (page == INSTANCES_PER_PAGE) { response.put("Marker", String.valueOf(start + page)); return Response.ok(response).build(); } long ordinal = ordinals.nextLong(); - arr.add(syntheticInstanceNode(cluster, set, first + ordinal - 1, ordinal, terminated)); + arr.add(syntheticInstanceNode(cluster, set, first + ordinal - 1, ordinal, terminated, devices)); page++; } skip = 0; @@ -1348,11 +1349,13 @@ public class EmrHandler { for (JsonNode g : groups) { JsonNode count = g.path("InstanceCount"); JsonNode configurations = g.path("Configurations"); + JsonNode shrink = g.path("ShrinkPolicy"); modifications.add(new EmrService.InstanceGroupModification( g.path("InstanceGroupId").asText(null), count.isMissingNode() || count.isNull() ? null : count.asInt(), configurations.isArray() ? configurations.toString() : null, - g.path("ReconfigurationType").asText(null), instanceIds(g.path("EC2InstanceIdsToTerminate")))); + g.path("ReconfigurationType").asText(null), instanceIds(g.path("EC2InstanceIdsToTerminate")), + shrink.isObject() ? shrink : null)); } } service.modifyInstanceGroups(text(request, "ClusterId"), region, modifications); @@ -1611,9 +1614,46 @@ public class EmrHandler { setRawJson(node, "LastSuccessfullyAppliedConfigurations", g.getConfigurations()); node.put("LastSuccessfullyAppliedConfigurationsVersion", g.getConfigurationsVersion()); } + JsonNode ebs = readRawObject(g.getEbsConfiguration()); + if (ebs != null) { + ArrayNode devices = ebsBlockDevices(ebs); + if (!devices.isEmpty()) { + node.set("EbsBlockDevices", devices); + } + if (ebs.hasNonNull("EbsOptimized")) { + node.put("EbsOptimized", ebs.path("EbsOptimized").asBoolean()); + } + } + if (g.getCustomAmiId() != null) { + node.put("CustomAmiId", g.getCustomAmiId()); + } + if (g.getShrinkPolicy() != null) { + setRawJson(node, "ShrinkPolicy", g.getShrinkPolicy()); + } return node; } + /** + * An EbsConfiguration as the EbsBlockDevices it gives each instance: one per volume, the way VolumesPerInstance + * counts them, with its VolumeSpecification, named {@code /dev/sdb} on, as the reference gives no device names. + */ + private ArrayNode ebsBlockDevices(JsonNode ebs) { + ArrayNode devices = objectMapper.createArrayNode(); + for (JsonNode device : ebs.path("EbsBlockDeviceConfigs")) { + // Bounded for a config stored before the limit was held at create. + int volumes = Math.min(device.path("VolumesPerInstance").asInt(1), + EBS_VOLUMES_PER_INSTANCE - devices.size()); + for (int volume = 0; volume < volumes; volume++) { + ObjectNode blockDevice = devices.addObject(); + if (device.hasNonNull("VolumeSpecification")) { + blockDevice.set("VolumeSpecification", device.get("VolumeSpecification")); + } + blockDevice.put("Device", deviceName(devices.size() - 1)); + } + } + return devices; + } + /** An AutoScalingPolicyDescription: the stored Constraints and Rules with an ATTACHED status. */ private ObjectNode autoScalingPolicyNode(String rawPolicy) { ObjectNode node = objectMapper.createObjectNode(); @@ -1677,19 +1717,7 @@ public class EmrHandler { specification.set("Configurations", config.get("Configurations")); } JsonNode ebs = config.path("EbsConfiguration"); - ArrayNode devices = objectMapper.createArrayNode(); - for (JsonNode device : ebs.path("EbsBlockDeviceConfigs")) { - // Bounded for a config stored before the limit was held at create. - int volumes = Math.min(device.path("VolumesPerInstance").asInt(1), - EBS_VOLUMES_PER_INSTANCE - devices.size()); - for (int volume = 0; volume < volumes; volume++) { - ObjectNode blockDevice = devices.addObject(); - if (device.hasNonNull("VolumeSpecification")) { - blockDevice.set("VolumeSpecification", device.get("VolumeSpecification")); - } - blockDevice.put("Device", deviceName(devices.size() - 1)); - } - } + ArrayNode devices = ebsBlockDevices(ebs); if (!devices.isEmpty()) { specification.set("EbsBlockDevices", devices); } @@ -1715,13 +1743,15 @@ public class EmrHandler { return "/dev/sd" + letters; } + /** An instance of {@code set}, whose EBS block {@code devices} each instance of the set has. */ private ObjectNode syntheticInstanceNode(EmrCluster cluster, ListedInstances set, long index, long ordinal, - boolean terminated) { + boolean terminated, ArrayNode devices) { String privateIp = EmrService.privateIpAddress(set.number(), ordinal); ObjectNode node = objectMapper.createObjectNode(); node.put("Id", "ci-" + index + cluster.getId()); node.put("Ec2InstanceId", EmrService.ec2InstanceId(index)); node.put("PublicDnsName", EmrService.publicDnsName(index, cluster.getRegion())); + node.put("PublicIpAddress", EmrService.publicIpAddress(index)); node.put("PrivateDnsName", AwsRegions.ec2PrivateIpDnsName(privateIp, cluster.getRegion())); node.put("PrivateIpAddress", privateIp); if (set.groupId() != null) { @@ -1737,9 +1767,44 @@ public class EmrHandler { node.put("InstanceType", set.instanceType()); } node.putObject("Status").put("State", set.state()); + if (!devices.isEmpty()) { + ArrayNode volumes = node.putArray("EbsVolumes"); + for (int device = 0; device < devices.size(); device++) { + volumes.addObject().put("Device", devices.get(device).path("Device").asText()) + .put("VolumeId", EmrService.ebsVolumeId(cluster.getId(), index, device)); + } + } return node; } + /** + * The EbsConfiguration an instance of {@code set} was given: its group's, or, in a fleet, that of the + * InstanceTypeConfig of its instance type. An empty one for none. + */ + private JsonNode ebsConfigurationOf(EmrCluster cluster, ListedInstances set) { + if (set.groupId() != null) { + for (EmrInstanceGroup group : cluster.getInstanceGroups()) { + if (set.groupId().equals(group.getId())) { + JsonNode ebs = readRawObject(group.getEbsConfiguration()); + return ebs == null ? objectMapper.createObjectNode() : ebs; + } + } + } + if (set.fleetId() != null) { + for (EmrInstanceFleet fleet : cluster.getInstanceFleets()) { + if (set.fleetId().equals(fleet.getId())) { + JsonNode configs = readRawArray(fleet.getInstanceTypeConfigs()); + for (JsonNode config : configs == null ? objectMapper.createArrayNode() : configs) { + if (config.path("InstanceType").asText("").equals(set.instanceType())) { + return config.path("EbsConfiguration"); + } + } + } + } + } + return objectMapper.createObjectNode(); + } + private ArrayNode tagArray(Map tags) { ArrayNode out = objectMapper.createArrayNode(); tags.forEach((k, v) -> { @@ -1802,6 +1867,12 @@ public class EmrHandler { EmrService.validateAutoScalingPolicy(autoScaling, group.getInstanceGroupType()); group.setAutoScalingPolicy(autoScaling.toString()); } + JsonNode ebs = g.path("EbsConfiguration"); + if (ebs.isObject()) { + requireEbsVolumeLimit(ebs); + group.setEbsConfiguration(ebs.toString()); + } + group.setCustomAmiId(g.path("CustomAmiId").asText(null)); groups.add(group); } return groups; @@ -1859,7 +1930,7 @@ public class EmrHandler { if (!violations.isEmpty()) { throw SmithyValidationErrors.validationException(violations); } - fleetsNode.forEach(EmrHandler::requireEbsVolumeLimit); + fleetsNode.forEach(EmrHandler::requireFleetEbsVolumeLimit); return fleets; } @@ -1868,15 +1939,20 @@ public class EmrHandler { * Guide allows: "There is a limit of 25 volumes per instance." AWS's error for it is not documented, so the * ValidationException carrying that sentence is Floci's. */ - private static void requireEbsVolumeLimit(JsonNode fleet) { + private static void requireFleetEbsVolumeLimit(JsonNode fleet) { for (JsonNode config : fleet.path("InstanceTypeConfigs")) { - long volumes = 0; - for (JsonNode device : config.path("EbsConfiguration").path("EbsBlockDeviceConfigs")) { - volumes += device.path("VolumesPerInstance").asLong(1); - } - if (volumes > EBS_VOLUMES_PER_INSTANCE) { - throw new AwsException("ValidationException", "There is a limit of 25 volumes per instance.", 400); - } + requireEbsVolumeLimit(config.path("EbsConfiguration")); + } + } + + /** An EbsConfiguration's volumes, counted as VolumesPerInstance counts them, hold to AWS's limit per instance. */ + private static void requireEbsVolumeLimit(JsonNode ebs) { + long volumes = 0; + for (JsonNode device : ebs.path("EbsBlockDeviceConfigs")) { + volumes += device.path("VolumesPerInstance").asLong(1); + } + if (volumes > EBS_VOLUMES_PER_INSTANCE) { + throw new AwsException("ValidationException", "There is a limit of 25 volumes per instance.", 400); } } @@ -1998,6 +2074,20 @@ public class EmrHandler { } } + /** A stored raw JSON object, or null when there is none or it cannot be read. */ + private JsonNode readRawObject(String rawJson) { + if (rawJson == null) { + return null; + } + try { + JsonNode node = objectMapper.readTree(rawJson); + return node.isObject() ? node : null; + } catch (JsonProcessingException e) { + LOG.warnv(e, "Failed to parse stored JSON object; ignored. Value: {0}", rawJson); + return null; + } + } + private void setRawJson(ObjectNode target, String field, String rawJson) { if (rawJson == null) { return; 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 32559a8492..2e0cf18eb0 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrService.java @@ -1463,15 +1463,21 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear * reconfiguration type is OVERWRITE, and {@code instancesToTerminate} are EC2InstanceIdsToTerminate, none for null. */ public record InstanceGroupModification(String instanceGroupId, Integer instanceCount, String configurations, - String reconfigurationType, List instancesToTerminate) { + String reconfigurationType, List instancesToTerminate, + JsonNode shrinkPolicy) { public InstanceGroupModification(String instanceGroupId, Integer instanceCount, String configurations) { - this(instanceGroupId, instanceCount, configurations, null, null); + this(instanceGroupId, instanceCount, configurations, null, null, null); } public InstanceGroupModification(String instanceGroupId, Integer instanceCount, String configurations, String reconfigurationType) { - this(instanceGroupId, instanceCount, configurations, reconfigurationType, null); + this(instanceGroupId, instanceCount, configurations, reconfigurationType, null, null); + } + + public InstanceGroupModification(String instanceGroupId, Integer instanceCount, String configurations, + String reconfigurationType, List instancesToTerminate) { + this(instanceGroupId, instanceCount, configurations, reconfigurationType, instancesToTerminate, null); } } @@ -1491,6 +1497,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear Map touched = new LinkedHashMap<>(); List groups = new ArrayList<>(); List> terminations = new ArrayList<>(); + Map> endings = new HashMap<>(); for (int position = 1; position <= modifications.size(); position++) { InstanceGroupModification mod = modifications.get(position - 1); EmrCluster found = clusterId != null @@ -1514,7 +1521,19 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear throw invalid("The instance count of a master instance group cannot be modified."); } } - terminations.add(ordinalsToTerminate(cluster, group, mod.instancesToTerminate())); + List named = ordinalsToTerminate(cluster, group, mod.instancesToTerminate()); + List ending = new ArrayList<>(named); + // What the request's earlier entries for the same group end, so a shrink counts from what they leave. + Set endingOfGroup = endings.computeIfAbsent(cluster.getId() + "/" + group.getId(), + key -> new LinkedHashSet<>()); + endingOfGroup.addAll(named); + if (mod.instanceCount() != null && mod.shrinkPolicy() != null) { + List shrink = shrinkOrdinals(cluster, group, mod.instanceCount(), mod.shrinkPolicy(), + endingOfGroup); + ending.addAll(shrink); + endingOfGroup.addAll(shrink); + } + terminations.add(ending); groups.add(group); } for (int i = 0; i < modifications.size(); i++) { @@ -1535,6 +1554,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear group.setRequestedInstanceCount(mod.instanceCount()); group.setRunningInstanceCount(mod.instanceCount()); } + if (mod.shrinkPolicy() != null) { + group.setShrinkPolicy(mod.shrinkPolicy().toString()); + } if (mod.configurations() != null) { group.setConfigurations(MERGE.equals(mod.reconfigurationType()) ? mergedConfigurations(group.getConfigurations(), mod.configurations()) @@ -1561,18 +1583,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear if ("MASTER".equals(group.getInstanceGroupType())) { throw invalid("The instance count of a master instance group cannot be modified."); } - List listed = EmrHandler.listedInstances(cluster, false); - Map current = new HashMap<>(); - for (EmrHandler.ListedInstances set : listed) { - if (group.getId().equals(set.groupId())) { - long first = firstIndex(listed, set); - PrimitiveIterator.OfLong ordinals = set.ordinalsFrom(1); - for (long k = 1; k <= set.count(); k++) { - long ordinal = ordinals.nextLong(); - current.put(ec2InstanceId(first + ordinal - 1), (int) ordinal); - } - } - } + Map current = runningOrdinals(cluster, group); List ordinals = new ArrayList<>(); for (String instanceId : new LinkedHashSet<>(instanceIds)) { Integer ordinal = current.get(instanceId); @@ -1585,6 +1596,71 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear return ordinals; } + /** The group's instances as ListInstances gives them now: each EC2 instance id and its ordinal, in that order. */ + private static Map runningOrdinals(EmrCluster cluster, EmrInstanceGroup group) { + List listed = EmrHandler.listedInstances(cluster, false); + Map current = new LinkedHashMap<>(); + for (EmrHandler.ListedInstances set : listed) { + if (group.getId().equals(set.groupId())) { + long first = firstIndex(listed, set); + PrimitiveIterator.OfLong ordinals = set.ordinalsFrom(1); + for (long k = 1; k <= set.count(); k++) { + long ordinal = ordinals.nextLong(); + current.put(ec2InstanceId(first + ordinal - 1), (int) ordinal); + } + } + } + return current; + } + + /** + * The ordinals a shrink to {@code count} ends under a ShrinkPolicy's InstanceResizePolicy, beyond those already + * {@code ending}, by EC2InstanceIdsToTerminate or the request's earlier entries for the group: first its "Specific + * list of instances to be terminated when shrinking an instance group", then the group's last instances, passing + * its "Specific list of instances to be protected when shrinking an instance group". Ended this way, as named + * instances are, their ids are not taken again. An id to terminate that is not one of the group's running + * instances is refused, as EC2InstanceIdsToTerminate refuses it, and so is a shrink the protected instances leave + * short, rather than ending one of them. No source gives AWS's answer to either, so the wording is Floci's. + */ + private static List shrinkOrdinals(EmrCluster cluster, EmrInstanceGroup group, int count, + JsonNode shrinkPolicy, Set ending) { + Map running = runningOrdinals(cluster, group); + int shrinkBy = running.size() - ending.size() - count; + JsonNode resize = shrinkPolicy.path("InstanceResizePolicy"); + if (shrinkBy <= 0 || !resize.isObject()) { + return List.of(); + } + Set protect = new HashSet<>(); + resize.path("InstancesToProtect").forEach(id -> protect.add(id.asText())); + List chosen = new ArrayList<>(); + for (JsonNode id : resize.path("InstancesToTerminate")) { + Integer ordinal = running.get(id.asText()); + if (ordinal == null) { + throw new AwsException("ValidationException", "Instance " + id.asText() + + " is not a running instance of instance group " + group.getId() + ".", 400); + } + if (chosen.size() < shrinkBy && !ending.contains(ordinal) && !chosen.contains(ordinal)) { + chosen.add(ordinal); + } + } + List> fromTheEnd = new ArrayList<>(running.entrySet()); + Collections.reverse(fromTheEnd); + for (Map.Entry instance : fromTheEnd) { + if (chosen.size() >= shrinkBy) { + break; + } + Integer ordinal = instance.getValue(); + if (!protect.contains(instance.getKey()) && !ending.contains(ordinal) && !chosen.contains(ordinal)) { + chosen.add(ordinal); + } + } + if (chosen.size() < shrinkBy) { + throw new AwsException("ValidationException", "Instance group " + group.getId() + " cannot shrink to " + + count + " instances without ending one its shrink policy protects.", 400); + } + return chosen; + } + /** * The index, in the cluster's instance numbering, of the first place {@code set} takes: 1 for the primary node's * group or fleet, and after the places of those before it for the others. @@ -3903,7 +3979,29 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear /** The public DNS name ListInstances gives a cluster's instance {@code index}, counted from 1, in a Region. */ static String publicDnsName(long index, String region) { - return AwsEndpoints.ec2PublicDns("203.0.113." + index, region); + return AwsEndpoints.ec2PublicDns(publicIpAddress(index), region); + } + + /** + * The public address ListInstances gives a cluster's instance {@code index}, counted from 1, the one its public DNS + * name names: in 203.0.113.0/24, RFC 5737's documentation range, for the first 254, and past them in + * 100.64.0.0/10, RFC 6598's shared address space, so no instance gets an address someone else holds. + */ + static String publicIpAddress(long index) { + if (index <= 254) { + return "203.0.113." + index; + } + long n = index - 255; + return "100." + (64 + n / (254 * 256)) + "." + (n / 254) % 256 + "." + (n % 254 + 1); + } + + /** + * The id ListInstances gives the {@code device}-th EBS volume, counted from 0, of cluster {@code clusterId}'s + * instance {@code index}: 17 hex digits, as EC2's are, the first 8 from the cluster, so two clusters' volumes + * differ. + */ + static String ebsVolumeId(String clusterId, long index, int device) { + return "vol-" + String.format("%08x%09x", clusterId.hashCode(), index * 100 + device + 1); } /** @@ -4000,10 +4098,18 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear List listed = EmrHandler.listedInstances(cluster, false); long index = ordinal; String instanceType = null; + String imageId = cluster.getCustomAmiId(); for (EmrHandler.ListedInstances set : listed) { if (set.number() == group) { index = firstIndex(listed, set) + ordinal - 1; instanceType = set.instanceType(); + // A group's own CustomAmiId is the one its instances run, over the cluster's. + for (EmrInstanceGroup instanceGroup : cluster.getInstanceGroups()) { + if (set.groupId() != null && set.groupId().equals(instanceGroup.getId()) + && instanceGroup.getCustomAmiId() != null) { + imageId = instanceGroup.getCustomAmiId(); + } + } break; } } @@ -4011,11 +4117,12 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear instance.setInstanceId(ec2InstanceId(index)); instance.setOwnerId(accountId); instance.setInstanceType(instanceType); - instance.setImageId(cluster.getCustomAmiId()); + instance.setImageId(imageId); String address = privateIpAddress(group, ordinal); instance.setPrivateIpAddress(address); instance.setPrivateDnsName(AwsRegions.ec2PrivateIpDnsName(address, cluster.getRegion())); instance.setPublicDnsName(publicDnsName(index, cluster.getRegion())); + instance.setPublicIpAddress(publicIpAddress(index)); instance.setPlacement(new Placement(availabilityZone(cluster))); instance.setRegion(cluster.getRegion()); instance.setState(InstanceState.running()); diff --git a/src/main/java/io/floci/aws/services/emr/model/EmrInstanceGroup.java b/src/main/java/io/floci/aws/services/emr/model/EmrInstanceGroup.java index eb2a99c8b7..c60c2f2ffd 100644 --- a/src/main/java/io/floci/aws/services/emr/model/EmrInstanceGroup.java +++ b/src/main/java/io/floci/aws/services/emr/model/EmrInstanceGroup.java @@ -27,6 +27,11 @@ public class EmrInstanceGroup { /** The group's Configurations as given, raw JSON; null when none. Applied at once, so it is also the last applied. */ private String configurations; private long configurationsVersion; + /** The EbsConfiguration as given (EbsBlockDeviceConfigs and EbsOptimized), raw JSON; null when none. */ + private String ebsConfiguration; + private String customAmiId; + /** The ShrinkPolicy the last ModifyInstanceGroups gave, raw JSON; null when none. */ + private String shrinkPolicy; public EmrInstanceGroup() {} @@ -79,4 +84,13 @@ public class EmrInstanceGroup { public String getAutoScalingPolicy() { return autoScalingPolicy; } public void setAutoScalingPolicy(String autoScalingPolicy) { this.autoScalingPolicy = autoScalingPolicy; } + + public String getEbsConfiguration() { return ebsConfiguration; } + public void setEbsConfiguration(String ebsConfiguration) { this.ebsConfiguration = ebsConfiguration; } + + public String getCustomAmiId() { return customAmiId; } + public void setCustomAmiId(String customAmiId) { this.customAmiId = customAmiId; } + + public String getShrinkPolicy() { return shrinkPolicy; } + public void setShrinkPolicy(String shrinkPolicy) { this.shrinkPolicy = shrinkPolicy; } } diff --git a/src/test/java/io/floci/aws/services/emr/EmrResizeIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrResizeIntegrationTest.java index 7d09c77e0f..fc7c9412ff 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrResizeIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrResizeIntegrationTest.java @@ -9,6 +9,7 @@ import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; +import java.util.HashSet; import java.util.List; import java.util.Map; @@ -19,6 +20,7 @@ import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * EMR instance group and fleet resizing and bootstrap action listing over the AWS JSON 1.1 wire @@ -41,6 +43,11 @@ class EmrResizeIntegrationTest { RestAssuredJsonUtils.configureAwsContentTypes(); } + /** ListInstances for one instance group of a cluster. */ + private static Response groupInstances(String clusterId, String groupId) { + return emr("ListInstances", "{\"ClusterId\":\"" + clusterId + "\",\"InstanceGroupId\":\"" + groupId + "\"}"); + } + private static String groupId(String type) { return emr("ListInstanceGroups", "{\"ClusterId\":\"" + groupsClusterId + "\"}").jsonPath() .getString("InstanceGroups.find { it.InstanceGroupType == '" + type + "' }.Id"); @@ -517,6 +524,114 @@ class EmrResizeIntegrationTest { * EC2InstanceIdsToTerminate ends the named instance: the group's others, and the next group's, keep their ids and * addresses, the group's counts go down, and an instance it gets later takes a new id. */ + @Test + void aGroupsVolumesAmiAndShrinkPolicyAreKeptAndEachInstanceListsItsVolumesAndPublicAddress() { + String id = emr("RunJobFlow", """ + {"Name": "volumes", "Instances": {"KeepJobFlowAliveWhenNoSteps": true, "InstanceGroups": [ + {"InstanceRole": "MASTER", "InstanceType": "m5.xlarge", "InstanceCount": 1}, + {"InstanceRole": "CORE", "InstanceType": "m5.xlarge", "InstanceCount": 3, + "CustomAmiId": "ami-0123456789abcdef0", + "EbsConfiguration": {"EbsOptimized": true, "EbsBlockDeviceConfigs": [{"VolumesPerInstance": 2, + "VolumeSpecification": {"VolumeType": "gp3", "SizeInGB": 100, "Iops": 3000, + "Throughput": 125}}]}}]}} + """).then().statusCode(200).extract().path("JobFlowId"); + try { + String cluster = "{\"ClusterId\":\"" + id + "\"}"; + String core = "InstanceGroups.find { it.InstanceGroupType == 'CORE' }"; + String coreId = emr("ListInstanceGroups", cluster).then().statusCode(200) + .body(core + ".EbsOptimized", equalTo(true)) + .body(core + ".CustomAmiId", equalTo("ami-0123456789abcdef0")) + .body(core + ".EbsBlockDevices.Device", equalTo(List.of("/dev/sdb", "/dev/sdc"))) + .body(core + ".EbsBlockDevices[0].VolumeSpecification.VolumeType", equalTo("gp3")) + .body(core + ".EbsBlockDevices[1].VolumeSpecification.SizeInGB", equalTo(100)) + .extract().path(core + ".Id"); + Response instances = groupInstances(id, coreId); + List coreIds = instances.jsonPath().getList("Instances.Ec2InstanceId"); + assertEquals(List.of("/dev/sdb", "/dev/sdc"), + instances.jsonPath().getList("Instances[0].EbsVolumes.Device")); + List volumeIds = instances.jsonPath().getList("Instances.EbsVolumes.flatten().VolumeId"); + assertEquals(6, new HashSet<>(volumeIds).size(), "each of the 3 instances' 2 volumes has its own id"); + String publicIp = instances.jsonPath().getString("Instances[0].PublicIpAddress"); + assertTrue(instances.jsonPath().getString("Instances[0].PublicDnsName") + .startsWith("ec2-" + publicIp.replace('.', '-')), publicIp); + + // Shrinking to 2 ends the instance named to terminate, not the last one, which is protected. + emr("ModifyInstanceGroups", """ + {"ClusterId": "%s", "InstanceGroups": [{"InstanceGroupId": "%s", "InstanceCount": 2, + "ShrinkPolicy": {"DecommissionTimeout": 60, "InstanceResizePolicy": { + "InstancesToTerminate": ["%s"], "InstancesToProtect": ["%s"]}}}]} + """.formatted(id, coreId, coreIds.get(0), coreIds.get(2))).then().statusCode(200); + assertEquals(List.of(coreIds.get(1), coreIds.get(2)), + groupInstances(id, coreId).jsonPath().getList("Instances.Ec2InstanceId")); + emr("ListInstanceGroups", cluster).then().statusCode(200) + .body(core + ".RequestedInstanceCount", equalTo(2)) + .body(core + ".ShrinkPolicy.DecommissionTimeout", equalTo(60)) + .body(core + ".ShrinkPolicy.InstanceResizePolicy.InstancesToProtect[0]", equalTo(coreIds.get(2))); + + // Without the protection, the protected instance would have been the one to go: the group's last. + emr("ModifyInstanceGroups", """ + {"ClusterId": "%s", "InstanceGroups": [{"InstanceGroupId": "%s", "InstanceCount": 1, + "ShrinkPolicy": {"InstanceResizePolicy": {"InstancesToProtect": ["%s"]}}}]} + """.formatted(id, coreId, coreIds.get(2))).then().statusCode(200); + assertEquals(List.of(coreIds.get(2)), + groupInstances(id, coreId).jsonPath().getList("Instances.Ec2InstanceId")); + + emr("AddInstanceGroups", """ + {"JobFlowId": "%s", "InstanceGroups": [{"InstanceRole": "TASK", "InstanceType": "m5.xlarge", + "InstanceCount": 1, "EbsConfiguration": {"EbsBlockDeviceConfigs": [{"VolumesPerInstance": 26, + "VolumeSpecification": {"VolumeType": "gp3", "SizeInGB": 10}}]}}]} + """.formatted(id)).then().statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", equalTo("There is a limit of 25 volumes per instance.")); + } finally { + emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + id + "\"]}").then().statusCode(200); + } + } + + @Test + void aShrinkThatNamesAnUnknownInstanceOrProtectsTooManyIsRefusedAndTwoEntriesShrinkAGroupOnce() { + String id = emr("RunJobFlow", """ + {"Name": "shrinks", "Instances": {"KeepJobFlowAliveWhenNoSteps": true, "InstanceGroups": [ + {"InstanceRole": "MASTER", "InstanceType": "m5.xlarge", "InstanceCount": 1}, + {"InstanceRole": "CORE", "InstanceType": "m5.xlarge", "InstanceCount": 4}]}} + """).then().statusCode(200).extract().path("JobFlowId"); + try { + String coreId = emr("ListInstanceGroups", "{\"ClusterId\":\"" + id + "\"}").jsonPath() + .getString("InstanceGroups.find { it.InstanceGroupType == 'CORE' }.Id"); + List ids = groupInstances(id, coreId).jsonPath().getList("Instances.Ec2InstanceId"); + + emr("ModifyInstanceGroups", """ + {"ClusterId": "%s", "InstanceGroups": [{"InstanceGroupId": "%s", "InstanceCount": 3, + "ShrinkPolicy": {"InstanceResizePolicy": {"InstancesToTerminate": ["i-99999999999999999"]}}}]} + """.formatted(id, coreId)).then().statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", equalTo("Instance i-99999999999999999 is not a running instance of instance " + + "group " + coreId + ".")); + emr("ModifyInstanceGroups", """ + {"ClusterId": "%s", "InstanceGroups": [{"InstanceGroupId": "%s", "InstanceCount": 3, + "ShrinkPolicy": {"InstanceResizePolicy": {"InstancesToProtect": ["%s", "%s", "%s", "%s"]}}}]} + """.formatted(id, coreId, ids.get(0), ids.get(1), ids.get(2), ids.get(3))).then().statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", equalTo("Instance group " + coreId + " cannot shrink to 3 instances without " + + "ending one its shrink policy protects.")); + assertEquals(ids, groupInstances(id, coreId).jsonPath().getList("Instances.Ec2InstanceId")); + + // The second entry counts from what the first leaves: the group is already down to 3. + emr("ModifyInstanceGroups", """ + {"ClusterId": "%s", "InstanceGroups": [ + {"InstanceGroupId": "%s", "InstanceCount": 3, + "ShrinkPolicy": {"InstanceResizePolicy": {"InstancesToTerminate": ["%s"]}}}, + {"InstanceGroupId": "%s", "InstanceCount": 3, + "ShrinkPolicy": {"InstanceResizePolicy": {"InstancesToTerminate": ["%s"]}}}]} + """.formatted(id, coreId, ids.get(0), coreId, ids.get(1))).then().statusCode(200); + assertEquals(ids.subList(1, 4), groupInstances(id, coreId).jsonPath().getList("Instances.Ec2InstanceId")); + emr("ListInstanceGroups", "{\"ClusterId\":\"" + id + "\"}").then().statusCode(200) + .body("InstanceGroups.find { it.Id == '" + coreId + "' }.RunningInstanceCount", equalTo(3)); + } finally { + emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + id + "\"]}").then().statusCode(200); + } + } + @Test void terminatingANamedInstanceLeavesTheOthersTheirIdsAndAddresses() { String id = emr("RunJobFlow", "{\"Name\":\"named\",\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true," diff --git a/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java b/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java index 178b655b2b..f7a34b2f19 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java @@ -755,6 +755,31 @@ class EmrServiceContainerStepsTest { assertEquals("ec2-203-0-113-1.compute-1.amazonaws.com", primary.getPublicDnsName()); } + @Test + void aNodeOfAGroupWithItsOwnAmiRunsThatAmiAndHasThePublicAddressItsNameNames() { + EmrCluster requested = cluster("own-ami", true); + requested.setCustomAmiId("ami-0000000000000c1a5"); + EmrInstanceGroup master = new EmrInstanceGroup(); + master.setInstanceGroupType("MASTER"); + master.setInstanceType("m5.xlarge"); + master.setRequestedInstanceCount(1); + EmrInstanceGroup core = new EmrInstanceGroup(); + core.setInstanceGroupType("CORE"); + core.setInstanceType("m5.xlarge"); + core.setRequestedInstanceCount(1); + core.setCustomAmiId("ami-00000000000000c0e"); + requested.setInstanceGroups(new ArrayList<>(List.of(master, core))); + EmrCluster cluster = service.runJobFlow(requested, REGION); + + Instance primary = service.nodeInstance(cluster, "111111111111", 0, 1); + Instance coreNode = service.nodeInstance(cluster, "111111111111", 1, 1); + + assertEquals("ami-0000000000000c1a5", primary.getImageId()); + assertEquals("ami-00000000000000c0e", coreNode.getImageId()); + assertEquals("203.0.113.2", coreNode.getPublicIpAddress()); + assertEquals("ec2-203-0-113-2.compute-1.amazonaws.com", coreNode.getPublicDnsName()); + } + @Test void aRelayThatCannotStartFailsTheStepThatWouldReadIt() { fixture.clusterStorage.metadata = true; diff --git a/src/test/java/io/floci/aws/services/emr/EmrServiceTest.java b/src/test/java/io/floci/aws/services/emr/EmrServiceTest.java index 044236d06d..d7ac92cfff 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceTest.java @@ -17,10 +17,12 @@ import org.junit.jupiter.api.function.Executable; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.PrimitiveIterator; +import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @@ -973,6 +975,25 @@ class EmrServiceTest { assertEquals(Map.of("ErrorCode", "INVALID_RELEASE_LABEL"), refused.getExtendedData()); } + @Test + void publicAddressesStayValidPastTheDocumentationRangeAndVolumeIdsDifferBetweenClusters() { + assertEquals("203.0.113.1", EmrService.publicIpAddress(1)); + assertEquals("203.0.113.254", EmrService.publicIpAddress(254)); + assertEquals("100.64.0.1", EmrService.publicIpAddress(255)); + assertEquals("100.64.1.1", EmrService.publicIpAddress(509)); + assertEquals("100.65.0.1", EmrService.publicIpAddress(255 + 254 * 256)); + Set addresses = LongStream.rangeClosed(1, 70_000).mapToObj(EmrService::publicIpAddress) + .collect(Collectors.toSet()); + assertEquals(70_000, addresses.size(), "no two instances share an address"); + assertTrue(addresses.stream().allMatch(address -> Arrays.stream(address.split("\\.")) + .mapToInt(Integer::parseInt).allMatch(octet -> octet >= 0 && octet <= 255)), "every octet is a byte"); + + String first = EmrService.ebsVolumeId("j-AAAAAAAAAAAAA", 1, 0); + assertTrue(first.matches("vol-[0-9a-f]{17}"), first); + assertFalse(first.equals(EmrService.ebsVolumeId("j-BBBBBBBBBBBBB", 1, 0)), "two clusters' volumes differ"); + assertFalse(first.equals(EmrService.ebsVolumeId("j-AAAAAAAAAAAAA", 1, 1)), "an instance's volumes differ"); + } + private static List ids(List steps) { return steps.stream().map(EmrStep::getId).toList(); } diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index 9d4b8d2a59..36b5e7544b 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -235,7 +235,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::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`, a group''s `EbsConfiguration` and `CustomAmiId` 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::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::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'