From 4595e8d1ef352d574d0c6ec44e50a25ba2ccda5f Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:45:08 -0400 Subject: [PATCH] fix(emr): terminate the instances ModifyInstanceGroups' EC2InstanceIdsToTerminate names (#9142) ModifyInstanceGroups ignored EC2InstanceIdsToTerminate, "The Amazon EC2 InstanceIds to terminate. After you terminate the instances, the instance group will not return to its original requested size." Floci's instances had no identity of their own: their ids and addresses followed their place in their group, so a group could only shrink from its end. Each instance group now keeps the ordinals of the instances those ids ended, and its instances take the first ordinals that are not among them. The named instances leave ListInstances and, in the docker runner mode, take their core or task node with them, HDFS moving its blocks first, as nodes are named by group and ordinal. The group's requested and running counts go down by as many. Its other instances keep their ids, addresses and nodes, as do the cluster's other groups', and an instance the group gets later takes a new ordinal, not an ended one's. An InstanceCount beside them is the group's size after that. An id that is not one of the group's instances is refused with ValidationException, as ModifyInstanceGroups' other refusals are recorded, and a MASTER group's with the refusal its count gets; AWS's wording for these is not documented, so it is Floci's. --- docs/services/emr.md | 10 +- .../io/floci/aws/services/emr/EmrHandler.java | 65 +++++-- .../io/floci/aws/services/emr/EmrService.java | 159 ++++++++++++++++-- .../services/emr/model/EmrInstanceGroup.java | 11 ++ .../emr/EmrResizeIntegrationTest.java | 56 ++++++ .../aws/services/emr/EmrServiceTest.java | 70 ++++++++ 6 files changed, 340 insertions(+), 31 deletions(-) diff --git a/docs/services/emr.md b/docs/services/emr.md index 73697c08b7..cbce7bf0cf 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -154,7 +154,15 @@ synthetic IDs and addresses of the `MASTER` group's or fleet's instance first, so the primary node keeps `i-00000000000000001` and `10.0.0.1`, as `DescribeCluster`'s `MasterPublicDnsName` says, while the others resize, and every other instance's private address is `10..0.`, its group's or fleet's number in the cluster and its own in it, so it too stays while -another resizes. An instance fleet has an instance for each unit of its capacity, its on-demand ones first, each of the +another resizes. `ModifyInstanceGroups`' `EC2InstanceIdsToTerminate` ends those instances of a group, which leave the +listing and, in the `docker` runner mode, take their core or task node with them, its HDFS blocks moved first; "After +you terminate the instances, the instance group will not return to its original requested size", so the group's +requested and running counts go down by as many. The group's other instances keep their IDs, addresses and nodes, as +do the cluster's other groups', and an instance the group gets later takes a new ID, not an ended one's. An +`InstanceCount` beside them is the group's size after that. An ID that is not one of the group's instances is refused +with `ValidationException`, and a `MASTER` group's with `InvalidRequestException`, as its count is; AWS's wording for +these is not documented, so it is Floci's. An instance fleet has an instance for each unit of its capacity, its +on-demand ones first, each of the first instance type in its `InstanceTypeConfigs`. `InstanceGroupId` and `InstanceGroupTypes` keep instance groups' instances, `InstanceFleetId` and `InstanceFleetType` instance fleets', and a call's filters all apply together. `ListInstances` retains each group's or fleet's 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 3006185399..cc01a7244b 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrHandler.java +++ b/src/main/java/io/floci/aws/services/emr/EmrHandler.java @@ -38,6 +38,7 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.PrimitiveIterator; /** * EMR (elasticmapreduce) JSON 1.1 handler. Dispatched from {@link AwsJson11Controller} @@ -425,6 +426,24 @@ public class EmrHandler { return value.asText(); } + // EC2InstanceIdsToTerminate, a list of strings in the model; another JSON type is refused as string() refuses one. + private static List instanceIds(JsonNode value) { + if (value.isMissingNode() || value.isNull()) { + return null; + } + List ids = new ArrayList<>(); + if (value.isArray()) { + for (JsonNode id : value) { + if (!id.isTextual()) { + throw malformed("EC2InstanceIdsToTerminate must be a list of strings"); + } + ids.add(id.asText()); + } + return ids; + } + throw malformed("EC2InstanceIdsToTerminate must be a list of strings"); + } + private static Long longOrNull(JsonNode value, String member) { if (value.isMissingNode() || value.isNull()) { return null; @@ -1003,13 +1022,7 @@ public class EmrHandler { long start = skip; int page = 0; List listed = listedInstances(cluster, terminated); - ListedInstances primary = listed.stream().filter(set -> set.number() == 0).findFirst().orElse(null); - long next = primary == null ? 1 : 1 + primary.count(); for (ListedInstances set : listed) { - long first = set == primary ? 1 : next; - if (set != primary) { - next += set.count(); - } if (!set.matches(groupId, groupTypes, fleetId, fleetType) || !states.isEmpty() && !states.contains(set.state())) { continue; @@ -1018,11 +1031,14 @@ public class EmrHandler { skip -= set.count(); continue; } - for (long ordinal = skip + 1; ordinal <= set.count(); ordinal++) { + long first = EmrService.firstIndex(listed, set); + PrimitiveIterator.OfLong ordinals = set.ordinalsFrom(skip + 1); + 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)); page++; } @@ -1056,9 +1072,11 @@ public class EmrHandler { List groups = cluster.getInstanceGroups(); for (EmrInstanceGroup group : groups) { int count = listedInstanceCount(group, terminated); + // All on the group's market, whatever their ordinals. listed.add(new ListedInstances(group.getId(), null, group.getInstanceGroupType(), group.getInstanceType(), - EmrService.groupNumber(groups, group), count, group.getMarket(), count, - instanceState(group.getState(), beingProvisioned(group), terminated))); + EmrService.groupNumber(groups, group), count, group.getMarket(), Long.MAX_VALUE, + instanceState(group.getState(), beingProvisioned(group), terminated), + List.copyOf(group.getTerminatedOrdinals()))); } List fleets = cluster.getInstanceFleets(); for (EmrInstanceFleet fleet : fleets) { @@ -1071,7 +1089,7 @@ public class EmrHandler { listed.add(new ListedInstances(null, fleet.getId(), fleet.getInstanceFleetType(), fleet.getInstanceTypes().isEmpty() ? null : fleet.getInstanceTypes().getFirst(), EmrService.fleetNumber(fleets, fleet), onDemand + spot, "ON_DEMAND", onDemand, - instanceState(fleet.getState(), provisioning, terminated))); + instanceState(fleet.getState(), provisioning, terminated), List.of())); } return listed; } @@ -1108,15 +1126,36 @@ public class EmrHandler { /** * The instances ListInstances lists for one instance group or fleet: {@code count} of them, with addresses numbered * {@code number}, those after the first {@code spotAfter} on the spot market and the others on {@code market}, each - * in {@code state}. + * in {@code state}, none of them at the ordinals {@code terminated} (ascending), which EC2InstanceIdsToTerminate + * ended. */ record ListedInstances(String groupId, String fleetId, String type, String instanceType, int number, long count, - String market, long spotAfter, String state) { + String market, long spotAfter, String state, List terminated) { String marketOf(long ordinal) { return ordinal <= spotAfter ? market : "SPOT"; } + /** The ordinal of their {@code k}-th instance, counted from 1 ({@link EmrService#ordinalAt}). */ + long ordinalAt(long k) { + return EmrService.ordinalAt(terminated, k); + } + + /** Their ordinals from their {@code k}-th instance's on ({@link EmrService#ordinalsFrom}). */ + PrimitiveIterator.OfLong ordinalsFrom(long k) { + return EmrService.ordinalsFrom(terminated, k); + } + + /** + * How many places they take in the cluster's instance numbering: up to their last instance's ordinal, or a + * terminated instance's above it, which keeps its place, so that ending a group's last instance moves no other + * group's ids onto it. + */ + long span() { + long live = count == 0 ? 0 : ordinalAt(count); + return terminated.isEmpty() ? live : Math.max(live, terminated.getLast()); + } + /** Whether ListInstances' filters keep them: the group ones keep groups' instances, the fleet ones fleets'. */ boolean matches(String instanceGroupId, List groupTypes, String instanceFleetId, String fleetType) { return (instanceGroupId == null || instanceGroupId.equals(groupId)) @@ -1281,7 +1320,7 @@ public class EmrHandler { g.path("InstanceGroupId").asText(null), count.isMissingNode() || count.isNull() ? null : count.asInt(), configurations.isArray() ? configurations.toString() : null, - g.path("ReconfigurationType").asText(null))); + g.path("ReconfigurationType").asText(null), instanceIds(g.path("EC2InstanceIdsToTerminate")))); } } service.modifyInstanceGroups(text(request, "ClusterId"), region, modifications); 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 620ca5a9aa..c7aeff7eb2 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrService.java @@ -64,6 +64,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; +import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; @@ -74,6 +75,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.PrimitiveIterator; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; @@ -1449,21 +1451,29 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear } /** - * One InstanceGroupModifyConfig: a null count or configurations leaves that setting as it is, and a null - * reconfiguration type is OVERWRITE. + * One InstanceGroupModifyConfig: a null count or configurations leaves that setting as it is, a null + * reconfiguration type is OVERWRITE, and {@code instancesToTerminate} are EC2InstanceIdsToTerminate, none for null. */ public record InstanceGroupModification(String instanceGroupId, Integer instanceCount, String configurations, - String reconfigurationType) { + String reconfigurationType, List instancesToTerminate) { public InstanceGroupModification(String instanceGroupId, Integer instanceCount, String configurations) { - this(instanceGroupId, instanceCount, configurations, null); + this(instanceGroupId, instanceCount, configurations, null, null); + } + + public InstanceGroupModification(String instanceGroupId, Integer instanceCount, String configurations, + String reconfigurationType) { + this(instanceGroupId, instanceCount, configurations, reconfigurationType, null); } } /** * Resizes or reconfigures instance groups in place. ClusterId is optional in the request, so * without it each group is looked up across the account's clusters in the Region. Every modification is - * checked before any is applied. + * checked before any is applied. A group's EC2InstanceIdsToTerminate end those of its instances: "After you + * terminate the instances, the instance group will not return to its original requested size", so its requested + * count goes down by as many, and the others keep their ids, addresses and nodes. An InstanceCount beside them is + * the group's size after that. */ public void modifyInstanceGroups(String clusterId, String region, List modifications) { run(() -> { @@ -1472,6 +1482,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear } Map touched = new LinkedHashMap<>(); List groups = new ArrayList<>(); + List> terminations = new ArrayList<>(); for (int position = 1; position <= modifications.size(); position++) { InstanceGroupModification mod = modifications.get(position - 1); EmrCluster found = clusterId != null @@ -1495,11 +1506,23 @@ 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())); groups.add(group); } for (int i = 0; i < modifications.size(); i++) { InstanceGroupModification mod = modifications.get(i); EmrInstanceGroup group = groups.get(i); + // Those another entry for the same group has not ended already. + List ended = terminations.get(i).stream() + .filter(ordinal -> !group.getTerminatedOrdinals().contains(ordinal)).toList(); + if (!ended.isEmpty()) { + List ordinals = new ArrayList<>(group.getTerminatedOrdinals()); + ordinals.addAll(ended); + Collections.sort(ordinals); + group.setTerminatedOrdinals(ordinals); + group.setRequestedInstanceCount(Math.max(0, group.getRequestedInstanceCount() - ended.size())); + group.setRunningInstanceCount(Math.max(0, group.getRunningInstanceCount() - ended.size())); + } if (mod.instanceCount() != null) { group.setRequestedInstanceCount(mod.instanceCount()); group.setRunningInstanceCount(mod.instanceCount()); @@ -1516,6 +1539,66 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear }); } + /** + * The ordinals of the group's instances that {@code instanceIds} name, each one of its instances now as + * ListInstances gives it; none for no ids. A master group's are refused as its count is, and an id that is not one + * of the group's instances with ValidationException, as ModifyInstanceGroups' other refusals are recorded; no + * source gives AWS's wording, so it is Floci's. + */ + private static List ordinalsToTerminate(EmrCluster cluster, EmrInstanceGroup group, + List instanceIds) { + if (instanceIds == null || instanceIds.isEmpty()) { + return List.of(); + } + 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); + } + } + } + List ordinals = new ArrayList<>(); + for (String instanceId : new LinkedHashSet<>(instanceIds)) { + Integer ordinal = current.get(instanceId); + if (ordinal == null) { + throw new AwsException("ValidationException", "Instance " + instanceId + + " is not a running instance of instance group " + group.getId() + ".", 400); + } + ordinals.add(ordinal); + } + return ordinals; + } + + /** + * 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. + */ + static long firstIndex(List listed, EmrHandler.ListedInstances set) { + EmrHandler.ListedInstances primary = listed.stream().filter(other -> other.number() == 0).findFirst() + .orElse(null); + if (set == primary) { + return 1; + } + long next = primary == null ? 1 : 1 + primary.span(); + for (EmrHandler.ListedInstances other : listed) { + if (other == set) { + return next; + } + if (other != primary) { + next += other.span(); + } + } + throw new IllegalArgumentException("The instances are not the cluster's"); + } + /** * A reconfiguration type is OVERWRITE or MERGE, the model's enum. MERGE is "supported for Amazon EMR releases * 5.35.0 and 6.6.0 and later", and OVERWRITE is "the only one available in Amazon EMR releases earlier than 5.35.0 @@ -3230,7 +3313,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear count = isCore ? Math.max(count, floor) : count; asked += Math.max(count, 0); addNodes(cluster, groupNumber(cluster.getInstanceGroups(), group), count, isCore, isCore ? core : task, - maxWorkerNodes); + maxWorkerNodes, group.getTerminatedOrdinals()); } } for (EmrInstanceFleet fleet : cluster.getInstanceFleets()) { @@ -3240,7 +3323,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear long capacity = (long) fleet.getTargetOnDemandCapacity() + fleet.getTargetSpotCapacity(); long count = isCore ? Math.max(capacity, floor) : capacity; asked += Math.max(count, 0); - addNodes(cluster, number, count, isCore, isCore ? core : task, maxWorkerNodes); + addNodes(cluster, number, count, isCore, isCore ? core : task, maxWorkerNodes, List.of()); } } List nodes = new ArrayList<>(core); @@ -3253,10 +3336,12 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear return nodes; } - // Up to count nodes of the group, as long as the list holds fewer than limit. + // Up to count nodes of the group, as long as the list holds fewer than limit, none at an ordinal terminated holds. private static void addNodes(EmrCluster cluster, int group, long count, boolean core, - List nodes, int limit) { - for (int ordinal = 1; ordinal <= count && nodes.size() < limit; ordinal++) { + List nodes, int limit, List terminated) { + PrimitiveIterator.OfLong ordinals = ordinalsFrom(terminated, 1); + for (long k = 1; k <= count && nodes.size() < limit; k++) { + long ordinal = ordinals.nextLong(); String id = group + "-" + ordinal; nodes.add(new ClusterStorage.Node(id, AwsRegions.ec2PrivateIpDnsName(privateIpAddress(group, ordinal), cluster.getRegion()), core, @@ -3808,6 +3893,52 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear return AwsEndpoints.ec2PublicDns("203.0.113." + index, region); } + /** + * The ordinal, counted from 1, of a group's {@code k}-th instance, when EC2InstanceIdsToTerminate has ended its + * instances {@code terminated} (ascending): the {@code k}-th ordinal that is not one of them, so an instance keeps + * its ordinal, and with it its id and addresses, while another of its group is ended. + */ + static long ordinalAt(List terminated, long k) { + long ordinal = k; + for (int gone : terminated) { + if (gone > ordinal) { + break; + } + ordinal++; + } + return ordinal; + } + + /** + * A group's instance ordinals from its {@code k}-th on, in order, as {@link #ordinalAt} gives each: the terminated + * ones before the {@code k}-th are passed once, and each later one as the walk reaches it, so a page of instances + * costs its own length and not that times the group's terminations. + */ + static PrimitiveIterator.OfLong ordinalsFrom(List terminated, long k) { + long first = ordinalAt(terminated, k); + return new PrimitiveIterator.OfLong() { + private long next = first; + // The terminated ordinals passed so far: as many as the first ordinal is past k. + private int passed = (int) (first - k); + + @Override + public boolean hasNext() { + return true; + } + + @Override + public long nextLong() { + long current = next; + next = current + 1; + while (passed < terminated.size() && terminated.get(passed) == next) { + next++; + passed++; + } + return current; + } + }; + } + /** * The private IPv4 address of the instance {@code ordinal}, counted from 1, of a cluster's instance group numbered * {@code group}: an instance keeps it while its cluster's other groups resize, as an EC2 instance does. @@ -3854,17 +3985,11 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear */ Instance nodeInstance(EmrCluster cluster, String accountId, int group, long ordinal) { List listed = EmrHandler.listedInstances(cluster, false); - EmrHandler.ListedInstances primary = listed.stream().filter(set -> set.number() == 0).findFirst().orElse(null); - long next = primary == null ? 1 : 1 + primary.count(); long index = ordinal; String instanceType = null; for (EmrHandler.ListedInstances set : listed) { - long first = set == primary ? 1 : next; - if (set != primary) { - next += set.count(); - } if (set.number() == group) { - index = first + ordinal - 1; + index = firstIndex(listed, set) + ordinal - 1; instanceType = set.instanceType(); break; } 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 8e01a79336..eb2a99c8b7 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 @@ -2,6 +2,9 @@ package io.floci.aws.services.emr.model; import io.quarkus.runtime.annotations.RegisterForReflection; +import java.util.ArrayList; +import java.util.List; + /** An EMR instance group (MASTER | CORE | TASK). */ @RegisterForReflection public class EmrInstanceGroup { @@ -15,6 +18,9 @@ public class EmrInstanceGroup { private int requestedInstanceCount; private int runningInstanceCount; private int terminatedInstanceCount; + // The ordinals of its instances EC2InstanceIdsToTerminate ended, ascending: none of its instances takes them again, + // so the others keep theirs. Floci's own. + private List terminatedOrdinals = new ArrayList<>(); private String state; /** The AutoScalingPolicy as given (Constraints and Rules), raw JSON; null when none is attached. */ private String autoScalingPolicy; @@ -63,6 +69,11 @@ public class EmrInstanceGroup { this.terminatedInstanceCount = terminatedInstanceCount; } + public List getTerminatedOrdinals() { return terminatedOrdinals; } + public void setTerminatedOrdinals(List terminatedOrdinals) { + this.terminatedOrdinals = terminatedOrdinals != null ? terminatedOrdinals : new ArrayList<>(); + } + public String getState() { return state; } public void setState(String state) { this.state = state; } 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 d928118fce..7d09c77e0f 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrResizeIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrResizeIntegrationTest.java @@ -17,6 +17,8 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; 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; /** * EMR instance group and fleet resizing and bootstrap action listing over the AWS JSON 1.1 wire @@ -510,4 +512,58 @@ class EmrResizeIntegrationTest { .body("__type", equalTo("ValidationException")) .body("message", containsString("'instanceGroups.1.member.reconfigurationType'")); } + + /** + * 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 terminatingANamedInstanceLeavesTheOthersTheirIdsAndAddresses() { + String id = emr("RunJobFlow", "{\"Name\":\"named\",\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true," + + "\"InstanceGroups\":[{\"InstanceRole\":\"MASTER\",\"InstanceType\":\"m5.xlarge\"," + + "\"InstanceCount\":1},{\"InstanceRole\":\"CORE\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":3}," + + "{\"InstanceRole\":\"TASK\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1}]}}") + .then().statusCode(200).extract().path("JobFlowId"); + try { + String cluster = "{\"ClusterId\":\"" + id + "\"}"; + String core = emr("ListInstanceGroups", cluster).jsonPath() + .getString("InstanceGroups.find { it.InstanceGroupType == 'CORE' }.Id"); + Response before = emr("ListInstances", cluster); + List ids = before.jsonPath().getList("Instances.Ec2InstanceId"); + List addresses = before.jsonPath().getList("Instances.PrivateIpAddress"); + String ended = ids.get(2); + + emr("ModifyInstanceGroups", "{\"ClusterId\":\"" + id + "\",\"InstanceGroups\":[{\"InstanceGroupId\":\"" + + core + "\",\"EC2InstanceIdsToTerminate\":[\"" + ended + "\"]}]}").then().statusCode(200); + + Response after = emr("ListInstances", cluster); + assertEquals(List.of(ids.get(0), ids.get(1), ids.get(3), ids.get(4)), + after.jsonPath().getList("Instances.Ec2InstanceId")); + assertEquals(List.of(addresses.get(0), addresses.get(1), addresses.get(3), addresses.get(4)), + after.jsonPath().getList("Instances.PrivateIpAddress")); + emr("ListInstanceGroups", cluster).then().statusCode(200) + .body("InstanceGroups.find { it.Id == '" + core + "' }.RequestedInstanceCount", equalTo(2)) + .body("InstanceGroups.find { it.Id == '" + core + "' }.RunningInstanceCount", equalTo(2)); + emr("ModifyInstanceGroups", "{\"ClusterId\":\"" + id + "\",\"InstanceGroups\":[{\"InstanceGroupId\":\"" + + core + "\",\"EC2InstanceIdsToTerminate\":[\"" + ended + "\"]}]}").then().statusCode(400) + .body("__type", equalTo("ValidationException")); + emr("ModifyInstanceGroups", "{\"ClusterId\":\"" + id + "\",\"InstanceGroups\":[{\"InstanceGroupId\":\"" + + core + "\",\"EC2InstanceIdsToTerminate\":\"" + ids.get(3) + "\"}]}").then().statusCode(400) + .body("__type", equalTo("SerializationException")); + // The group's last instance too: the task instance after it keeps its id. + emr("ModifyInstanceGroups", "{\"ClusterId\":\"" + id + "\",\"InstanceGroups\":[{\"InstanceGroupId\":\"" + + core + "\",\"EC2InstanceIdsToTerminate\":[\"" + ids.get(3) + "\"]}]}").then().statusCode(200); + assertEquals(List.of(ids.get(0), ids.get(1), ids.get(4)), + emr("ListInstances", cluster).jsonPath().getList("Instances.Ec2InstanceId")); + + emr("ModifyInstanceGroups", "{\"ClusterId\":\"" + id + "\",\"InstanceGroups\":[{\"InstanceGroupId\":\"" + + core + "\",\"InstanceCount\":3}]}").then().statusCode(200); + List grown = emr("ListInstances", "{\"ClusterId\":\"" + id + "\",\"InstanceGroupId\":\"" + core + + "\"}").jsonPath().getList("Instances.Ec2InstanceId"); + assertEquals(3, grown.size()); + assertFalse(grown.contains(ended), "an ended instance's id is not taken again"); + } finally { + emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + id + "\"]}").then().statusCode(200); + } + } } 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 a952d6eae5..044236d06d 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceTest.java @@ -20,9 +20,11 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.PrimitiveIterator; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import java.util.stream.LongStream; import static io.floci.aws.services.emr.EmrServiceFixture.REGION; import static io.floci.aws.services.emr.EmrServiceFixture.cluster; @@ -859,6 +861,74 @@ class EmrServiceTest { assertTrue(nodes.stream().allMatch(ClusterStorage.Node::core), nodes.toString()); } + /** + * EC2InstanceIdsToTerminate ends the instances it names: their nodes go, the group's other instances keep their ids + * and nodes, and one the group gets later takes a new ordinal, not an ended one's. + */ + @Test + void terminatingANamedInstanceTakesItsNodeAndLeavesTheOthersTheirs() { + EmrServiceFixture fixture = new EmrServiceFixture(0, 0, 0); + EmrService service = fixture.service; + EmrCluster requested = cluster("named", true); + requested.getInstanceGroups().addAll(List.of(group("MASTER", 1), group("CORE", 3))); + EmrCluster cluster = service.runJobFlow(requested, REGION); + String core = cluster.getInstanceGroups().get(1).getId(); + // The primary node is i-...1, and the core group's instances i-...2 to i-...4, ordinals 1 to 3. + String second = EmrService.ec2InstanceId(3); + + service.modifyInstanceGroups(cluster.getId(), REGION, List.of( + new EmrService.InstanceGroupModification(core, null, null, null, List.of(second)))); + + EmrCluster shrunk = service.describeCluster(cluster.getId()); + assertEquals(List.of("1-1", "1-3"), service.workerNodes(shrunk).stream().map(ClusterStorage.Node::id).toList()); + assertEquals(2, shrunk.getInstanceGroups().get(1).getRequestedInstanceCount()); + assertEquals(2, shrunk.getInstanceGroups().get(1).getRunningInstanceCount()); + AwsException again = assertThrows(AwsException.class, () -> service.modifyInstanceGroups(cluster.getId(), + REGION, List.of(new EmrService.InstanceGroupModification(core, null, null, null, List.of(second))))); + assertEquals("ValidationException", again.getErrorCode()); + AwsException master = assertThrows(AwsException.class, () -> service.modifyInstanceGroups(cluster.getId(), + REGION, List.of(new EmrService.InstanceGroupModification(cluster.getInstanceGroups().get(0).getId(), + null, null, null, List.of(EmrService.ec2InstanceId(1)))))); + assertEquals("InvalidRequestException", master.getErrorCode()); + + service.modifyInstanceGroups(cluster.getId(), REGION, + List.of(new EmrService.InstanceGroupModification(core, 3, null))); + assertEquals(List.of("1-1", "1-3", "1-4"), service.workerNodes(service.describeCluster(cluster.getId())) + .stream().map(ClusterStorage.Node::id).toList()); + } + + @Test + void anInstancesOrdinalSkipsThoseItsGroupEnded() { + assertEquals(List.of(1L, 4L, 5L, 7L), LongStream.rangeClosed(1, 4) + .map(k -> EmrService.ordinalAt(List.of(2, 3, 6), k)).boxed().toList()); + // The walk from any instance gives the same ordinals. + for (long k = 1; k <= 4; k++) { + PrimitiveIterator.OfLong walk = EmrService.ordinalsFrom(List.of(2, 3, 6), k); + for (long next = k; next <= 6; next++) { + assertEquals(EmrService.ordinalAt(List.of(2, 3, 6), next), walk.nextLong(), "from " + k); + } + } + } + + /** One group named twice with the same instance ends it once. */ + @Test + void anInstanceNamedTwiceInOneRequestIsEndedOnce() { + EmrServiceFixture fixture = new EmrServiceFixture(0, 0, 0); + EmrService service = fixture.service; + EmrCluster requested = cluster("twice", true); + requested.getInstanceGroups().addAll(List.of(group("MASTER", 1), group("CORE", 3))); + EmrCluster cluster = service.runJobFlow(requested, REGION); + String core = cluster.getInstanceGroups().get(1).getId(); + EmrService.InstanceGroupModification end = + new EmrService.InstanceGroupModification(core, null, null, null, List.of(EmrService.ec2InstanceId(3))); + + service.modifyInstanceGroups(cluster.getId(), REGION, List.of(end, end)); + + EmrCluster shrunk = service.describeCluster(cluster.getId()); + assertEquals(2, shrunk.getInstanceGroups().get(1).getRequestedInstanceCount()); + assertEquals(List.of("1-1", "1-3"), service.workerNodes(shrunk).stream().map(ClusterStorage.Node::id).toList()); + } + /** ModifyInstanceFleet's answer for a cluster that is starting or bootstrapping. */ private static void assertNotRunningOrWaiting(AwsException refused) { assertEquals("InvalidRequestException", refused.getErrorCode());