diff --git a/docs/services/emr.md b/docs/services/emr.md index 4851e41667..cdbb347cbc 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -86,10 +86,13 @@ does not exist.", as AWS does. Instance groups and fleets report `RUNNING` from the cluster's creation until it is `TERMINATED`. Then they report `TERMINATED` with zero running or provisioned capacity; their requested and target capacities remain recorded. `ListInstances` numbers the synthetic IDs and addresses of the `MASTER` -group's instance first, so the primary node keeps `i-00000000000000001` and `10.0.0.1`, as -`DescribeCluster`'s `MasterPublicDnsName` says, while the other groups resize, and every other instance's private -address is `10..0.`, its group's number in the cluster and its own in the group, so it too stays while -another group resizes; it retains each group's +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 +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 instances with their original synthetic IDs and `TERMINATED` status for 30 days after termination. New groups or fleets are rejected on terminated clusters. As on AWS, `ModifyInstanceGroups` answers `ValidationException` "An instance group may only be modified when the cluster is running or waiting." for a cluster in any other state, @@ -100,7 +103,16 @@ running or waiting." with `ErrorCode` `MODIFY_INSTANCE_FLEET_OF_RUNNING_JOBFLOW_ other state, such as `STARTING` or `BOOTSTRAPPING`. `AddInstanceFleet` gives a `TERMINATING` or `TERMINATED` cluster the "shutting down" answer, and `AddInstanceGroups` gives it as `ValidationException`, as `AddJobFlowSteps` does. `InstanceStates` filters the modeled `RUNNING` and -`TERMINATED` instances. +`TERMINATED` instances. As `ListInstances` "Provides information for all active Amazon EC2 instances and Amazon EC2 +instances terminated in the last 30 days, up to a maximum of 2,000", a call lists at most 2,000 and gives a `Marker` +for the next; a `Marker` no call gave is refused with `InvalidRequestException`. +A cluster has instance groups or instance fleets, never both, as "instance fleets and instance groups cannot coexist in a +cluster": `RunJobFlow` with both is refused with `ValidationException` "The RunJobFlow request can contain +InstanceFleets parameters or InstanceGroups parameters, but not both.", the API reference's own words, and +`AddInstanceGroups` on a cluster with instance fleets with `ValidationException`, `AddInstanceFleet` on one with +instance groups with `InvalidRequestException`, each saying the cluster uses the other kind; AWS's wording for these is +not documented, so it is Floci's. A fleet without its `InstanceFleetType`, or with an `InstanceTypeConfigs` member +without its `InstanceType`, both required, is refused with the framework's `ValidationException`. A cluster that is `TERMINATING`, `TERMINATED` or `TERMINATED_WITH_ERRORS` also refuses `ModifyCluster`, the four `Set*` setters, and `Put` and `Remove` of its managed scaling, auto-termination and automatic @@ -244,8 +256,8 @@ holding the driver and its executors, or a command or a script. The cluster itse Each core and task node is a container of its own on that network, `emr--node--`, with its data in a volume of its own: "Core nodes run the Data Node daemon", "a core node runs YARN NodeManager daemons, Hadoop MapReduce tasks, and Spark executors", and "Task nodes don't run the Data Node daemon". Its name on the network is the - private DNS name `ListInstances` gives it, which YARN and HDFS know it by; an instance fleet's nodes are named the same - way, though `ListInstances` does not list a fleet's instances. How many there are follows the instance + private DNS name `ListInstances` gives it, which YARN and HDFS know it by, an instance fleet's as an instance group's. + How many there are follows the instance groups' counts or the instance fleets' target capacities, at most `yarn-max-worker-nodes`, 4 by default, core nodes first, as each costs 300 to 800 MB while idle; with 0 the cluster runs on its primary node alone. `ModifyInstanceGroups`, `AddInstanceGroups`, `ModifyInstanceFleet` and `AddInstanceFleet` reach the nodes of a cluster a step has started them @@ -486,8 +498,9 @@ holding the driver and its executors, or a command or a script. The cluster itse - **No more nodes than `yarn-max-worker-nodes`.** A cluster that names more core and task instances runs that many, core nodes first, while `ListInstances` still lists them all. Its core and task nodes offer the same capacity whatever their instance type. -- **An instance fleet's unit of capacity is one node.** Floci does not read a fleet's instance types, so it has no - `WeightedCapacity` to divide its target capacity by. +- **An instance fleet's unit of capacity is one instance.** Floci does not choose among a fleet's instance types as EMR + does: `ListInstances` gives each of its instances the first in its `InstanceTypeConfigs`, and its target capacity is + divided by no `WeightedCapacity`, so it has an instance and a node for each unit. - **A resize shows at once.** An instance group is `RUNNING` with its new count, and an instance fleet its new capacity, as soon as the resize is asked for, while the nodes take a few seconds to follow, or longer to decommission. A core group shrunk below the copies HDFS keeps says the count asked for, while its nodes stop at the copies; EMR documents 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 f1cdd0a273..0646080d10 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrHandler.java +++ b/src/main/java/io/floci/aws/services/emr/EmrHandler.java @@ -40,6 +40,9 @@ import java.util.Map; public class EmrHandler { private static final Logger LOG = Logger.getLogger(EmrHandler.class); + // ListInstances "Provides information for all active Amazon EC2 instances and Amazon EC2 instances terminated in the + // last 30 days, up to a maximum of 2,000": that many to a call, the rest after its Marker. + static final int INSTANCES_PER_PAGE = 2000; private final EmrService service; private final ObjectMapper objectMapper; @@ -295,7 +298,11 @@ public class EmrHandler { } private Response handleAddInstanceFleet(JsonNode request) { - EmrInstanceFleet fleet = parseInstanceFleet(request.path("InstanceFleet")); + List violations = new ArrayList<>(); + EmrInstanceFleet fleet = parseInstanceFleet(request.path("InstanceFleet"), "instanceFleet", violations); + if (!violations.isEmpty()) { + throw SmithyValidationErrors.validationException(violations); + } String id = service.addInstanceFleet(text(request, "ClusterId"), fleet); ObjectNode response = objectMapper.createObjectNode(); response.put("ClusterId", text(request, "ClusterId")); @@ -323,27 +330,106 @@ public class EmrHandler { || (terminated && !withinTerminatedInstanceRetention(cluster.getEndDateTime(), Instant.now()))) { return Response.ok(response).build(); } - // Listed in their groups' order, the first MASTER group's instances numbered first, so the primary node keeps - // its id and address, DescribeCluster's MasterPublicDnsName, while the other groups resize, as an instance - // does; any other group's follow, each after those before it. - EmrInstanceGroup primary = cluster.getInstanceGroups().stream().filter(EmrService::isMasterGroup) - .findFirst().orElse(null); - int next = primary == null ? 1 : 1 + listedInstanceCount(primary, terminated); - for (EmrInstanceGroup group : cluster.getInstanceGroups()) { - int count = listedInstanceCount(group, terminated); - int first = group == primary ? 1 : next; - int number = EmrService.groupNumber(cluster.getInstanceGroups(), group); - for (int i = 0; i < count; i++) { - arr.add(syntheticInstanceNode(cluster, group, first + i, EmrService.privateIpAddress(number, i + 1), - terminated)); + String groupId = text(request, "InstanceGroupId"); + List groupTypes = stringList(request.path("InstanceGroupTypes")); + String fleetId = text(request, "InstanceFleetId"); + String fleetType = text(request, "InstanceFleetType"); + // Listed in their groups' or fleets' order, the primary node's group or fleet numbered first, so the primary + // node keeps its id and address, DescribeCluster's MasterPublicDnsName, while the others resize, as an + // instance does; any other's follow, each after those before it. Only the page asked for is built, so a + // group or fleet of any size costs a page. Counted in longs, as a fleet's two capacities add up past an int. + long skip = instancesMarker(text(request, "Marker")); + 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 (group != primary) { - next += count; + if (!set.matches(groupId, groupTypes, fleetId, fleetType)) { + continue; } + if (skip >= set.count()) { + skip -= set.count(); + continue; + } + for (long ordinal = skip + 1; ordinal <= set.count(); ordinal++) { + if (page == INSTANCES_PER_PAGE) { + response.put("Marker", String.valueOf(start + page)); + return Response.ok(response).build(); + } + arr.add(syntheticInstanceNode(cluster, set, first + ordinal - 1, ordinal, terminated)); + page++; + } + skip = 0; } return Response.ok(response).build(); } + // How many of a listing's instances its Marker passes, the count the page before it ended at; none without one. + private static long instancesMarker(String marker) { + if (marker == null) { + return 0; + } + try { + long passed = Long.parseLong(marker); + if (passed >= 0) { + return passed; + } + } catch (NumberFormatException e) { + // Refused below, as any marker no page gave. + } + throw new AwsException("InvalidRequestException", "Invalid pagination token: " + marker, 400); + } + + /** + * A cluster's instance groups' and fleets' instances, in the cluster's order. A fleet has one instance for each unit + * of its capacity, as its nodes do, its on-demand ones first, each of its first instance type. + */ + static List listedInstances(EmrCluster cluster, boolean terminated) { + List listed = new ArrayList<>(); + List groups = cluster.getInstanceGroups(); + for (EmrInstanceGroup group : groups) { + int count = listedInstanceCount(group, terminated); + listed.add(new ListedInstances(group.getId(), null, group.getInstanceGroupType(), group.getInstanceType(), + EmrService.groupNumber(groups, group), count, group.getMarket(), count)); + } + List fleets = cluster.getInstanceFleets(); + for (EmrInstanceFleet fleet : fleets) { + // An ended fleet has no capacity provisioned any more; its targets, which it can no longer change, say what + // it ran. + long onDemand = terminated ? fleet.getTargetOnDemandCapacity() : fleet.getProvisionedOnDemandCapacity(); + long spot = terminated ? fleet.getTargetSpotCapacity() : fleet.getProvisionedSpotCapacity(); + 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)); + } + return listed; + } + + /** + * 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}. + */ + record ListedInstances(String groupId, String fleetId, String type, String instanceType, int number, long count, + String market, long spotAfter) { + + String marketOf(long ordinal) { + return ordinal <= spotAfter ? market : "SPOT"; + } + + /** 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)) + && (groupTypes.isEmpty() || (groupId != null && groupTypes.contains(type))) + && (instanceFleetId == null || instanceFleetId.equals(fleetId)) + && (fleetType == null || (fleetId != null && fleetType.equals(type))); + } + } + static boolean withinTerminatedInstanceRetention(Instant endedAt, Instant now) { return endedAt != null && !endedAt.isBefore(now.minus(30, ChronoUnit.DAYS)); } @@ -754,19 +840,27 @@ public class EmrHandler { return node; } - private ObjectNode syntheticInstanceNode(EmrCluster cluster, EmrInstanceGroup group, int index, String privateIp, + private ObjectNode syntheticInstanceNode(EmrCluster cluster, ListedInstances set, long index, long ordinal, boolean terminated) { + 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", AwsEndpoints.ec2PublicDns("203.0.113." + index, cluster.getRegion())); node.put("PrivateDnsName", AwsRegions.ec2PrivateIpDnsName(privateIp, cluster.getRegion())); node.put("PrivateIpAddress", privateIp); - node.put("InstanceGroupId", group.getId()); - if (group.getMarket() != null) { - node.put("Market", group.getMarket()); + if (set.groupId() != null) { + node.put("InstanceGroupId", set.groupId()); + } + if (set.fleetId() != null) { + node.put("InstanceFleetId", set.fleetId()); + } + if (set.marketOf(ordinal) != null) { + node.put("Market", set.marketOf(ordinal)); + } + if (set.instanceType() != null) { + node.put("InstanceType", set.instanceType()); } - node.put("InstanceType", group.getInstanceType()); node.putObject("Status").put("State", terminated ? "TERMINATED" : "RUNNING"); return node; } @@ -840,16 +934,41 @@ public class EmrHandler { if (!fleetsNode.isArray()) { return fleets; } + List violations = new ArrayList<>(); + int position = 1; for (JsonNode f : fleetsNode) { - fleets.add(parseInstanceFleet(f)); + fleets.add(parseInstanceFleet(f, "instances.instanceFleets." + position++ + ".member", violations)); + } + if (!violations.isEmpty()) { + throw SmithyValidationErrors.validationException(violations); } return fleets; } - private EmrInstanceFleet parseInstanceFleet(JsonNode f) { + /** + * An InstanceFleetConfig at {@code path} in its request, as the framework names a member's place; one without its + * required InstanceFleetType, or with an InstanceTypeConfigs member without its required InstanceType, adds to + * {@code violations}, as the framework refuses such a request. + */ + private EmrInstanceFleet parseInstanceFleet(JsonNode f, String path, List violations) { EmrInstanceFleet fleet = new EmrInstanceFleet(); fleet.setName(f.path("Name").asText(null)); fleet.setInstanceFleetType(f.path("InstanceFleetType").asText(null)); + if (fleet.getInstanceFleetType() == null) { + violations.add(SmithyValidationErrors.notNull(path + ".instanceFleetType")); + } + List instanceTypes = new ArrayList<>(); + int position = 1; + for (JsonNode config : f.path("InstanceTypeConfigs")) { + String instanceType = config.path("InstanceType").asText(null); + if (instanceType == null) { + violations.add(SmithyValidationErrors.notNull( + path + ".instanceTypeConfigs." + position + ".member.instanceType")); + } + instanceTypes.add(instanceType); + position++; + } + fleet.setInstanceTypes(instanceTypes); fleet.setTargetOnDemandCapacity(f.path("TargetOnDemandCapacity").asInt(0)); fleet.setTargetSpotCapacity(f.path("TargetSpotCapacity").asInt(0)); return fleet; 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 5e5afedb52..ea32e2aeed 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrService.java @@ -62,6 +62,7 @@ import java.util.function.BiFunction; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.Function; +import java.util.function.Predicate; import java.util.function.Supplier; /** @@ -369,6 +370,12 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear if (cluster.getName() == null) { throw SmithyValidationErrors.validationException(SmithyValidationErrors.notNull("name")); } + // "The RunJobFlow request can contain InstanceFleets parameters or InstanceGroups parameters, but not + // both", as "instance fleets and instance groups cannot coexist in a cluster". + if (!cluster.getInstanceGroups().isEmpty() && !cluster.getInstanceFleets().isEmpty()) { + throw new AwsException("ValidationException", "The RunJobFlow request can contain InstanceFleets" + + " parameters or InstanceGroups parameters, but not both.", 400); + } String id = "j-" + randomId(13); cluster.setId(id); cluster.setRegion(region); @@ -569,6 +576,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear return call(() -> { EmrCluster cluster = requireCluster(clusterId); rejectShutDownCluster(cluster, EmrService::jobFlowShutDownValidation); + if (!cluster.getInstanceFleets().isEmpty()) { + throw new AwsException("ValidationException", fleetsAndGroupsApart(clusterId, "instance fleets"), 400); + } List ids = new ArrayList<>(); for (EmrInstanceGroup group : groups) { group.setId("ig-" + randomId(13)); @@ -668,6 +678,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear return call(() -> { EmrCluster cluster = requireCluster(clusterId); rejectShutDownCluster(cluster, EmrService::jobFlowShutDown); + if (!cluster.getInstanceGroups().isEmpty()) { + throw invalid(fleetsAndGroupsApart(clusterId, "instance groups")); + } fleet.setId("if-" + randomId(13)); fleet.setProvisionedOnDemandCapacity(fleet.getTargetOnDemandCapacity()); fleet.setProvisionedSpotCapacity(fleet.getTargetSpotCapacity()); @@ -1134,6 +1147,14 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear return new AwsException("InvalidRequestException", message, 400); } + // Why a cluster gets no instance group or fleet of the other kind: "The configuration option you choose applies to + // all nodes, it applies for the lifetime of the cluster, and instance fleets and instance groups cannot coexist in + // a cluster." + private static String fleetsAndGroupsApart(String clusterId, String uses) { + return "Cluster " + clusterId + " uses " + uses + ", and instance fleets and instance groups cannot coexist" + + " in a cluster."; + } + /** * ModifyInstanceFleet's answer for a job flow that is shutting down or ended, ErrorCode member included. * AddInstanceFleet and ModifyCluster give it too, as their models also declare InvalidRequestException. @@ -1746,16 +1767,13 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear isCore, isCore ? core : task); } } - EmrInstanceFleet primaryFleet = cluster.getInstanceFleets().stream() - .filter(fleet -> "MASTER".equals(fleet.getInstanceFleetType())).findFirst().orElse(null); - int number = 1; for (EmrInstanceFleet fleet : cluster.getInstanceFleets()) { - if (fleet == primaryFleet) { - continue; + int number = fleetNumber(cluster.getInstanceFleets(), fleet); + if (number > 0) { + boolean isCore = "CORE".equals(fleet.getInstanceFleetType()); + int count = fleet.getTargetOnDemandCapacity() + fleet.getTargetSpotCapacity(); + addNodes(cluster, number, isCore ? Math.max(count, floor) : count, isCore, isCore ? core : task); } - boolean isCore = "CORE".equals(fleet.getInstanceFleetType()); - int count = fleet.getTargetOnDemandCapacity() + fleet.getTargetSpotCapacity(); - addNodes(cluster, number++, isCore ? Math.max(count, floor) : count, isCore, isCore ? core : task); } List nodes = new ArrayList<>(core); nodes.addAll(task); @@ -1934,7 +1952,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear } /** The EC2 instance id ListInstances gives a cluster's instance {@code index}, counted from 1. */ - static String ec2InstanceId(int index) { + static String ec2InstanceId(long index) { return "i-" + String.format("%017d", index); } @@ -1942,7 +1960,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear * 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. */ - static String privateIpAddress(int group, int ordinal) { + static String privateIpAddress(int group, long ordinal) { return "10." + group + "." + (ordinal - 1) / 254 + "." + ((ordinal - 1) % 254 + 1); } @@ -1951,23 +1969,32 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear * group, and from 1 for the others in the order the cluster has them, which only adds to the end. */ static int groupNumber(List groups, EmrInstanceGroup group) { - EmrInstanceGroup primary = groups.stream().filter(EmrService::isMasterGroup).findFirst().orElse(null); - if (group == primary) { + return numberAmong(groups, group, EmrService::isMasterGroup); + } + + /** A cluster's instance fleet's number in its instances' addresses, as {@link #groupNumber} gives a group's. */ + static int fleetNumber(List fleets, EmrInstanceFleet fleet) { + return numberAmong(fleets, fleet, EmrService::isMasterFleet); + } + + private static int numberAmong(List all, T one, Predicate isMaster) { + T primary = all.stream().filter(isMaster).findFirst().orElse(null); + if (one == primary) { return 0; } int number = 1; - for (EmrInstanceGroup other : groups) { - if (other == group) { + for (T other : all) { + if (other == one) { return number; } if (other != primary) { number++; } } - throw new IllegalArgumentException("The instance group is not one of the cluster's"); + throw new IllegalArgumentException("The instance group or fleet is not one of the cluster's"); } - // The primary instance's: the first of the MASTER group, which ListInstances numbers before the others. + // The primary instance's: the first of the MASTER group or fleet, which ListInstances numbers before the others. static String masterInstanceId(EmrCluster cluster) { return ec2InstanceId(1); } @@ -1982,6 +2009,10 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear return "MASTER".equals(group.getInstanceGroupType()); } + static boolean isMasterFleet(EmrInstanceFleet fleet) { + return "MASTER".equals(fleet.getInstanceFleetType()); + } + /** What a step's thread asks the service while its driver goes: a step has no timeout to report. */ private final class StepProgress implements SparkJobRunner.Progress { 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 2bb846bde4..619aa5527e 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 @@ -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 fleet (MASTER | CORE | TASK). */ @RegisterForReflection public class EmrInstanceFleet { @@ -9,6 +12,7 @@ public class EmrInstanceFleet { private String id; private String name; private String instanceFleetType; + private List instanceTypes = new ArrayList<>(); private int targetOnDemandCapacity; private int targetSpotCapacity; private int provisionedOnDemandCapacity; @@ -26,6 +30,10 @@ public class EmrInstanceFleet { public String getInstanceFleetType() { return instanceFleetType; } public void setInstanceFleetType(String instanceFleetType) { this.instanceFleetType = instanceFleetType; } + /** The instance types of its InstanceTypeConfigs, in their order. */ + public List getInstanceTypes() { return instanceTypes; } + public void setInstanceTypes(List instanceTypes) { this.instanceTypes = instanceTypes; } + public int getTargetOnDemandCapacity() { return targetOnDemandCapacity; } public void setTargetOnDemandCapacity(int targetOnDemandCapacity) { this.targetOnDemandCapacity = targetOnDemandCapacity; 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 07bf3d925d..ebfcb7dc48 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrResizeIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrResizeIntegrationTest.java @@ -248,4 +248,205 @@ class EmrResizeIntegrationTest { equalTo(List.of("ip-10-2-0-1.ec2.internal", "ip-10-2-0-2.ec2.internal"))); emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + id + "\"]}").then().statusCode(200); } + + @Test + @Order(11) + void aFleetsInstancesAreListedOnePerUnitOnDemandFirstAndKeepTheirAddresses() { + String id = emr("RunJobFlow", "{\"Name\":\"fleet-instances\",\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true," + + "\"InstanceFleets\":[{\"InstanceFleetType\":\"CORE\",\"TargetOnDemandCapacity\":1," + + "\"TargetSpotCapacity\":2,\"InstanceTypeConfigs\":[{\"InstanceType\":\"r5.2xlarge\"}," + + "{\"InstanceType\":\"m5.2xlarge\"}]}," + + "{\"InstanceFleetType\":\"MASTER\",\"TargetOnDemandCapacity\":1," + + "\"InstanceTypeConfigs\":[{\"InstanceType\":\"m5.xlarge\"}]}]}}") + .then().statusCode(200).extract().path("JobFlowId"); + Response fleets = emr("ListInstanceFleets", "{\"ClusterId\":\"" + id + "\"}"); + String master = fleets.jsonPath().getString("InstanceFleets.find { it.InstanceFleetType == 'MASTER' }.Id"); + String core = fleets.jsonPath().getString("InstanceFleets.find { it.InstanceFleetType == 'CORE' }.Id"); + String task = emr("AddInstanceFleet", "{\"ClusterId\":\"" + id + "\",\"InstanceFleet\":" + + "{\"InstanceFleetType\":\"TASK\",\"TargetSpotCapacity\":1," + + "\"InstanceTypeConfigs\":[{\"InstanceType\":\"c5.xlarge\"}]}}") + .then().statusCode(200).extract().path("InstanceFleetId"); + String primary = "Instances.find { it.InstanceFleetId == '" + master + "' }"; + String coreInstances = "Instances.findAll { it.InstanceFleetId == '" + core + "' }"; + String taskInstances = "Instances.findAll { it.InstanceFleetId == '" + task + "' }"; + + // The primary node is numbered first, as DescribeCluster's MasterPublicDnsName names it, and each node as the + // cluster's containers are named. + emr("ListInstances", "{\"ClusterId\":\"" + id + "\"}").then().statusCode(200) + .body("Instances", hasSize(5)) + .body("Instances.findAll { it.containsKey('InstanceGroupId') }", hasSize(0)) + .body(primary + ".Ec2InstanceId", equalTo("i-00000000000000001")) + .body(primary + ".PrivateDnsName", equalTo("ip-10-0-0-1.ec2.internal")) + .body(primary + ".Market", equalTo("ON_DEMAND")) + .body(primary + ".InstanceType", equalTo("m5.xlarge")) + .body(coreInstances + ".PrivateIpAddress", equalTo(List.of("10.1.0.1", "10.1.0.2", "10.1.0.3"))) + .body(coreInstances + ".Market", equalTo(List.of("ON_DEMAND", "SPOT", "SPOT"))) + .body(coreInstances + ".InstanceType", equalTo(List.of("r5.2xlarge", "r5.2xlarge", "r5.2xlarge"))) + .body(taskInstances + ".PrivateDnsName", equalTo(List.of("ip-10-2-0-1.ec2.internal"))) + .body(taskInstances + ".Market", equalTo(List.of("SPOT"))) + .body(taskInstances + ".InstanceType", equalTo(List.of("c5.xlarge"))); + emr("DescribeCluster", "{\"ClusterId\":\"" + id + "\"}").then().statusCode(200) + .body("Cluster.MasterPublicDnsName", equalTo("ip-10-0-0-1.ec2.internal")); + + emr("ModifyInstanceFleet", "{\"ClusterId\":\"" + id + "\",\"InstanceFleet\":" + + "{\"InstanceFleetId\":\"" + core + "\",\"TargetSpotCapacity\":0}}").then().statusCode(200); + emr("ListInstances", "{\"ClusterId\":\"" + id + "\"}").then().statusCode(200) + .body("Instances", hasSize(3)) + .body(primary + ".Ec2InstanceId", equalTo("i-00000000000000001")) + .body(coreInstances + ".PrivateIpAddress", equalTo(List.of("10.1.0.1"))) + .body(taskInstances + ".PrivateIpAddress", equalTo(List.of("10.2.0.1"))); + emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + id + "\"]}").then().statusCode(200); + } + + @Test + @Order(12) + void listInstancesKeepsTheGroupsOrFleetsItsFiltersName() { + String fleetsId = emr("RunJobFlow", "{\"Name\":\"fleet-filters\",\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true," + + "\"InstanceFleets\":[{\"InstanceFleetType\":\"MASTER\",\"TargetOnDemandCapacity\":1," + + "\"InstanceTypeConfigs\":[{\"InstanceType\":\"m5.xlarge\"}]}," + + "{\"InstanceFleetType\":\"CORE\",\"TargetOnDemandCapacity\":2," + + "\"InstanceTypeConfigs\":[{\"InstanceType\":\"m5.xlarge\"}]}]}}") + .then().statusCode(200).extract().path("JobFlowId"); + String core = emr("ListInstanceFleets", "{\"ClusterId\":\"" + fleetsId + "\"}").jsonPath() + .getString("InstanceFleets.find { it.InstanceFleetType == 'CORE' }.Id"); + String fleets = "{\"ClusterId\":\"" + fleetsId + "\","; + + emr("ListInstances", fleets + "\"InstanceFleetType\":\"CORE\"}").then().statusCode(200) + .body("Instances.Ec2InstanceId", equalTo(List.of("i-00000000000000002", "i-00000000000000003"))); + emr("ListInstances", fleets + "\"InstanceFleetType\":\"MASTER\"}").then().statusCode(200) + .body("Instances.PrivateIpAddress", equalTo(List.of("10.0.0.1"))); + emr("ListInstances", fleets + "\"InstanceFleetId\":\"" + core + "\"}").then().statusCode(200) + .body("Instances", hasSize(2)); + emr("ListInstances", fleets + "\"InstanceFleetId\":\"" + core + "\",\"InstanceFleetType\":\"MASTER\"}") + .then().statusCode(200).body("Instances", hasSize(0)); + emr("ListInstances", fleets + "\"InstanceGroupTypes\":[\"MASTER\"]}").then().statusCode(200) + .body("Instances", hasSize(0)); + + String groupsId = emr("RunJobFlow", "{\"Name\":\"group-filters\",\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true," + + "\"InstanceGroups\":[{\"InstanceRole\":\"MASTER\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1}," + + "{\"InstanceRole\":\"CORE\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":2}," + + "{\"InstanceRole\":\"TASK\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1}]}}") + .then().statusCode(200).extract().path("JobFlowId"); + String task = emr("ListInstanceGroups", "{\"ClusterId\":\"" + groupsId + "\"}").jsonPath() + .getString("InstanceGroups.find { it.InstanceGroupType == 'TASK' }.Id"); + String groups = "{\"ClusterId\":\"" + groupsId + "\","; + + emr("ListInstances", groups + "\"InstanceGroupTypes\":[\"MASTER\"]}").then().statusCode(200) + .body("Instances.Ec2InstanceId", equalTo(List.of("i-00000000000000001"))); + emr("ListInstances", groups + "\"InstanceGroupTypes\":[\"CORE\",\"TASK\"]}").then().statusCode(200) + .body("Instances.PrivateIpAddress", equalTo(List.of("10.1.0.1", "10.1.0.2", "10.2.0.1"))); + emr("ListInstances", groups + "\"InstanceGroupId\":\"" + task + "\"}").then().statusCode(200) + .body("Instances.Ec2InstanceId", equalTo(List.of("i-00000000000000004"))); + emr("ListInstances", groups + "\"InstanceGroupId\":\"" + task + "\",\"InstanceGroupTypes\":[\"CORE\"]}") + .then().statusCode(200).body("Instances", hasSize(0)); + emr("ListInstances", groups + "\"InstanceFleetType\":\"MASTER\"}").then().statusCode(200) + .body("Instances", hasSize(0)); + emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + fleetsId + "\",\"" + groupsId + "\"]}").then().statusCode(200); + } + + @Test + @Order(13) + void aListingGivesAtMostTwoThousandInstancesAndAMarkerForTheRest() { + // "up to a maximum of 2,000", a fleet of any capacity costing a page. + String id = emr("RunJobFlow", "{\"Name\":\"many-instances\",\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true," + + "\"InstanceFleets\":[{\"InstanceFleetType\":\"MASTER\",\"TargetOnDemandCapacity\":1," + + "\"InstanceTypeConfigs\":[{\"InstanceType\":\"m5.xlarge\"}]}," + + "{\"InstanceFleetType\":\"CORE\",\"TargetOnDemandCapacity\":2500," + + "\"InstanceTypeConfigs\":[{\"InstanceType\":\"m5.xlarge\"}]}]}}") + .then().statusCode(200).extract().path("JobFlowId"); + + emr("ListInstances", "{\"ClusterId\":\"" + id + "\"}").then().statusCode(200) + .body("Instances", hasSize(2000)) + .body("Instances[0].Ec2InstanceId", equalTo("i-00000000000000001")) + .body("Marker", equalTo("2000")); + emr("ListInstances", "{\"ClusterId\":\"" + id + "\",\"Marker\":\"2000\"}").then().statusCode(200) + .body("Instances", hasSize(501)) + .body("Instances[0].Ec2InstanceId", equalTo("i-00000000000002001")) + .body("Instances[500].PrivateIpAddress", equalTo("10.1.9.214")) + .body("Marker", nullValue()); + // The pages count what the filters keep. + emr("ListInstances", "{\"ClusterId\":\"" + id + "\",\"InstanceFleetType\":\"CORE\",\"Marker\":\"2000\"}") + .then().statusCode(200).body("Instances", hasSize(500)); + emr("ListInstances", "{\"ClusterId\":\"" + id + "\",\"Marker\":\"next\"}").then().statusCode(400) + .body("__type", equalTo("InvalidRequestException")) + .body("message", equalTo("Invalid pagination token: next")); + + // A fleet's two capacities add up past an int, and its last page is as cheap as its first. + String widest = emr("RunJobFlow", "{\"Name\":\"widest\",\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true," + + "\"InstanceFleets\":[{\"InstanceFleetType\":\"MASTER\",\"TargetOnDemandCapacity\":1," + + "\"InstanceTypeConfigs\":[{\"InstanceType\":\"m5.xlarge\"}]}," + + "{\"InstanceFleetType\":\"CORE\",\"TargetOnDemandCapacity\":2147483647," + + "\"TargetSpotCapacity\":2147483647,\"InstanceTypeConfigs\":[{\"InstanceType\":\"m5.xlarge\"}]}]}}") + .then().statusCode(200).extract().path("JobFlowId"); + emr("ListInstances", "{\"ClusterId\":\"" + widest + "\"}").then().statusCode(200) + .body("Instances", hasSize(2000)).body("Marker", equalTo("2000")); + emr("ListInstances", "{\"ClusterId\":\"" + widest + "\",\"Marker\":\"4294967293\"}").then().statusCode(200) + .body("Instances.Ec2InstanceId", equalTo(List.of("i-00000004294967294", "i-00000004294967295"))) + .body("Instances.Market", equalTo(List.of("SPOT", "SPOT"))) + .body("Marker", nullValue()); + emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + id + "\",\"" + widest + "\"]}").then().statusCode(200); + } + + @Test + @Order(14) + void aClustersInstanceGroupsAndFleetsNeverMeet() { + // "instance fleets and instance groups cannot coexist in a cluster". + emr("RunJobFlow", "{\"Name\":\"both\",\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true," + + "\"InstanceGroups\":[{\"InstanceRole\":\"MASTER\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1}]," + + "\"InstanceFleets\":[{\"InstanceFleetType\":\"CORE\",\"TargetOnDemandCapacity\":1," + + "\"InstanceTypeConfigs\":[{\"InstanceType\":\"m5.xlarge\"}]}]}}").then().statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", equalTo("The RunJobFlow request can contain InstanceFleets parameters or" + + " InstanceGroups parameters, but not both.")); + + String fleetsId = emr("RunJobFlow", "{\"Name\":\"fleets\",\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true," + + "\"InstanceFleets\":[{\"InstanceFleetType\":\"MASTER\",\"TargetOnDemandCapacity\":1," + + "\"InstanceTypeConfigs\":[{\"InstanceType\":\"m5.xlarge\"}]}]}}") + .then().statusCode(200).extract().path("JobFlowId"); + emr("AddInstanceGroups", "{\"JobFlowId\":\"" + fleetsId + "\",\"InstanceGroups\":[{\"InstanceRole\":\"TASK\"," + + "\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1}]}").then().statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", equalTo("Cluster " + fleetsId + " uses instance fleets, and instance fleets and" + + " instance groups cannot coexist in a cluster.")); + String groupsId = emr("RunJobFlow", "{\"Name\":\"groups\",\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true," + + "\"InstanceGroups\":[{\"InstanceRole\":\"MASTER\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1}]}}") + .then().statusCode(200).extract().path("JobFlowId"); + emr("AddInstanceFleet", "{\"ClusterId\":\"" + groupsId + "\",\"InstanceFleet\":{\"InstanceFleetType\":\"TASK\"," + + "\"TargetSpotCapacity\":1,\"InstanceTypeConfigs\":[{\"InstanceType\":\"m5.xlarge\"}]}}") + .then().statusCode(400) + .body("__type", equalTo("InvalidRequestException")) + .body("message", equalTo("Cluster " + groupsId + " uses instance groups, and instance fleets and" + + " instance groups cannot coexist in a cluster.")); + emr("ListInstanceFleets", "{\"ClusterId\":\"" + groupsId + "\"}").then().statusCode(200) + .body("InstanceFleets", hasSize(0)); + emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + fleetsId + "\",\"" + groupsId + "\"]}").then().statusCode(200); + } + + @Test + @Order(15) + void aFleetWithoutItsTypeOrAnInstanceTypeIsRefused() { + emr("RunJobFlow", "{\"Name\":\"typeless\",\"Instances\":{\"InstanceFleets\":[" + + "{\"TargetOnDemandCapacity\":1,\"InstanceTypeConfigs\":[{\"InstanceType\":\"m5.xlarge\"}," + + "{\"WeightedCapacity\":1}]}]}}").then().statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", equalTo("2 validation errors detected: Value null at" + + " 'instances.instanceFleets.1.member.instanceFleetType' failed to satisfy constraint: Member" + + " must not be null; Value null at" + + " 'instances.instanceFleets.1.member.instanceTypeConfigs.2.member.instanceType' failed to" + + " satisfy constraint: Member must not be null")); + String id = emr("RunJobFlow", "{\"Name\":\"typed\",\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true," + + "\"InstanceFleets\":[{\"InstanceFleetType\":\"MASTER\",\"TargetOnDemandCapacity\":1," + + "\"InstanceTypeConfigs\":[{\"InstanceType\":\"m5.xlarge\"}]}]}}") + .then().statusCode(200).extract().path("JobFlowId"); + + emr("AddInstanceFleet", "{\"ClusterId\":\"" + id + "\",\"InstanceFleet\":{\"InstanceFleetType\":\"TASK\"," + + "\"TargetSpotCapacity\":1,\"InstanceTypeConfigs\":[{\"BidPrice\":\"0.1\"}]}}").then().statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", equalTo("1 validation error detected: Value null at" + + " 'instanceFleet.instanceTypeConfigs.1.member.instanceType' failed to satisfy constraint:" + + " Member must not be null")); + emr("ListInstanceFleets", "{\"ClusterId\":\"" + id + "\"}").then().statusCode(200) + .body("InstanceFleets", hasSize(1)); + emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + id + "\"]}").then().statusCode(200); + } } 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 5a5b06f4c7..0af63eacbf 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java @@ -393,6 +393,21 @@ class EmrServiceContainerStepsTest { fixture.clusterStorage.yarns.get(0).nodes()); } + @Test + void aFleetListedBeforeThePrimaryOneIsNamedAsListInstancesNamesIt() { + fixture.clusterStorage.ownNetwork = true; + EmrCluster requested = cluster("core-first", true, sparkStep("report", "CONTINUE")); + requested.setInstanceFleets(new ArrayList<>(List.of(fleet("CORE", 1, 0), fleet("MASTER", 1, 0), + fleet("TASK", 0, 1)))); + service.runJobFlow(requested, REGION); + + fixture.runStepThread(); + + assertEquals(List.of(new ClusterStorage.Node("1-1", "ip-10-1-0-1.ec2.internal", true), + new ClusterStorage.Node("2-1", "ip-10-2-0-1.ec2.internal", false)), + fixture.clusterStorage.yarns.get(0).nodes()); + } + @Test void noMoreNodesRunThanTheSettingAllowsCoreNodesFirst() { fixture.clusterStorage.ownNetwork = 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 e304457f98..bd04fd92a8 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceTest.java @@ -463,18 +463,21 @@ class EmrServiceTest { EmrService service = fixture.service; EmrCluster read = cluster("read", true, step("only")); read.getInstanceGroups().add(group("CORE", 2)); - read.getInstanceFleets().add(fleet("TASK", 2)); EmrCluster created = service.runJobFlow(read, REGION); String id = created.getId(); String stepId = created.getSteps().get(0).getId(); + // A cluster has instance groups or fleets, never both, so the fleet is another cluster's. + EmrCluster fleets = cluster("fleets", true, step("only")); + fleets.getInstanceFleets().add(fleet("TASK", 2)); + String fleetsId = service.runJobFlow(fleets, REGION).getId(); List clusters = List.of(service.describeCluster(id), service.listClusters(REGION, null, null, null).get(0), service.getClusterForInstances(id)); List steps = List.of(service.describeStep(id, stepId), service.listSteps(id, null, null).get(0)); EmrInstanceGroup group = service.listInstanceGroups(id).get(0); - EmrInstanceFleet fleet = service.listInstanceFleets(id).get(0); + EmrInstanceFleet fleet = service.listInstanceFleets(fleetsId).get(0); fixture.pass(Duration.ofSeconds(60)); - service.terminateJobFlows(List.of(id)); + service.terminateJobFlows(List.of(id, fleetsId)); fixture.pass(Duration.ofSeconds(30)); assertEquals("TERMINATED", service.describeCluster(id).getState()); diff --git a/src/test/java/io/floci/aws/services/emr/EmrTerminatedCapacityIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrTerminatedCapacityIntegrationTest.java index b20588edfe..d16f581d85 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrTerminatedCapacityIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrTerminatedCapacityIntegrationTest.java @@ -1,6 +1,8 @@ package io.floci.aws.services.emr; import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.services.emr.model.EmrCluster; +import io.floci.aws.services.emr.model.EmrInstanceFleet; import io.floci.aws.services.emr.model.EmrInstanceGroup; import io.floci.aws.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; @@ -9,6 +11,7 @@ import org.junit.jupiter.api.Test; import java.time.Instant; import java.time.temporal.ChronoUnit; +import java.util.Collections; import java.util.List; import static io.floci.aws.testing.EmrRequests.emr; @@ -16,6 +19,7 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; @QuarkusTest @@ -170,6 +174,20 @@ class EmrTerminatedCapacityIntegrationTest { assertEquals(2, EmrHandler.listedInstanceCount(legacy, false)); } + @Test + void aFleetStoredBeforeItsInstanceTypesWereKeptListsItsInstancesWithoutOne() throws Exception { + EmrCluster cluster = new EmrCluster(); + cluster.getInstanceFleets().add(new ObjectMapper().readValue( + "{\"instanceFleetType\":\"CORE\",\"targetSpotCapacity\":2,\"provisionedSpotCapacity\":2}", + EmrInstanceFleet.class)); + + EmrHandler.ListedInstances listed = EmrHandler.listedInstances(cluster, false).getFirst(); + + assertEquals(2, listed.count()); + assertNull(listed.instanceType()); + assertEquals("SPOT", listed.marketOf(1)); + } + private static String clusterRequest(String id) { return "{\"ClusterId\":\"" + id + "\"}"; } @@ -231,5 +249,13 @@ class EmrTerminatedCapacityIntegrationTest { .body("InstanceFleets.find { it.InstanceFleetType == 'CORE' }.TargetSpotCapacity", equalTo(3)) .body("InstanceFleets.find { it.InstanceFleetType == 'CORE' }.ProvisionedOnDemandCapacity", equalTo(0)) .body("InstanceFleets.find { it.InstanceFleetType == 'CORE' }.ProvisionedSpotCapacity", equalTo(0)); + // What the fleets ran, kept as the 30 days of ended instances. + emr("ListInstances", clusterRequest(id)).then().statusCode(200) + .body("Instances.Id", equalTo(List.of("ci-1" + id, "ci-2" + id, "ci-3" + id, "ci-4" + id, + "ci-5" + id, "ci-6" + id))) + .body("Instances.Market", equalTo(List.of("ON_DEMAND", "ON_DEMAND", "ON_DEMAND", "SPOT", "SPOT", "SPOT"))) + .body("Instances.Status.State", equalTo(Collections.nCopies(6, "TERMINATED"))); + emr("ListInstances", "{\"ClusterId\":\"" + id + "\",\"InstanceStates\":[\"RUNNING\"]}") + .then().statusCode(200).body("Instances", hasSize(0)); } }