From 7ae2339100733af69e16e2d7bfbb2a12c5edb940 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:11:48 -0400 Subject: [PATCH] fix(emr): apply MERGE reconfigurations, step log locations, the scaling index and ServerUrl (#9129) Four members EMR accepted and ignored now act as AWS documents them. ModifyInstanceGroups' ReconfigurationType MERGE merges the group's new Configurations into its own, as the Release Guide's "Reconfigure an instance group in a running cluster" has it: "This option only adds or modifies the new configurations that you submit. It preserves existing configurations." A classification it names takes its properties over the group's, nested configurations merged the same way, and the others stay; OVERWRITE, the default, still replaces them. MERGE is "supported for Amazon EMR releases 5.35.0 and 6.6.0 and later", so an earlier release refuses it with ValidationException, in Floci's wording, and a type that is neither gets the framework's enum message. A step's StepMonitoringConfiguration sends its logs, and its applications' container logs, to its own LogUri from release 7.11, as its options "take precedence over any cluster-wide logging settings", still only on a cluster with a LogUri. The guide gives no layout under the step's destination, so it is the cluster's. A node removed while such steps run puts its containers' logs there when they share one. DescribeStep and ListSteps give the step's LogUri and EncryptionKeyArn back. A managed scaling policy's UtilizationPerformanceIndex is one of 1, 25, 50, 75 and 100: "If you set the index to values other than these, it results in a validation error." One outside the model's 1 to 100 gets the framework's ValidationException, another Floci's wording. A session whose Spark Connect server answers reports ServerUrl, Floci's own address in Spark Connect's sc:// form, where a call still needs GetSessionEndpoint's token to reach the server; an ended session has none. --- docs/services/emr.md | 28 +++- .../io/floci/aws/services/emr/EmrHandler.java | 10 +- .../io/floci/aws/services/emr/EmrService.java | 139 +++++++++++++++++- .../floci/aws/services/emr/EmrSessions.java | 2 + .../floci/aws/services/emr/EmrSparkSteps.java | 47 +++++- .../aws/services/emr/model/EmrSession.java | 4 + .../floci/aws/services/emr/model/EmrStep.java | 9 ++ .../SparkConnectSessionOwner.java | 5 + .../aws/services/emr/EmrIntegrationTest.java | 31 ++++ .../emr/EmrPoliciesIntegrationTest.java | 18 ++- .../emr/EmrResizeIntegrationTest.java | 61 ++++++++ .../aws/services/emr/EmrServiceTest.java | 17 +++ .../services/emr/EmrSessionServerTest.java | 4 + .../aws/services/emr/EmrSparkStepsTest.java | 48 ++++++ 14 files changed, 411 insertions(+), 12 deletions(-) diff --git a/docs/services/emr.md b/docs/services/emr.md index 363f1f47e8..f847ac7111 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -190,6 +190,19 @@ 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. +`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 +configurations that you submit. It preserves existing configurations." A classification they name takes their +properties over its own, and its nested configurations are merged the same way; the group's other classifications +stay. `OVERWRITE`, the default, replaces them. `MERGE` is "supported for Amazon EMR releases 5.35.0 and 6.6.0 and +later"; on an earlier release it is refused with `ValidationException`, in Floci's wording, and a type that is neither +with the framework's enum message. +A managed scaling policy, from `PutManagedScalingPolicy` or `RunJobFlow`, takes a `UtilizationPerformanceIndex` of 1, +25, 50, 75 or 100 only, as the Management Guide's "Advanced Scaling for Amazon EMR" says: "If you set the index to +values other than these, it results in a validation error." One outside the model's 1 to 100 is refused with the +framework's `ValidationException`, and another with `ValidationException` in Floci's wording, as the guide gives none. +The policy is kept and given back as written. 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 @@ -251,6 +264,11 @@ lifecycle on its cluster but runs no server for it. hour". AWS's endpoint is an `https://` URL per session without a port; a Spark Connect URL holds no path, so Floci's is its address alone, port included, and the token names the session. No `Credentials` are given. A session that has ended, or is `TERMINATING`, is refused with `InvalidRequestException`, in Floci's own wording. +* **ServerUrl**: in the `docker` mode, once a session's server answers, `GetSession` and `ListSessions` give it Floci's + own address in Spark Connect's form, such as `sc://localhost:4566`, as "The Spark Connect server URL for the + session", which a client uses "with the Credentials returned by GetSessionEndpoint". A call there still needs + `GetSessionEndpoint`'s token, which routes it to the session's server, so the server is reached no other way. AWS's + form is not documented. An ended session has none. * **ListSessions** returns the newest sessions first, as "Newer sessions are returned first", the later of two started in the same millisecond first too, filtered by `SessionStates`, at most `MaxResults` (1 to 100, 100 by default) to a page. @@ -907,7 +925,15 @@ holding the driver and its executors, or a command or a script. The cluster itse cluster, its standard output and error also go to Floci's S3 once the step ends, gzipped, as `stdout.gz` and `stderr.gz` under `//steps//`, the step log folder of the Management Guide's "Log locations" (an `s3n://` or `s3a://` `LogUri` names the same bucket). A - cancelled step's logs hold what its driver wrote until it was stopped. Logs that cannot be written, + cancelled step's logs hold what its driver wrote until it was stopped. From release 7.11, a step's + `StepMonitoringConfiguration` sends its logs, and its applications' container logs, to its own `LogUri` instead, as + its options "take precedence over any cluster-wide logging settings" (Management Guide, "Customizing the log + location for step log files"), still only on a cluster with a `LogUri`: "If your cluster does not enable cluster + logging, step logs will not be uploaded to S3 even if you provide a StepMonitoringConfiguration". The guide gives no + layout under a step's own destination, so it is the cluster's. A node a resize removes while such steps run puts its + containers' logs at their destination when they share one, and at the cluster's otherwise. `DescribeStep` and + `ListSteps` give a step's own `LogUri` and `EncryptionKeyArn` back; the logs are not encrypted with the key. Logs + that cannot be written, to a bucket that does not exist say, leave the step as it ended. On a cluster that runs YARN, the logs of its applications' containers, a cluster-mode driver's output among them, go gzipped to `//containers///` when a step ends, "Application container logs. The logs 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 c7c9f99c93..0cb5a8a361 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrHandler.java +++ b/src/main/java/io/floci/aws/services/emr/EmrHandler.java @@ -405,6 +405,7 @@ public class EmrHandler { setRawJson(node, "EngineConfigurations", session.getEngineConfigurations()); setRawJson(node, "MonitoringConfiguration", session.getMonitoringConfiguration()); node.put("SessionIdleTimeoutInMinutes", session.getSessionIdleTimeoutInMinutes()); + putIfSet(node, "ServerUrl", session.getServerUrl()); node.set("Tags", tagArray(session.getTags())); return node; } @@ -1279,7 +1280,8 @@ public class EmrHandler { modifications.add(new EmrService.InstanceGroupModification( g.path("InstanceGroupId").asText(null), count.isMissingNode() || count.isNull() ? null : count.asInt(), - configurations.isArray() ? configurations.toString() : null)); + configurations.isArray() ? configurations.toString() : null, + g.path("ReconfigurationType").asText(null))); } } service.modifyInstanceGroups(text(request, "ClusterId"), region, modifications); @@ -1490,6 +1492,9 @@ public class EmrHandler { if (includeExecutionRole && step.getExecutionRoleArn() != null) { node.put("ExecutionRoleArn", step.getExecutionRoleArn()); } + // Its own log destination and key, the StepMonitoringConfiguration it was given. + putIfSet(node, "LogUri", step.getLogUri()); + putIfSet(node, "EncryptionKeyArn", step.getEncryptionKeyArn()); ObjectNode status = node.putObject("Status"); status.put("State", step.getState()); if (step.getStateChangeReason() != null) { @@ -1697,6 +1702,9 @@ public class EmrHandler { props.forEach(p -> map.put(p.path("Key").asText(), p.path("Value").asText())); step.setProperties(map); } + JsonNode s3Logs = s.path("StepMonitoringConfiguration").path("S3MonitoringConfiguration"); + step.setLogUri(s3Logs.path("LogUri").asText(null)); + step.setEncryptionKeyArn(s3Logs.path("EncryptionKeyArn").asText(null)); steps.add(step); } return steps; 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 2bd73eaa37..adaa9ecaf4 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrService.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import io.floci.aws.config.EmulatorConfig; @@ -54,6 +55,7 @@ import jakarta.inject.Inject; import jakarta.inject.Provider; import org.jboss.logging.Logger; +import java.net.URI; import java.security.SecureRandom; import java.time.Clock; import java.time.Duration; @@ -230,6 +232,11 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear private static final Set COMPUTE_LIMITS_UNIT_TYPES = Set.of("InstanceFleetUnits", "Instances", "VCPU"); private static final Set SCALING_STRATEGIES = Set.of("DEFAULT", "ADVANCED"); + private static final int MIN_PERFORMANCE_INDEX = 1; + private static final int MAX_PERFORMANCE_INDEX = 100; + private static final List PERFORMANCE_INDEXES = List.of(1, 25, 50, 75, 100); + private static final String MERGE = "MERGE"; + private static final List RECONFIGURATION_TYPES = List.of("OVERWRITE", MERGE); private static final long MIN_IDLE_TIMEOUT_SECONDS = 60; private static final long MAX_IDLE_TIMEOUT_SECONDS = 604_800; // StepConcurrencyLevel: "You can specify a minimum of 1 step and a maximum of 256 steps" (ModifyCluster), "The @@ -1357,6 +1364,20 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear sessionStore.put(stored.getId(), stored); } + /** + * The session's ServerUrl, "The Spark Connect server URL for the session", which a client uses "with the + * Credentials returned by GetSessionEndpoint to connect directly to the session": Floci's own address in Spark + * Connect's {@code sc://} form, where {@link SparkConnectProxy} takes a call carrying GetSessionEndpoint's token + * on to the session's server, so that no client reaches the server without one. The model gives no example of + * AWS's. + */ + @Override + protected void ready(EmrSession stored) { + URI base = URI.create(baseUrl); + int port = base.getPort() != -1 ? base.getPort() : "https".equals(base.getScheme()) ? 443 : 80; + stored.setServerUrl("sc://" + base.getHost() + ":" + port); + } + // The reason it has, as TerminateSession or its cluster's end gave it. @Override protected String endReason(EmrSession stored, SparkJobRunner.Outcome outcome) { @@ -1408,8 +1429,17 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear }); } - /** One InstanceGroupModifyConfig: a null count or configurations leaves that setting as it is. */ - public record InstanceGroupModification(String instanceGroupId, Integer instanceCount, String configurations) {} + /** + * One InstanceGroupModifyConfig: a null count or configurations leaves that setting as it is, and a null + * reconfiguration type is OVERWRITE. + */ + public record InstanceGroupModification(String instanceGroupId, Integer instanceCount, String configurations, + String reconfigurationType) { + + public InstanceGroupModification(String instanceGroupId, Integer instanceCount, String configurations) { + this(instanceGroupId, instanceCount, configurations, null); + } + } /** * Resizes or reconfigures instance groups in place. ClusterId is optional in the request, so @@ -1423,7 +1453,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear } Map touched = new LinkedHashMap<>(); List groups = new ArrayList<>(); - for (InstanceGroupModification mod : modifications) { + for (int position = 1; position <= modifications.size(); position++) { + InstanceGroupModification mod = modifications.get(position - 1); EmrCluster found = clusterId != null ? requireCluster(clusterId) : clusterOwning(region, mod.instanceGroupId()); // AWS's answer here, recorded by Terraform users @@ -1435,6 +1466,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear // One copy per cluster, so two groups of the same cluster are changed and stored together. EmrCluster cluster = touched.computeIfAbsent(found.getId(), id -> found); EmrInstanceGroup group = requireInstanceGroup(cluster, mod.instanceGroupId()); + checkReconfigurationType(mod.reconfigurationType(), position, cluster.getReleaseLabel()); if (mod.instanceCount() != null) { if (mod.instanceCount() < 0) { throw invalid("InstanceCount must not be negative."); @@ -1454,7 +1486,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear group.setRunningInstanceCount(mod.instanceCount()); } if (mod.configurations() != null) { - group.setConfigurations(mod.configurations()); + group.setConfigurations(MERGE.equals(mod.reconfigurationType()) + ? mergedConfigurations(group.getConfigurations(), mod.configurations()) + : mod.configurations()); group.setConfigurationsVersion(group.getConfigurationsVersion() + 1); } } @@ -1463,6 +1497,74 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear }); } + /** + * 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 + * and 6.6.0" (Release Guide, "Reconfigure an instance group in a running cluster"). No source gives AWS's refusal + * of MERGE on an earlier release, so its wording is Floci's. + */ + private static void checkReconfigurationType(String type, int position, String releaseLabel) { + if (type == null) { + return; + } + if (!RECONFIGURATION_TYPES.contains(type)) { + throw SmithyValidationErrors.validationException(SmithyValidationErrors.notInEnum(type, + "instanceGroups." + position + ".member.reconfigurationType", RECONFIGURATION_TYPES)); + } + boolean merges = releaseAtLeast(releaseLabel, 6, 6, 0) + || (releaseAtLeast(releaseLabel, 5, 35, 0) && !releaseAtLeast(releaseLabel, 6, 0, 0)); + if (MERGE.equals(type) && !merges) { + throw new AwsException("ValidationException", "MERGE reconfiguration is supported for Amazon EMR releases" + + " 5.35.0 and 6.6.0 and later, and the cluster runs " + releaseLabel + ".", 400); + } + } + + /** + * An instance group's configurations after a MERGE reconfiguration: it "merges the newly submitted configurations + * with configurations that already exist on the cluster. This option only adds or modifies the new configurations + * that you submit. It preserves existing configurations." A classification it names takes its properties over the + * existing ones of that classification, and its nested configurations merged the same way; one it does not name + * stays, and a new one is added. + */ + static String mergedConfigurations(String existing, String added) { + try { + ArrayNode merged = existing != null && SNAPSHOT_MAPPER.readTree(existing) instanceof ArrayNode held + ? held : SNAPSHOT_MAPPER.createArrayNode(); + return merged(merged, (ArrayNode) SNAPSHOT_MAPPER.readTree(added)).toString(); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Stored configurations are not JSON", e); + } + } + + private static ArrayNode merged(ArrayNode existing, ArrayNode added) { + ArrayNode merged = existing.deepCopy(); + for (JsonNode configuration : added) { + String classification = configuration.path("Classification").asText(null); + ObjectNode match = null; + for (JsonNode held : merged) { + if (classification != null && held instanceof ObjectNode object + && classification.equals(held.path("Classification").asText(null))) { + match = object; + } + } + if (match == null || !configuration.isObject()) { + merged.add(configuration.deepCopy()); + continue; + } + if (configuration.path("Properties").isObject()) { + JsonNode properties = match.path("Properties"); + ObjectNode into = properties.isObject() ? (ObjectNode) properties : match.putObject("Properties"); + into.setAll((ObjectNode) configuration.get("Properties").deepCopy()); + } + if (configuration.path("Configurations").isArray()) { + JsonNode nested = match.path("Configurations"); + match.set("Configurations", merged(nested.isArray() ? (ArrayNode) nested + : SNAPSHOT_MAPPER.createArrayNode(), (ArrayNode) configuration.get("Configurations"))); + } + } + return merged; + } + @Override public String namespace() { return "elasticmapreduce"; @@ -2042,6 +2144,31 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear if (!strategy.isMissingNode() && !SCALING_STRATEGIES.contains(strategy.asText(""))) { throw invalid("ScalingStrategy must be one of " + SCALING_STRATEGIES + "."); } + checkUtilizationPerformanceIndex(policy.path("UtilizationPerformanceIndex")); + } + + /** + * The model bounds UtilizationPerformanceIndex to 1 to 100, and of those "Possible values are 1, 25, 50, 75 and + * 100. If you set the index to values other than these, it results in a validation error" (Management Guide, + * "Advanced Scaling for Amazon EMR"). The guide gives no message for the latter, so its wording is Floci's. + */ + private static void checkUtilizationPerformanceIndex(JsonNode index) { + if (index.isMissingNode() || index.isNull()) { + return; + } + String path = "managedScalingPolicy.utilizationPerformanceIndex"; + if (!index.isIntegralNumber() || !index.canConvertToInt()) { + throw invalid("ManagedScalingPolicy.UtilizationPerformanceIndex must be an integer."); + } + String range = SmithyValidationErrors.outOfRange(path, index.intValue(), MIN_PERFORMANCE_INDEX, + MAX_PERFORMANCE_INDEX); + if (range != null) { + throw SmithyValidationErrors.validationException(range); + } + if (!PERFORMANCE_INDEXES.contains(index.intValue())) { + throw new AwsException("ValidationException", "UtilizationPerformanceIndex must be one of " + + PERFORMANCE_INDEXES + ".", 400); + } } /** IdleTimeout, when given, is 60 to 604800 seconds. */ @@ -2775,7 +2902,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear StepLaunch launch = new StepLaunch(accountId, region, cluster.getId(), step.getId(), generation, teardowns.get()); executing.add(stepKey(accountId, step.getId())); - String containerLogs = yarn ? EmrSparkSteps.containerLogFolder(cluster) : null; + String containerLogs = yarn ? EmrSparkSteps.containerLogFolder(cluster, step) : null; stepExecutor.execute(() -> runStep(job, launch, onCluster.releaseImage(), onCluster.hdfs(), containerLogs, onCluster.primary())); } @@ -3010,7 +3137,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear long coreNodes = nodes.stream().filter(ClusterStorage.Node::core).count(); return nodeManager.withHadoopFolder(EmrReleaseImages.hadoopFolder(cluster.getReleaseLabel())) .onNodes(nodes, (int) Math.max(1, Math.min(replication(cluster), coreNodes)), - EmrSparkSteps.containerLogFolder(cluster)) + EmrSparkSteps.nodeLogFolder(cluster)) .withPrimaryWorking(cluster.getProvisionedCoreNodes() == 0 || coreNodes == 0) .withSparkHistory(EmrSparkSteps.names(cluster.getApplications(), SNAPSHOT_MAPPER, "Spark")) .withHistories(timeline, timeline && tezImage diff --git a/src/main/java/io/floci/aws/services/emr/EmrSessions.java b/src/main/java/io/floci/aws/services/emr/EmrSessions.java index 2d978152c4..a0d2ef31ff 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrSessions.java +++ b/src/main/java/io/floci/aws/services/emr/EmrSessions.java @@ -273,6 +273,8 @@ final class EmrSessions { session.setEndedAt(at); session.setUpdatedAt(at); session.setIdleSince(null); + // Its server has gone, and with it the URL to reach it at. + session.setServerUrl(null); } /** Whether the session has ended, TERMINATED or FAILED. */ diff --git a/src/main/java/io/floci/aws/services/emr/EmrSparkSteps.java b/src/main/java/io/floci/aws/services/emr/EmrSparkSteps.java index 7e71debca5..b0d441812b 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrSparkSteps.java +++ b/src/main/java/io/floci/aws/services/emr/EmrSparkSteps.java @@ -12,6 +12,7 @@ import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -329,16 +330,58 @@ final class EmrSparkSteps { return EmrServerlessSparkRunner.logFolder(cluster.getLogUri(), cluster.getId() + "/containers/"); } + /** + * The S3 folder a step's application container logs go to: its own log destination's {@code containers} folder, + * as "the application's container logs will also be uploaded to the location specified in the + * StepMonitoringConfiguration", where it has one ({@link #logUri}), and else its cluster's. + */ + static String containerLogFolder(EmrCluster cluster, EmrStep step) { + return EmrServerlessSparkRunner.logFolder(logUri(cluster, step), cluster.getId() + "/containers/"); + } + + /** + * Where a node removed from the cluster puts its containers' logs: the running steps' own destination when they + * share one, as those logs are their applications', and else the cluster's. A node removed between steps, or while + * steps with other destinations run, uses the cluster's. + */ + static String nodeLogFolder(EmrCluster cluster) { + Set folders = new HashSet<>(); + String folder = containerLogFolder(cluster); + for (EmrStep step : cluster.getSteps()) { + if (EmrClusterLifecycle.RUNNING.equals(step.getState()) + || EmrClusterLifecycle.CANCEL_PENDING.equals(step.getState())) { + folder = containerLogFolder(cluster, step); + folders.add(String.valueOf(folder)); + } + } + return folders.size() == 1 ? folder : containerLogFolder(cluster); + } + /** * The S3 folder a step's logs go to, or null when its cluster has no {@code LogUri}: "If a value is not * provided, logs are not created". The Management Guide's "Log locations" puts step logs at - * {@code //steps//}. + * {@code //steps//}, under the step's own destination where it has one. */ static String logFolder(EmrCluster cluster, EmrStep step) { - return EmrServerlessSparkRunner.logFolder(cluster.getLogUri(), + return EmrServerlessSparkRunner.logFolder(logUri(cluster, step), cluster.getId() + "/steps/" + step.getId() + "/"); } + /** + * Where a step's logs are published: the {@code LogUri} of its StepMonitoringConfiguration, which "Beginning in + * Amazon EMR version 7.11" "take[s] precedence over any cluster-wide logging settings", and else its cluster's. + * None without the cluster's: "If your cluster does not enable cluster logging, step logs will not be uploaded to + * S3 even if you provide a StepMonitoringConfiguration" (Management Guide, "Customizing the log location for step + * log files"). The guide gives no folder layout under the step's own destination; it is the cluster's. + */ + static String logUri(EmrCluster cluster, EmrStep step) { + if (cluster.getLogUri() == null || step.getLogUri() == null + || !EmrService.releaseAtLeast(cluster.getReleaseLabel(), 7, 11, 0)) { + return cluster.getLogUri(); + } + return step.getLogUri(); + } + /** * The Spark properties of a cluster's {@code Configurations}, the JSON array {@code RunJobFlow} was given, * that a step's {@code spark-submit} gets as defaults: {@code spark-defaults}'s, and {@code core-site}'s and diff --git a/src/main/java/io/floci/aws/services/emr/model/EmrSession.java b/src/main/java/io/floci/aws/services/emr/model/EmrSession.java index 58778100cd..dec350bc32 100644 --- a/src/main/java/io/floci/aws/services/emr/model/EmrSession.java +++ b/src/main/java/io/floci/aws/services/emr/model/EmrSession.java @@ -31,6 +31,8 @@ public class EmrSession implements SparkConnectSession { private Instant startedAt; private Instant endedAt; private Instant idleSince; + // The Spark Connect server URL, once its server answers. + private String serverUrl; private String engineConfigurations; private String monitoringConfiguration; private long sessionIdleTimeoutInMinutes; @@ -70,6 +72,8 @@ public class EmrSession implements SparkConnectSession { public void setStartedAt(Instant startedAt) { this.startedAt = startedAt; } public Instant getEndedAt() { return endedAt; } public void setEndedAt(Instant endedAt) { this.endedAt = endedAt; } + public String getServerUrl() { return serverUrl; } + public void setServerUrl(String serverUrl) { this.serverUrl = serverUrl; } public Instant getIdleSince() { return idleSince; } public void setIdleSince(Instant idleSince) { this.idleSince = idleSince; } public String getEngineConfigurations() { return engineConfigurations; } diff --git a/src/main/java/io/floci/aws/services/emr/model/EmrStep.java b/src/main/java/io/floci/aws/services/emr/model/EmrStep.java index 8b9c48d617..1468b5f6f6 100644 --- a/src/main/java/io/floci/aws/services/emr/model/EmrStep.java +++ b/src/main/java/io/floci/aws/services/emr/model/EmrStep.java @@ -25,6 +25,9 @@ public class EmrStep { private String state; private String stateChangeReason; private String executionRoleArn; + // Its StepMonitoringConfiguration's S3MonitoringConfiguration, null where it gives none. + private String logUri; + private String encryptionKeyArn; private boolean runInContainer; private String failureReason; private String failureMessage; @@ -64,6 +67,12 @@ public class EmrStep { public String getExecutionRoleArn() { return executionRoleArn; } public void setExecutionRoleArn(String executionRoleArn) { this.executionRoleArn = executionRoleArn; } + public String getLogUri() { return logUri; } + public void setLogUri(String logUri) { this.logUri = logUri; } + + public String getEncryptionKeyArn() { return encryptionKeyArn; } + public void setEncryptionKeyArn(String encryptionKeyArn) { this.encryptionKeyArn = encryptionKeyArn; } + public boolean isRunInContainer() { return runInContainer; } public void setRunInContainer(boolean runInContainer) { this.runInContainer = runInContainer; } diff --git a/src/main/java/io/floci/aws/services/emrserverless/SparkConnectSessionOwner.java b/src/main/java/io/floci/aws/services/emrserverless/SparkConnectSessionOwner.java index 5e0016b929..aced3e18e9 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/SparkConnectSessionOwner.java +++ b/src/main/java/io/floci/aws/services/emrserverless/SparkConnectSessionOwner.java @@ -51,6 +51,10 @@ public abstract class SparkConnectSessionOwner implements SparkConnectServers /** Checks the session again at its next deadline, or cancels its check where it has none. */ protected abstract void checkLater(R stored); + /** Sets on the session what its server's first answer gives it, before it is saved IDLE; nothing by default. */ + protected void ready(R stored) { + } + @Override public void running(String sessionId) { inState(sessionId, SUBMITTED, stored -> { @@ -69,6 +73,7 @@ public abstract class SparkConnectSessionOwner implements SparkConnectServers session.setStartedAt(now); session.setIdleSince(now); session.setUpdatedAt(now); + ready(stored); save(stored); checkLater(stored); LOG.infov("Session {0} is ready", sessionId); diff --git a/src/test/java/io/floci/aws/services/emr/EmrIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrIntegrationTest.java index 551787531a..f9136f4889 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrIntegrationTest.java @@ -236,6 +236,37 @@ class EmrIntegrationTest { .body("Step.Status.State", equalTo("COMPLETED")); } + /** A step's own log destination and key, its StepMonitoringConfiguration, read back as DescribeStep's members. */ + @Test + void aStepGivesBackItsOwnLogUriAndEncryptionKey() { + String cluster = emr("RunJobFlow", "{\"Name\":\"step-logs\",\"ReleaseLabel\":\"emr-7.11.0\"," + + "\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true}}") + .then().statusCode(200).extract().path("JobFlowId"); + try { + List ids = emr("AddJobFlowSteps", "{\"JobFlowId\":\"" + cluster + "\",\"Steps\":[" + + "{\"Name\":\"logged\",\"ActionOnFailure\":\"CONTINUE\",\"HadoopJarStep\":{" + + "\"Jar\":\"command-runner.jar\",\"Args\":[\"true\"]},\"StepMonitoringConfiguration\":{" + + "\"S3MonitoringConfiguration\":{\"LogUri\":\"s3://step-logs/\"," + + "\"EncryptionKeyArn\":\"arn:aws:kms:us-east-1:000000000000:key/k\"}}}," + + "{\"Name\":\"plain\",\"ActionOnFailure\":\"CONTINUE\",\"HadoopJarStep\":{" + + "\"Jar\":\"command-runner.jar\",\"Args\":[\"true\"]}}]}") + .then().statusCode(200).extract().jsonPath().getList("StepIds", String.class); + + emr("DescribeStep", "{\"ClusterId\":\"" + cluster + "\",\"StepId\":\"" + ids.get(0) + "\"}") + .then().statusCode(200) + .body("Step.LogUri", equalTo("s3://step-logs/")) + .body("Step.EncryptionKeyArn", equalTo("arn:aws:kms:us-east-1:000000000000:key/k")); + emr("DescribeStep", "{\"ClusterId\":\"" + cluster + "\",\"StepId\":\"" + ids.get(1) + "\"}") + .then().statusCode(200) + .body("Step", not(hasKey("LogUri"))); + emr("ListSteps", "{\"ClusterId\":\"" + cluster + "\",\"StepIds\":[\"" + ids.get(0) + "\"]}") + .then().statusCode(200) + .body("Steps[0].LogUri", equalTo("s3://step-logs/")); + } finally { + emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + cluster + "\"]}").then().statusCode(200); + } + } + @Test @Order(8) void listStepsNewestFirst() { diff --git a/src/test/java/io/floci/aws/services/emr/EmrPoliciesIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrPoliciesIntegrationTest.java index fdb449a528..4d8c66e245 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrPoliciesIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrPoliciesIntegrationTest.java @@ -11,6 +11,7 @@ import org.junit.jupiter.api.TestMethodOrder; import static io.floci.aws.testing.EmrRequests.emr; import static org.hamcrest.Matchers.anEmptyMap; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.notNullValue; @@ -79,10 +80,11 @@ class EmrPoliciesIntegrationTest { void managedScalingPolicyPutGetRemove() { emr("PutManagedScalingPolicy", cluster() + ",\"ManagedScalingPolicy\":{\"ComputeLimits\":" + "{\"UnitType\":\"VCPU\",\"MinimumCapacityUnits\":4,\"MaximumCapacityUnits\":32}," - + "\"ScalingStrategy\":\"ADVANCED\"}}").then().statusCode(200); + + "\"ScalingStrategy\":\"ADVANCED\",\"UtilizationPerformanceIndex\":25}}").then().statusCode(200); emr("GetManagedScalingPolicy", cluster() + "}").then().statusCode(200) .body("ManagedScalingPolicy.ComputeLimits.UnitType", equalTo("VCPU")) - .body("ManagedScalingPolicy.ScalingStrategy", equalTo("ADVANCED")); + .body("ManagedScalingPolicy.ScalingStrategy", equalTo("ADVANCED")) + .body("ManagedScalingPolicy.UtilizationPerformanceIndex", equalTo(25)); emr("RemoveManagedScalingPolicy", cluster() + "}").then().statusCode(200); emr("GetManagedScalingPolicy", cluster() + "}").then().statusCode(200) .body("$", anEmptyMap()); @@ -102,6 +104,18 @@ class EmrPoliciesIntegrationTest { .then().statusCode(400).body("__type", equalTo("InvalidRequestException")); emr("PutManagedScalingPolicy", "{\"ClusterId\":\"j-MISSING\",\"ManagedScalingPolicy\":" + MANAGED_SCALING + "}") .then().statusCode(400).body("__type", equalTo("InvalidRequestException")); + // "Possible values are 1, 25, 50, 75 and 100": the model's range first, then the guide's values. + String indexed = cluster() + ",\"ManagedScalingPolicy\":{\"ComputeLimits\":{\"UnitType\":\"VCPU\"," + + "\"MinimumCapacityUnits\":4,\"MaximumCapacityUnits\":32},\"ScalingStrategy\":\"ADVANCED\"," + + "\"UtilizationPerformanceIndex\":%s}}"; + emr("PutManagedScalingPolicy", indexed.formatted("0")).then().statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", containsString("'managedScalingPolicy.utilizationPerformanceIndex'")); + emr("PutManagedScalingPolicy", indexed.formatted("30")).then().statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", containsString("1, 25, 50, 75, 100")); + emr("GetManagedScalingPolicy", cluster() + "}").then().statusCode(200) + .body("$", anEmptyMap()); } @Test 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 ebfcb7dc48..d928118fce 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrResizeIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrResizeIntegrationTest.java @@ -10,8 +10,10 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import java.util.List; +import java.util.Map; import static io.floci.aws.testing.EmrRequests.emr; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.nullValue; @@ -449,4 +451,63 @@ class EmrResizeIntegrationTest { .body("InstanceFleets", hasSize(1)); emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + id + "\"]}").then().statusCode(200); } + + // A cluster on releaseLabel whose task group starts with these configurations: the cluster's id, then the group's. + private static List clusterWithTaskConfigurations(String releaseLabel, String configurations) { + String id = emr("RunJobFlow", "{\"Name\":\"reconfigure\",\"ReleaseLabel\":\"" + releaseLabel + "\"," + + "\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true,\"InstanceGroups\":[" + + "{\"InstanceRole\":\"MASTER\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1}," + + "{\"InstanceRole\":\"TASK\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1," + + "\"Configurations\":" + configurations + "}]}}") + .then().statusCode(200).extract().path("JobFlowId"); + return List.of(id, emr("ListInstanceGroups", "{\"ClusterId\":\"" + id + "\"}").jsonPath() + .getString("InstanceGroups.find { it.InstanceGroupType == 'TASK' }.Id")); + } + + /** + * MERGE "only adds or modifies the new configurations that you submit. It preserves existing configurations", + * where OVERWRITE, the default, replaces them. + */ + @Test + void aMergeReconfigurationKeepsTheGroupsOtherConfigurationsAndOverwriteReplacesThem() { + List ids = clusterWithTaskConfigurations("emr-7.5.0", "[{\"Classification\":\"yarn-site\"," + + "\"Properties\":{\"a\":\"1\",\"b\":\"2\"}},{\"Classification\":\"core-site\"," + + "\"Properties\":{\"x\":\"1\"}}]"); + String listGroups = "{\"ClusterId\":\"" + ids.get(0) + "\"}"; + String task = "InstanceGroups.find { it.Id == '" + ids.get(1) + "' }"; + + emr("ModifyInstanceGroups", "{\"InstanceGroups\":[{\"InstanceGroupId\":\"" + ids.get(1) + "\"," + + "\"ReconfigurationType\":\"MERGE\",\"Configurations\":[{\"Classification\":\"yarn-site\"," + + "\"Properties\":{\"b\":\"3\",\"c\":\"4\"}},{\"Classification\":\"hive-site\"," + + "\"Properties\":{\"h\":\"1\"}}]}]}").then().statusCode(200); + emr("ListInstanceGroups", listGroups).then().statusCode(200) + .body(task + ".Configurations.Classification", equalTo(List.of("yarn-site", "core-site", "hive-site"))) + // GPath answers null for a key named Properties read as ".Properties". + .body(task + ".Configurations[0].get('Properties')", equalTo(Map.of("a", "1", "b", "3", "c", "4"))) + .body(task + ".Configurations[1].get('Properties').x", equalTo("1")) + .body(task + ".ConfigurationsVersion", equalTo(1)); + + emr("ModifyInstanceGroups", "{\"InstanceGroups\":[{\"InstanceGroupId\":\"" + ids.get(1) + "\"," + + "\"Configurations\":[{\"Classification\":\"spark\",\"Properties\":{\"s\":\"1\"}}]}]}") + .then().statusCode(200); + emr("ListInstanceGroups", listGroups).then().statusCode(200) + .body(task + ".Configurations.Classification", equalTo(List.of("spark"))) + .body(task + ".ConfigurationsVersion", equalTo(2)); + } + + @Test + void aMergeBeforeItsReleasesOrAnUnknownTypeIsRefused() { + String early = clusterWithTaskConfigurations("emr-6.5.0", "[]").get(1); + String current = clusterWithTaskConfigurations("emr-7.5.0", "[]").get(1); + String change = "\"Configurations\":[{\"Classification\":\"spark\",\"Properties\":{}}]"; + + emr("ModifyInstanceGroups", "{\"InstanceGroups\":[{\"InstanceGroupId\":\"" + early + "\"," + + "\"ReconfigurationType\":\"MERGE\"," + change + "}]}").then().statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", containsString("5.35.0 and 6.6.0")); + emr("ModifyInstanceGroups", "{\"InstanceGroups\":[{\"InstanceGroupId\":\"" + current + "\"," + + "\"ReconfigurationType\":\"REPLACE\"," + change + "}]}").then().statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", containsString("'instanceGroups.1.member.reconfigurationType'")); + } } 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 5fcf7a3b4f..a45815d718 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceTest.java @@ -55,6 +55,23 @@ class EmrServiceTest { * A tag call's {@code ResourceId} is the cluster the tag handlers find by it: one in the request's Region, or one * stored with no Region, which they find in any. */ + /** A MERGE keeps the classifications it does not name, and merges the ones it does, nested ones included. */ + @Test + void aMergeReconfigurationMergesNestedConfigurationsByClassification() { + String merged = EmrService.mergedConfigurations(""" + [{"Classification":"hadoop-env","Configurations":[{"Classification":"export", + "Properties":{"JAVA_HOME":"/usr/lib/jvm/java-17"}}]}, + {"Classification":"spark","Properties":{"maximizeResourceAllocation":"true"}}]""", """ + [{"Classification":"hadoop-env","Configurations":[{"Classification":"export", + "Properties":{"HADOOP_HEAPSIZE":"2048"}}]}]"""); + + assertEquals("[{\"Classification\":\"hadoop-env\",\"Configurations\":[{\"Classification\":\"export\"," + + "\"Properties\":{\"JAVA_HOME\":\"/usr/lib/jvm/java-17\",\"HADOOP_HEAPSIZE\":\"2048\"}}]}," + + "{\"Classification\":\"spark\",\"Properties\":{\"maximizeResourceAllocation\":\"true\"}}]", merged); + assertEquals("[{\"Classification\":\"spark\"}]", EmrService.mergedConfigurations(null, + "[{\"Classification\":\"spark\"}]")); + } + @Test void aTagCallsResourceIdIsTheClusterTheTagHandlersFind() { EmrServiceFixture fixture = new EmrServiceFixture(0, 0, 0); diff --git a/src/test/java/io/floci/aws/services/emr/EmrSessionServerTest.java b/src/test/java/io/floci/aws/services/emr/EmrSessionServerTest.java index b0d4f17b0f..16f3fe180a 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrSessionServerTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrSessionServerTest.java @@ -58,8 +58,11 @@ class EmrSessionServerTest { EmrSession idle = awaitState(clusterId, started.getId(), "IDLE"); assertEquals("SUBMITTED", started.getState()); + assertNull(started.getServerUrl()); assertNotNull(idle.getStartedAt()); assertEquals(idle.getStartedAt(), idle.getIdleSince()); + // Floci's own address, whose proxy takes only a call with GetSessionEndpoint's token on to the server. + assertEquals("sc://localhost:4566", idle.getServerUrl()); SparkJobRunner.Job job = runner.jobs.get(started.getId()); assertEquals(EmrSessions.SPARK_CONNECT_PORT, job.listenPort()); assertEquals(List.of("--class", "org.apache.spark.sql.connect.service.SparkConnectServer", "spark-internal"), @@ -120,6 +123,7 @@ class EmrSessionServerTest { assertEquals("TERMINATING", terminating.getState()); assertTrue(runner.stopped.contains(sessionId)); assertEquals(EmrSessions.USER_REQUEST, terminated.getStateChangeReason()); + assertNull(terminated.getServerUrl(), "an ended session's server has gone"); assertTrue(service.route(token).isEmpty()); } diff --git a/src/test/java/io/floci/aws/services/emr/EmrSparkStepsTest.java b/src/test/java/io/floci/aws/services/emr/EmrSparkStepsTest.java index 4642987173..a4c428eadd 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrSparkStepsTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrSparkStepsTest.java @@ -1,6 +1,7 @@ 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.EmrStep; import io.floci.aws.services.lambda.launcher.BootstrapProcess; import org.junit.jupiter.api.Test; @@ -10,6 +11,7 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -41,6 +43,52 @@ class EmrSparkStepsTest { "s3://bucket/jobs/report.jar", "--master", "kept"), EmrSparkSteps.application(step, false)); } + /** From 7.11 a step's own LogUri "take[s] precedence", but only on a cluster that logs. */ + @Test + void aStepsLogsGoToItsOwnLogUriFromRelease711OnAClusterThatLogs() { + EmrStep step = step("command-runner.jar", null, "true"); + step.setId("s-1"); + step.setLogUri("s3://step-logs/"); + EmrCluster cluster = new EmrCluster(); + cluster.setId("j-1"); + cluster.setLogUri("s3://cluster-logs/"); + + cluster.setReleaseLabel("emr-7.11.0"); + assertEquals("s3://step-logs/j-1/steps/s-1/", EmrSparkSteps.logFolder(cluster, step)); + assertEquals("s3://step-logs/j-1/containers/", EmrSparkSteps.containerLogFolder(cluster, step)); + cluster.setReleaseLabel("emr-spark-8.0.0"); + assertEquals("s3://step-logs/j-1/steps/s-1/", EmrSparkSteps.logFolder(cluster, step)); + cluster.setReleaseLabel("emr-7.10.0"); + assertEquals("s3://cluster-logs/j-1/steps/s-1/", EmrSparkSteps.logFolder(cluster, step)); + cluster.setReleaseLabel("emr-7.11.0"); + cluster.setLogUri(null); + assertNull(EmrSparkSteps.logFolder(cluster, step)); + } + + /** A node removed while steps run puts its containers' logs where those steps' container logs go. */ + @Test + void aRemovedNodesLogsGoWhereTheRunningStepsContainerLogsGoWhenTheyShareOne() { + EmrCluster cluster = new EmrCluster(); + cluster.setId("j-1"); + cluster.setLogUri("s3://cluster-logs/"); + cluster.setReleaseLabel("emr-7.11.0"); + EmrStep own = step("command-runner.jar", null, "true"); + own.setId("s-1"); + own.setLogUri("s3://step-logs/"); + own.setState("RUNNING"); + EmrStep plain = step("command-runner.jar", null, "true"); + plain.setId("s-2"); + plain.setState("PENDING"); + cluster.setSteps(new ArrayList<>(List.of(own, plain))); + + assertEquals("s3://step-logs/j-1/containers/", EmrSparkSteps.nodeLogFolder(cluster)); + plain.setState("RUNNING"); + assertEquals("s3://cluster-logs/j-1/containers/", EmrSparkSteps.nodeLogFolder(cluster)); + own.setState("COMPLETED"); + plain.setState("COMPLETED"); + assertEquals("s3://cluster-logs/j-1/containers/", EmrSparkSteps.nodeLogFolder(cluster)); + } + @Test void sparkSubmitMayBeNamedByItsPath() { assertEquals(List.of("s3://bucket/jobs/report.py"), EmrSparkSteps.application(