mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(emr): run a cluster's core and task nodes in containers of their own (#8066)
A docker cluster's YARN and HDFS ran on its primary node alone, however many instances the cluster named. On EMR "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". - Each core and task node is a container of its own on the cluster's network, with its data in a volume of its own, its name there the private DNS name ListInstances gives it. The primary node keeps a DataNode and a NodeManager only on a cluster created with no core node, which keeps them as core nodes are added, and a primary node whose volume holds a DataNode's data runs it in any case, so the blocks on it stay in reach. - ListInstances gives each group's instances addresses of their own, so an instance keeps its address while another group resizes. - How many follows the instance groups' counts or the instance fleets' target capacities, at most yarn-max-worker-nodes, core nodes first. A fleet's unit of capacity is one node. With 0 a cluster runs on its primary node alone. - HDFS keeps what EMR's does: one copy of a block below four core nodes, two below ten, three otherwise, or the hdfs-site classification's dfs.replication. Steps' Spark, Hive and hadoop clients write that many. - A resize reaches the nodes of a cluster a step has started them on, on another thread: a new node takes work once it has registered, and one no longer wanted is decommissioned, HDFS and YARN telling when it may go, within EMR's default hour, each node its own, then goes with its data. Core nodes stop at the copies HDFS keeps. - A core node's NodeManager is decommissioned only once HDFS has moved its blocks, as a decommissioned NodeManager exits, which ends the node's container, its DataNode with it. A core node that has gone stays among HDFS's excluded nodes until the NameNode has it dead, 40s after it stopped, so the copies it held never count again. - A core node that stops before HDFS has moved its blocks starts again on its data, and one a shutdown cut off while it was decommissioned starts again with the cluster's next step, from its volume, which carries its name, to be decommissioned then. A task node's volume a shutdown left goes. - A decommissioning round that fails, a refresh of HDFS's or YARN's lists among them, is tried again on the next; a node Docker will not remove yet stays to be removed then, and one whose start a teardown passed goes. A cluster's end removes the volumes of nodes that have no container, and finishes even when Docker cannot list its nodes. - The node list is read inside the cluster's lock, so a step queued before a resize starts the nodes asked for by then. - Container logs come from every node, a decommissioned one's first.
This commit is contained in:
1 parent
ef5e1cf010
commit
7ebed877a8
21 files changed
+2148
-111
No files matched your search
+49
-12
@@ -87,7 +87,9 @@ Instance groups and fleets report `RUNNING` from the cluster's creation until it
|
||||
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; it retains each group's
|
||||
`DescribeCluster`'s `MasterPublicDnsName` says, while the other groups resize, and every other instance's private
|
||||
address is `10.<group>.0.<n>`, 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
|
||||
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,
|
||||
@@ -171,8 +173,10 @@ holding the driver and its executors, or a command or a script. The cluster itse
|
||||
container of their own, `emr-<cluster-id>-hdfs`, from the image the cluster's steps run in where it runs YARN (see
|
||||
**YARN**), else from the release's EMR Serverless Hive image, which has HDFS
|
||||
where the release's image has only its client (`hive-image-template` names another), or, for an `emr-spark-*`
|
||||
release, which has no Hive image, from `emr-7.5.0`'s, with their data in a third volume, one copy of each block,
|
||||
and permissions off. On a cluster with Hive or HCatalog (see **Which steps run**), the same container runs Hive's
|
||||
release, which has no Hive image, from `emr-7.5.0`'s, with their data in a third volume and permissions off. Where
|
||||
the cluster was created with core nodes the DataNodes are theirs instead (see **YARN**), and HDFS keeps what EMR's does, one copy
|
||||
of a block below four core nodes, two below ten and three otherwise, or what the `hdfs-site` classification's
|
||||
`dfs.replication` says, which is the one property of that classification Floci applies. On a cluster with Hive or HCatalog (see **Which steps run**), the same container runs Hive's
|
||||
metastore service, which EMR's HCatalog server is, on port 9083, its Derby database in that volume and its warehouse
|
||||
in the HDFS; it reaches the S3 locations of tables through Floci's S3 as the role of the cluster's EC2 instance
|
||||
profile, as the bootstrap actions do, with a session that goes with the container. It gets the cluster's `core-site`
|
||||
@@ -212,15 +216,16 @@ holding the driver and its executors, or a command or a script. The cluster itse
|
||||
`reconcile-containers-on-startup` is off. A shutdown of Floci removes the HDFS containers of the clusters that are
|
||||
still up, and their next step starts them again, on the data their volume keeps. `/tmp` is each container's own.
|
||||
* **YARN**: on a Docker network of the cluster's own, the default, "the primary node runs the YARN ResourceManager
|
||||
service", as the Management Guide puts it, and, as on a
|
||||
cluster of one node, a NodeManager, both in the primary node's container, and the cluster's Spark runs on them. A
|
||||
service", as the Management Guide puts it, in the primary node's container, with a NodeManager beside it on a cluster
|
||||
created with no core node, which keeps it, and its DataNode, as core nodes are added, the blocks it holds staying in
|
||||
reach, and the cluster's Spark runs on them. A
|
||||
Spark step or custom JAR step submits to it, with `--master yarn` unless it names another master, and in the deploy
|
||||
mode it asks for, `client` when it names none, and so does a `spark-submit` a command or script starts. In client
|
||||
mode the driver stays in the step's container and its output in the step's logs, and the executors run in YARN's
|
||||
containers on the node; in cluster mode the driver runs on the node too, its output in the application's container
|
||||
logs (see **Output**) and only the client's in the step's.
|
||||
The node needs Spark, Python and what the bootstrap actions installed, as an EMR cluster's nodes hold every
|
||||
application it installs, so it runs from the image the steps run in: the bootstrap's, else the release's EMR
|
||||
containers on the cluster's nodes; in cluster mode the driver runs on one of them too, its output in the application's
|
||||
container logs (see **Output**) and only the client's in the step's.
|
||||
A node needs Spark, Python and what the bootstrap actions installed, as an EMR cluster's nodes hold every
|
||||
application it installs, so each runs from the image the steps run in: the bootstrap's, else the release's EMR
|
||||
Serverless image with the HDFS, MapReduce and YARN of its EMR Serverless Hive image, and Hive on a cluster with
|
||||
Hive, which Floci makes the first time one of the release's clusters needs it (see **Hive steps**), and in which the
|
||||
cluster's bootstrap actions run. An `emr-spark-*` release has no EMR Serverless Hive image, and `emr-7.5.0`'s HDFS and
|
||||
@@ -234,6 +239,25 @@ holding the driver and its executors, or a command or a script. The cluster itse
|
||||
Floci's address on the cluster's network, which Floci's container joins as for the metastore (see **Storage**), over
|
||||
HTTP, which Floci serves beside HTTPS with TLS on, so no certificate is involved, with the step's AWS credentials,
|
||||
and find the driver at its container's name on that network.
|
||||
Each core and task node is a container of its own on that network, `emr-<cluster-id>-node-<group>-<n>`, 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
|
||||
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
|
||||
on at once, and the first step of any other starts those asked for by then. A new node takes work as soon as it has
|
||||
registered, even from a step already running. One no longer wanted is decommissioned, as "both YARN NodeManager and
|
||||
HDFS DataNode daemons must be decommissioned", so the steps running on it finish and its blocks move to the nodes that
|
||||
stay, within EMR's default timeout of an hour, each node its own, and then it goes with its data; core nodes stop at the copies HDFS
|
||||
keeps, as "Amazon EMR will not allow clusters to scale core nodes below `dfs.replication`". A core node's NodeManager
|
||||
is decommissioned only once HDFS has moved its blocks, as a decommissioned NodeManager exits, which ends the node's
|
||||
container, its DataNode with it. A core node that has gone stays among HDFS's excluded nodes for a minute, until the
|
||||
NameNode, told to by Floci, has it dead 40 seconds after it stopped, so the copies of blocks it held never count
|
||||
again. A core node a resize brings back under its name in that minute takes no new blocks until it is over. A core
|
||||
node that stops before HDFS has moved its blocks starts again on its data, and one a shutdown of Floci cut off while
|
||||
it was being decommissioned starts again on its data with the cluster's next step, to be decommissioned then.
|
||||
* **Hadoop streaming and MapReduce**: a step's `hadoop` command runs MapReduce in local mode, in its own JVM, on the
|
||||
YARN clusters too (see **Known limitations**): the image has MapReduce only in Spark's shaded Hadoop client, which
|
||||
Floci makes the
|
||||
@@ -370,7 +394,8 @@ holding the driver and its executors, or a command or a script. The cluster itse
|
||||
when it stopped ends with `INTERNAL_ERROR` once Floci is back. With a `LogUri`, each action's output
|
||||
goes to `stdout.gz` and `stderr.gz` under `<LogUri>/<cluster-id>/node/<instance-id>/bootstrap-actions/<n>/`,
|
||||
as the Management Guide's bootstrap failure pages give the folder. The actions run once, as on the
|
||||
master: there are no core or task nodes to run them on. Shutdown actions do not run, and
|
||||
master, and every node of the cluster runs from the image they leave, so each holds what they installed. Shutdown
|
||||
actions do not run, and
|
||||
`Status.ErrorDetails` is not given.
|
||||
* **States**: a step is `RUNNING` from when it starts until its driver or command exits; `step-duration-seconds`
|
||||
does not apply. The first step of a release also waits while its image is pulled (3.5 to 4.3 GB
|
||||
@@ -449,8 +474,19 @@ holding the driver and its executors, or a command or a script. The cluster itse
|
||||
|
||||
### Known limitations
|
||||
|
||||
- **One NodeManager, on the primary node.** A cluster's core and task instance groups get no NodeManager of their own,
|
||||
so its executors all run on the primary node, however many instances the cluster names.
|
||||
- **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.
|
||||
- **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
|
||||
that it does not scale below them, but no error for the request.
|
||||
- **No YARN node labels.** An application master can run on any node, as on EMR's 6.x releases by default. EMR's 7.x
|
||||
releases label nodes by market type and 5.x's keep application masters on core nodes.
|
||||
- **No nodes for a cluster made with `MasterInstanceType`, `SlaveInstanceType` and `InstanceCount`.** Floci keeps no
|
||||
instance groups for that older form of `RunJobFlow`, so such a cluster runs on its primary node alone.
|
||||
- **An `emr-spark-*` cluster's HDFS and YARN are `emr-7.5.0`'s.** The Release Guide lists both at Hadoop 3.4.2 for
|
||||
`emr-spark-8.0.0` and `emr-spark-8.1.0`, and EMR Serverless publishes no image holding them, so the primary node runs
|
||||
Hadoop 3.4.0's. Spark and its Hadoop client are the release's own.
|
||||
@@ -519,6 +555,7 @@ its `STARTING` event, has its events sent after the rest of that call's.
|
||||
| `FLOCI_SERVICES_EMR_HIVE_IMAGE_TEMPLATE` | `public.ecr.aws/emr-serverless/hive/%s:latest` | The EMR Serverless Hive image a `docker` cluster takes HDFS and YARN from, and a cluster with Hive takes Hive from, `%s` standing for the cluster's release label, or `emr-7.5.0` for the Hadoop of an `emr-spark-*` release; see [Storage and Hive steps](#running-steps) |
|
||||
| `FLOCI_SERVICES_EMR_YARN_NODE_MEMORY_MB` | `4096` | The memory a `docker` cluster's NodeManager offers the YARN containers its Spark executors run in (see [Running steps](#running-steps)) |
|
||||
| `FLOCI_SERVICES_EMR_YARN_NODE_VCORES` | `4` | The virtual cores it offers them |
|
||||
| `FLOCI_SERVICES_EMR_YARN_MAX_WORKER_NODES` | `4` | The most core and task nodes a `docker` cluster runs as containers of their own, core nodes first; 0 keeps a cluster on its primary node |
|
||||
| `FLOCI_SERVICES_EMR_RECONCILE_CONTAINERS_ON_STARTUP` | `true` | Remove the step drivers and bootstrap containers a previous run of this Floci left on the Docker daemon, and the images bootstrap actions left for clusters that are gone or have ended, when the EMR service starts; turn it off when two Floci instances share a daemon with the same port and no resource namespace |
|
||||
|
||||
## Release catalogue
|
||||
|
||||
@@ -2138,6 +2138,16 @@ public interface EmulatorConfig {
|
||||
@WithDefault("4")
|
||||
int yarnNodeVcores();
|
||||
|
||||
/**
|
||||
* The most core and task nodes a {@code docker} cluster runs as containers of their own, core nodes first; each
|
||||
* costs 300 to 800 MB while idle. With 0 the primary node holds its DataNode and NodeManager, as a cluster of one
|
||||
* node does.
|
||||
*
|
||||
* Env var: FLOCI_SERVICES_EMR_YARN_MAX_WORKER_NODES
|
||||
*/
|
||||
@WithDefault("4")
|
||||
int yarnMaxWorkerNodes();
|
||||
|
||||
/**
|
||||
* When true, Floci removes, in the {@code docker} runner mode, every EMR step driver and bootstrap
|
||||
* container a previous run of <em>this same</em> Floci left on the daemon (matched by the
|
||||
|
||||
@@ -201,6 +201,7 @@ public class ContainerBuilder {
|
||||
private Long memorySwapBytes;
|
||||
private Long memorySwappiness;
|
||||
private boolean javaTrustStore;
|
||||
private String dnsName;
|
||||
|
||||
Builder(String image, EmulatorConfig config, DockerHostResolver dockerHostResolver,
|
||||
EmbeddedDnsServer embeddedDnsServer,
|
||||
@@ -406,6 +407,15 @@ public class ContainerBuilder {
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives the container {@code name} as its host name and as its alias on the user-defined network it joins at
|
||||
* creation, so the other containers there reach it by that name.
|
||||
*/
|
||||
public Builder withDnsName(String name) {
|
||||
this.dnsName = name;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the Docker network from a service-specific Optional, falling back to
|
||||
* the global services.dockerNetwork() if not present.
|
||||
@@ -822,7 +832,8 @@ public class ContainerBuilder {
|
||||
init,
|
||||
new LinuxOptions(List.copyOf(capAdd), List.copyOf(capDrop), List.copyOf(devices),
|
||||
shmSizeBytes, Map.copyOf(tmpfs), memorySwapBytes, memorySwappiness),
|
||||
javaTrustStore
|
||||
javaTrustStore,
|
||||
dnsName
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -294,6 +294,9 @@ public class ContainerLifecycleManager {
|
||||
if (spec.user() != null && !spec.user().isBlank()) {
|
||||
createCmd.withUser(spec.user());
|
||||
}
|
||||
if (spec.dnsName() != null) {
|
||||
createCmd.withHostName(spec.dnsName()).withAliases(spec.dnsName());
|
||||
}
|
||||
if (env != null && !env.isEmpty()) {
|
||||
createCmd.withEnv(env);
|
||||
}
|
||||
|
||||
@@ -51,6 +51,8 @@ import java.util.regex.Pattern;
|
||||
* ({@link LinuxOptions#NONE} = daemon defaults)
|
||||
* @param javaTrustStore Whether, with TLS on, the container's JVMs trust Floci's CA: the CA bundle's Java trust
|
||||
* store goes in beside the bundle, and {@code JAVA_TOOL_OPTIONS} points at it
|
||||
* @param dnsName The container's host name, and its alias on the user-defined network it joins at creation, so other
|
||||
* containers there reach it by that name (null = Docker's own)
|
||||
*/
|
||||
public record ContainerSpec(
|
||||
String image,
|
||||
@@ -83,7 +85,8 @@ public record ContainerSpec(
|
||||
Map<Integer, String> portBindingHostIps,
|
||||
boolean init,
|
||||
LinuxOptions linuxOptions,
|
||||
boolean javaTrustStore
|
||||
boolean javaTrustStore,
|
||||
String dnsName
|
||||
) {
|
||||
private static final Pattern LINK_LOCAL_IPV4 = Pattern.compile("^169\\.254\\.(\\d{1,3})\\.(\\d{1,3})$");
|
||||
private static final Set<String> NETWORKS_WITHOUT_ENDPOINT_IPAM = Set.of("bridge", "default", "host", "none");
|
||||
@@ -107,7 +110,51 @@ public record ContainerSpec(
|
||||
this(image, null, List.of(), null, null, null, Map.of(), List.of(), List.of(), null,
|
||||
List.of(), List.of(), List.of(), List.of(), Map.of(), null, false, null, List.of(),
|
||||
null, null, List.of(), List.of(), null, null, false, List.of(), Map.of(), false, LinuxOptions.NONE,
|
||||
false);
|
||||
false, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Backward-compatible constructor that leaves the container's name on its network to Docker, so callers that
|
||||
* predate {@code dnsName} keep their existing behaviour.
|
||||
*/
|
||||
public ContainerSpec(
|
||||
String image,
|
||||
String name,
|
||||
List<String> env,
|
||||
List<String> cmd,
|
||||
List<String> entrypoint,
|
||||
Long memoryBytes,
|
||||
Map<Integer, Integer> portBindings,
|
||||
List<Integer> loopbackPortBindings,
|
||||
List<Integer> exposedPorts,
|
||||
String networkMode,
|
||||
List<Mount> mounts,
|
||||
List<Bind> binds,
|
||||
List<VolumesFrom> volumesFrom,
|
||||
List<String> extraHosts,
|
||||
Map<String, String> labels,
|
||||
LogConfig logConfig,
|
||||
boolean privileged,
|
||||
String cgroupnsMode,
|
||||
List<String> dnsServers,
|
||||
String workingDir,
|
||||
String user,
|
||||
List<String> groupAdd,
|
||||
List<DeviceRequest> deviceRequests,
|
||||
Long nanoCpus,
|
||||
Integer cpuShares,
|
||||
boolean readonlyRootfs,
|
||||
List<String> linkLocalIps,
|
||||
Map<Integer, String> portBindingHostIps,
|
||||
boolean init,
|
||||
LinuxOptions linuxOptions,
|
||||
boolean javaTrustStore
|
||||
) {
|
||||
this(image, name, env, cmd, entrypoint, memoryBytes, portBindings, loopbackPortBindings,
|
||||
exposedPorts, networkMode, mounts, binds, volumesFrom, extraHosts, labels, logConfig,
|
||||
privileged, cgroupnsMode, dnsServers, workingDir, user, groupAdd, deviceRequests,
|
||||
nanoCpus, cpuShares, readonlyRootfs, linkLocalIps, portBindingHostIps, init, linuxOptions,
|
||||
javaTrustStore, null);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -149,7 +196,8 @@ public record ContainerSpec(
|
||||
this(image, name, env, cmd, entrypoint, memoryBytes, portBindings, loopbackPortBindings,
|
||||
exposedPorts, networkMode, mounts, binds, volumesFrom, extraHosts, labels, logConfig,
|
||||
privileged, cgroupnsMode, dnsServers, workingDir, user, groupAdd, deviceRequests,
|
||||
nanoCpus, cpuShares, readonlyRootfs, linkLocalIps, portBindingHostIps, init, linuxOptions, false);
|
||||
nanoCpus, cpuShares, readonlyRootfs, linkLocalIps, portBindingHostIps, init, linuxOptions, false,
|
||||
null);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,9 +2,11 @@ package io.floci.aws.services.emr;
|
||||
|
||||
import io.floci.aws.services.emrserverless.SparkJobRunner;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* A cluster's storage in the EMR {@code docker} runner mode: the disks of its primary node, which every one of
|
||||
@@ -34,14 +36,24 @@ public interface ClusterStorage {
|
||||
* unless it is running, and returns the cluster's storage with them: its primary node's {@code host} name, which a
|
||||
* step's container resolves to the address given, on the network given, the metastore's URI, and YARN's
|
||||
* ResourceManager with the address Floci has on that network, the metastore and YARN only on a network of the
|
||||
* cluster's own. A failure to start them is thrown, and {@link Stopped} once {@code stopped} says the step is past
|
||||
* starting, or a teardown has stopped the HDFS.
|
||||
* cluster's own. Its core and task nodes, {@code yarn}'s, run in containers of their own on that network, and
|
||||
* {@code yarn} is read as they start, so a resize since the step was queued counts. A failure to start them is
|
||||
* thrown, and {@link Stopped} once {@code stopped} says the step is past starting, or a teardown
|
||||
* has stopped the HDFS.
|
||||
*/
|
||||
SparkJobRunner.Storage hdfs(String clusterId, String accountId, String region, String host, String image,
|
||||
String dockerNetwork, HiveMetastore hiveMetastore, Yarn yarn, BooleanSupplier stopped);
|
||||
String dockerNetwork, HiveMetastore hiveMetastore, Supplier<Yarn> yarn,
|
||||
BooleanSupplier stopped);
|
||||
|
||||
/**
|
||||
* Puts the logs of the YARN applications on {@code clusterId}'s primary node in {@code logFolder}, an S3 folder
|
||||
* Brings {@code clusterId}'s core and task nodes to what {@code yarn} says at that moment, when a step has started
|
||||
* them: a node that is new starts, and one that is no longer wanted is decommissioned and then goes, while the rest
|
||||
* carry on. Clusters no step has started yet get theirs when one does.
|
||||
*/
|
||||
void resize(String clusterId, Supplier<Yarn> yarn);
|
||||
|
||||
/**
|
||||
* Puts the logs of the YARN applications on {@code clusterId}'s nodes in {@code logFolder}, an S3 folder
|
||||
* ending in a slash, each container's files gzipped in {@code <application>/<container>/}, those already there
|
||||
* and unchanged left as they are. Logs that cannot be read or written leave the step as it ended, and are only
|
||||
* logged.
|
||||
@@ -57,20 +69,44 @@ public interface ClusterStorage {
|
||||
}
|
||||
|
||||
/**
|
||||
* YARN on a cluster's primary node: a ResourceManager, and a NodeManager offering its containers
|
||||
* {@code memoryMb} of memory and {@code vcores} virtual cores, which run its steps' Spark executors, and the folder
|
||||
* of the node's image holding the Hadoop its daemons run from, or null for the image's own.
|
||||
* YARN on a cluster: a ResourceManager on its primary node, and a NodeManager on each of its {@code nodes}, and on
|
||||
* the primary node too when it {@code primaryWorks}, each offering its containers {@code memoryMb} of memory and
|
||||
* {@code vcores} virtual cores, which run its steps' Spark executors; the folder of the nodes' image holding the
|
||||
* Hadoop their daemons run from, or null for the image's own; the copies of a block its HDFS keeps; and the S3
|
||||
* folder its applications' logs go in, or null. A primary node that works runs a DataNode as well.
|
||||
*/
|
||||
record Yarn(int memoryMb, int vcores, String hadoopFolder) {
|
||||
record Yarn(int memoryMb, int vcores, String hadoopFolder, List<Node> nodes, int replication, String logFolder,
|
||||
boolean primaryWorks) {
|
||||
|
||||
Yarn(int memoryMb, int vcores) {
|
||||
this(memoryMb, vcores, null);
|
||||
this(memoryMb, vcores, null, List.of(), 1, null, true);
|
||||
}
|
||||
|
||||
/** This YARN with its daemons run from the Hadoop in {@code folder}. */
|
||||
Yarn withHadoopFolder(String folder) {
|
||||
return new Yarn(memoryMb, vcores, folder);
|
||||
return new Yarn(memoryMb, vcores, folder, nodes, replication, logFolder, primaryWorks);
|
||||
}
|
||||
|
||||
/**
|
||||
* This YARN on these nodes, its HDFS keeping {@code copies} of a block, its logs going to {@code folder}, its
|
||||
* primary node working when none of them is a core node.
|
||||
*/
|
||||
Yarn onNodes(List<Node> workers, int copies, String folder) {
|
||||
return new Yarn(memoryMb, vcores, hadoopFolder, List.copyOf(workers), copies, folder,
|
||||
workers.stream().noneMatch(Node::core));
|
||||
}
|
||||
|
||||
/** This YARN with its primary node running a DataNode and a NodeManager, or not. */
|
||||
Yarn withPrimaryWorking(boolean works) {
|
||||
return new Yarn(memoryMb, vcores, hadoopFolder, nodes, replication, logFolder, works);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A core or task node of a cluster: {@code id} tells its container from its cluster's others, {@code host} is its
|
||||
* private DNS name, and a {@code core} node holds a DataNode beside its NodeManager.
|
||||
*/
|
||||
record Node(String id, String host, boolean core) {
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -36,6 +36,7 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -43,9 +44,12 @@ import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.function.LongSupplier;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
@@ -59,7 +63,9 @@ import java.util.zip.GZIPOutputStream;
|
||||
* primary node's, with their data in a third volume, so that the first container to mount the {@code /mnt} one is a
|
||||
* step's, which fills it from the step's image. On a cluster with Hive or HCatalog the same container runs Hive's
|
||||
* metastore service, as EMR's primary node does, with its database in that third volume, reaching S3 with a session
|
||||
* for the cluster's instance profile's role, which goes with the container.
|
||||
* for the cluster's instance profile's role, which goes with the container. Where it has core nodes, "Core nodes run
|
||||
* the Data Node daemon" and "a core node runs YARN NodeManager daemons", and "Task nodes don't run the Data Node
|
||||
* daemon", each is a container of its own on the cluster's network, with its data in a volume of its own.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
@@ -95,8 +101,23 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
private static final String YARN_VCORES_VARIABLE = "FLOCI_YARN_VCORES";
|
||||
// The folder of the image holding the Hadoop the node's daemons run from; set only when that is not the image's own.
|
||||
private static final String HADOOP_FOLDER_VARIABLE = "FLOCI_HADOOP_FOLDER";
|
||||
// A core or task node's container: its host name, and whether it holds a DataNode, as a resize must know them again
|
||||
// after Floci restarts.
|
||||
private static final String NODE_COMPONENT = SparkJobRunner.Storage.NODE_COMPONENT;
|
||||
private static final String NODE_HOST_LABEL = "io.floci.emr.node-host";
|
||||
private static final String NODE_CORE_LABEL = "io.floci.emr.node-core";
|
||||
private static final String NODE_HOST_VARIABLE = "FLOCI_NODE_HOST";
|
||||
private static final String NODE_CORE_VARIABLE = "FLOCI_NODE_CORE";
|
||||
// Set on a primary node whose cluster was created with core nodes, which hold its DataNodes and NodeManagers in its
|
||||
// place.
|
||||
private static final String NODE_WORKERS_VARIABLE = "FLOCI_NODE_WORKERS";
|
||||
private static final String REPLICATION_VARIABLE = "FLOCI_HDFS_REPLICATION";
|
||||
// The nodes being decommissioned, one host name to a line, as HDFS and YARN read them on the primary node.
|
||||
private static final String DFS_EXCLUDE = HDFS_CONF + "/dfs.exclude";
|
||||
private static final String YARN_EXCLUDE = HDFS_CONF + "/yarn.exclude";
|
||||
// The ResourceManager's cluster metrics on its web port, which say when the NodeManager has registered.
|
||||
private static final String RESOURCE_MANAGER_METRICS = "http://127.0.0.1:8088/ws/v1/cluster/metrics";
|
||||
private static final String RESOURCE_MANAGER_NODES = "http://127.0.0.1:8088/ws/v1/cluster/nodes?states=";
|
||||
// The java.base packages Hadoop 3.4's YARN daemons reach into, which Java 17 opens only when told, through
|
||||
// JDK_JAVA_OPTIONS, which Java 9 on reads and Java 8, on which a release may run and which refuses the options
|
||||
// themselves, ignores.
|
||||
@@ -115,44 +136,50 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
// gives up.
|
||||
private static final Duration HDFS_START_TIMEOUT = Duration.ofSeconds(120);
|
||||
private static final Duration HDFS_POLL_INTERVAL = Duration.ofMillis(500);
|
||||
// How long a node being decommissioned may take before it goes anyway: EMR's default for a graceful one, "3600s
|
||||
// (one hour)", and a minute more for the ResourceManager's own timeout to pass first.
|
||||
private static final Duration GRACEFUL_DECOMMISSION = Duration.ofHours(1);
|
||||
private static final Duration DECOMMISSION_MARGIN = Duration.ofMinutes(1);
|
||||
private static final Duration DECOMMISSION_POLL = Duration.ofSeconds(3);
|
||||
// A core node that has gone stays in HDFS's exclude list until the NameNode has it dead: taken out while the
|
||||
// NameNode still has it live, it is back in service, the copies of its blocks count again, and the NameNode drops
|
||||
// one copy of each block now held twice, which may be the remaining node's. The NameNode has a node dead after twice
|
||||
// its heartbeat recheck interval and ten heartbeats, 2 x 5s + 10 x 3s with NODE_SETUP's setting; this has a margin.
|
||||
private static final Duration DEAD_NODE_WAIT = Duration.ofSeconds(60);
|
||||
private static final int NODE_COMMAND_SECONDS = 120;
|
||||
// How much of a node's output is logged when it does not become ready, and how long reading it may take.
|
||||
private static final int NODE_LOG_LINES = 40;
|
||||
private static final Duration NODE_LOG_READ = Duration.ofSeconds(5);
|
||||
// The primary node's HDFS, started as root: its daemons log their warnings and errors to the container's output,
|
||||
// which docker logs shows; its host name, FLOCI_HDFS_HOST, leads to this container's address, where the DataNode
|
||||
// registers, so steps reach both by it; /mnt, its data's volume, becomes the image's user's, which runs a NameNode
|
||||
// and a DataNode with their data in it, the NameNode formatted the first time, with one copy of each block and
|
||||
// without permissions, listening on FLOCI_HDFS_BIND: every address of the container, on the cluster's own network,
|
||||
// or, in a namespace the steps share, the host's or a container's, only its loopback, which its name leads to, so
|
||||
// no other interface serves files anyone could change; in a container's, the hosts file the name goes in is the
|
||||
// one the namespace's containers share, the steps' too. Once the NameNode on its port is this container's own,
|
||||
// its ClusterId the one its format gave it, rather than another cluster's in that namespace, the DataNode has
|
||||
// joined and the NameNode has left safe mode, which on a restart waits for the blocks the volume holds, the
|
||||
// folders EMR's HDFS has for steps, /tmp and the hadoop user's home, are made. With HIVE_METASTORE_VARIABLE set,
|
||||
// Hive's metastore service starts too, with the Hive image's Hadoop configuration, which the node's image keeps at
|
||||
// HIVE_HADOOP_CONF, as Hive steps run, its settings after it: "Hive records metastore information in a MySQL database on the primary node's file system", kept as a Derby
|
||||
// database in /mnt, which only the service opens, so any number of steps share it, its log in /tmp, and its
|
||||
// warehouse in the HDFS, Hive's exec jar in HIVE_JARS; the cluster's core-site and hive-site, last, replace any of
|
||||
// them, as on EMR's primary node. With YARN_MEMORY_VARIABLE set, YARN starts last, as "the primary node runs the
|
||||
// YARN ResourceManager service": a ResourceManager and, as on a cluster of one node, a NodeManager, which offers
|
||||
// that much memory and YARN_VCORES_VARIABLE's cores to the containers it runs the steps' Spark executors in, its
|
||||
// local and log folders in /mnt, Java 17 opening to both the packages they reach into, and the node is ready once
|
||||
// the NodeManager has registered. HDFS_READY then says the node is ready. A daemon that exits,
|
||||
// before or after, the metastore among them, ends the container, its readiness gone, so the next step starts it
|
||||
// again on its data. With HADOOP_FOLDER_VARIABLE set, every daemon runs from the Hadoop in that folder.
|
||||
private static final String HDFS_SCRIPT = String.join("\n",
|
||||
"address=$FLOCI_HDFS_BIND; [ \"$address\" != 0.0.0.0 ] || address=$(hostname -i | awk '{print $1}')",
|
||||
"echo \"$address $FLOCI_HDFS_HOST\" >> /etc/hosts || exit",
|
||||
// Every daemon of a node, and each command run on it, uses the Hadoop in HADOOP_FOLDER_VARIABLE when that is set.
|
||||
private static final String HADOOP_FOLDER_SETUP = String.join("\n",
|
||||
"if [ -n \"$" + HADOOP_FOLDER_VARIABLE + "\" ]; then",
|
||||
" h=$" + HADOOP_FOLDER_VARIABLE,
|
||||
" export HADOOP_HOME=$h/hadoop HADOOP_COMMON_HOME=$h/hadoop HADOOP_LIBEXEC_DIR=$h/hadoop/libexec"
|
||||
+ " HADOOP_HDFS_HOME=$h/hadoop-hdfs HADOOP_MAPRED_HOME=$h/hadoop-mapreduce"
|
||||
+ " HADOOP_YARN_HOME=$h/hadoop-yarn PATH=$h/hadoop-hdfs/bin:$h/hadoop-yarn/bin:$h/hadoop/bin:$PATH",
|
||||
"fi");
|
||||
// What every node of a cluster writes before its daemons start: the Hadoop configuration, its name among the
|
||||
// nodes in HDFS's when it is given one, and the empty files listing the nodes being decommissioned.
|
||||
private static final String NODE_SETUP = String.join("\n",
|
||||
"chown hadoop:hadoop /mnt || exit",
|
||||
EmrServerlessSparkRunner.HIVE_ONE_SDK,
|
||||
"mkdir -p " + HDFS_CONF + " || exit",
|
||||
"printf '%s\\n' '<configuration>'"
|
||||
+ " \"<property><name>fs.defaultFS</name><value>hdfs://$FLOCI_HDFS_HOST:8020</value></property>\""
|
||||
+ " '</configuration>' > " + HDFS_CONF + "/core-site.xml",
|
||||
"datanode_name=; [ -z \"$" + NODE_HOST_VARIABLE + "\" ] || datanode_name=\"<property>"
|
||||
+ "<name>dfs.datanode.hostname</name><value>$" + NODE_HOST_VARIABLE + "</value></property>\"",
|
||||
": > " + DFS_EXCLUDE + " || exit",
|
||||
": > " + YARN_EXCLUDE + " || exit",
|
||||
"printf '%s\\n' '<configuration>'"
|
||||
+ " '<property><name>dfs.namenode.name.dir</name><value>file:///mnt/namenode</value></property>'"
|
||||
+ " '<property><name>dfs.datanode.data.dir</name><value>file:///mnt/datanode</value></property>'"
|
||||
+ " '<property><name>dfs.replication</name><value>1</value></property>'"
|
||||
+ " \"<property><name>dfs.replication</name><value>${" + REPLICATION_VARIABLE
|
||||
+ ":-1}</value></property>\""
|
||||
+ " '<property><name>dfs.hosts.exclude</name><value>" + DFS_EXCLUDE + "</value></property>'"
|
||||
+ " '<property><name>dfs.namenode.decommission.interval</name><value>3</value></property>'"
|
||||
+ " '<property><name>dfs.namenode.heartbeat.recheck-interval</name><value>5000</value></property>'"
|
||||
+ " \"$datanode_name\""
|
||||
+ " '<property><name>dfs.permissions.enabled</name><value>false</value></property>'"
|
||||
+ " \"<property><name>dfs.namenode.rpc-bind-host</name><value>$FLOCI_HDFS_BIND</value></property>\""
|
||||
+ " \"<property><name>dfs.namenode.http-address</name>"
|
||||
@@ -178,7 +205,9 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
"yarn.nodemanager.local-dirs", "/mnt/yarn/local",
|
||||
"yarn.nodemanager.log-dirs", "/mnt/yarn/logs",
|
||||
"yarn.nodemanager.disk-health-checker.max-disk-utilization-per-disk-percentage", "100",
|
||||
"yarn.nodemanager.aux-services", "mapreduce_shuffle"))
|
||||
"yarn.nodemanager.aux-services", "mapreduce_shuffle",
|
||||
"yarn.resourcemanager.nodes.exclude-path", YARN_EXCLUDE,
|
||||
"yarn.resourcemanager.decommissioning-nodes-watcher.poll-interval-secs", "3"))
|
||||
+ " '</configuration>' > " + HDFS_CONF + "/yarn-site.xml || exit",
|
||||
" printf '%s\\n' '<configuration>'" + yarnProperties(List.of(
|
||||
"yarn.scheduler.capacity.root.queues", "default",
|
||||
@@ -191,21 +220,46 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
+ " 'log4j.appender.console.layout=org.apache.log4j.PatternLayout'"
|
||||
+ " 'log4j.appender.console.layout.ConversionPattern=%d %p %c: %m%n'"
|
||||
+ " > " + HDFS_CONF + "/log4j.properties",
|
||||
"if [ -n \"$" + HADOOP_FOLDER_VARIABLE + "\" ]; then",
|
||||
" h=$" + HADOOP_FOLDER_VARIABLE,
|
||||
" export HADOOP_HOME=$h/hadoop HADOOP_COMMON_HOME=$h/hadoop HADOOP_LIBEXEC_DIR=$h/hadoop/libexec"
|
||||
+ " HADOOP_HDFS_HOME=$h/hadoop-hdfs HADOOP_MAPRED_HOME=$h/hadoop-mapreduce"
|
||||
+ " HADOOP_YARN_HOME=$h/hadoop-yarn PATH=$h/hadoop-hdfs/bin:$h/hadoop-yarn/bin:$h/hadoop/bin:$PATH",
|
||||
"fi",
|
||||
HADOOP_FOLDER_SETUP);
|
||||
// The primary node's HDFS, started as root: its daemons log their warnings and errors to the container's output,
|
||||
// which docker logs shows; its host name, FLOCI_HDFS_HOST, leads to this container's address, where the DataNode
|
||||
// registers, so steps reach both by it; /mnt, its data's volume, becomes the image's user's, which runs a NameNode
|
||||
// and a DataNode with their data in it, the NameNode formatted the first time, with one copy of each block and
|
||||
// without permissions, listening on FLOCI_HDFS_BIND: every address of the container, on the cluster's own network,
|
||||
// or, in a namespace the steps share, the host's or a container's, only its loopback, which its name leads to, so
|
||||
// no other interface serves files anyone could change; in a container's, the hosts file the name goes in is the
|
||||
// one the namespace's containers share, the steps' too. Once the NameNode on its port is this container's own,
|
||||
// its ClusterId the one its format gave it, rather than another cluster's in that namespace, the DataNode has
|
||||
// joined and the NameNode has left safe mode, which on a restart waits for the blocks the volume holds, the
|
||||
// folders EMR's HDFS has for steps, /tmp and the hadoop user's home, are made. With HIVE_METASTORE_VARIABLE set,
|
||||
// Hive's metastore service starts too, with the Hive image's Hadoop configuration, which the node's image keeps at
|
||||
// HIVE_HADOOP_CONF, as Hive steps run, its settings after it: "Hive records metastore information in a MySQL database on the primary node's file system", kept as a Derby
|
||||
// database in /mnt, which only the service opens, so any number of steps share it, its log in /tmp, and its
|
||||
// warehouse in the HDFS, Hive's exec jar in HIVE_JARS; the cluster's core-site and hive-site, last, replace any of
|
||||
// them, as on EMR's primary node. With YARN_MEMORY_VARIABLE set, YARN starts last, as "the primary node runs the
|
||||
// YARN ResourceManager service": a ResourceManager and, as on a cluster of one node, a NodeManager, which offers
|
||||
// that much memory and YARN_VCORES_VARIABLE's cores to the containers it runs the steps' Spark executors in, its
|
||||
// local and log folders in /mnt, Java 17 opening to both the packages they reach into, and the node is ready once
|
||||
// the NodeManager has registered. Where the cluster's core nodes hold them (NODE_WORKERS_VARIABLE), the node runs no
|
||||
// DataNode or NodeManager, but a DataNode on a volume that holds one's data, so the blocks it kept stay in reach.
|
||||
// HDFS_READY then says the node is ready. A daemon that exits,
|
||||
// before or after, the metastore among them, ends the container, its readiness gone, so the next step starts it
|
||||
// again on its data. With HADOOP_FOLDER_VARIABLE set, every daemon runs from the Hadoop in that folder.
|
||||
private static final String HDFS_SCRIPT = String.join("\n",
|
||||
"address=$FLOCI_HDFS_BIND; [ \"$address\" != 0.0.0.0 ] || address=$(hostname -i | awk '{print $1}')",
|
||||
"echo \"$address $FLOCI_HDFS_HOST\" >> /etc/hosts || exit",
|
||||
NODE_SETUP,
|
||||
"exec setpriv --reuid=hadoop --regid=hadoop --clear-groups bash -c '"
|
||||
+ "[ -d /mnt/namenode/current ] || hdfs namenode -format -nonInteractive || exit; "
|
||||
+ "cid=$(sed -n \"s/^clusterID=//p\" /mnt/namenode/current/VERSION); "
|
||||
+ "hdfs namenode & hdfs datanode & n=2; "
|
||||
+ "hdfs namenode & n=1; "
|
||||
+ "if [ -z \"$" + NODE_WORKERS_VARIABLE + "\" ] || [ -d /mnt/datanode/current ]; then "
|
||||
+ "hdfs datanode & n=2; fi; "
|
||||
+ "until curl -sf -m 5 \"" + NAMENODE_JMX + "NameNodeInfo\""
|
||||
+ " | grep -q \"\\\"ClusterId\\\" : \\\"$cid\\\"\"; do "
|
||||
+ "[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done; "
|
||||
+ "until curl -sf -m 5 \"" + NAMENODE_JMX + "FSNamesystemState\""
|
||||
+ " | grep -q \"\\\"NumLiveDataNodes\\\" : 1,\"; do "
|
||||
+ " | grep -q \"\\\"NumLiveDataNodes\\\" : [1-9]\"; do "
|
||||
+ "[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done; "
|
||||
+ "until curl -sf -m 5 \"" + NAMENODE_JMX + "NameNodeInfo\""
|
||||
+ " | grep -q \"\\\"Safemode\\\" : \\\"\\\"\"; do "
|
||||
@@ -233,9 +287,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
+ "[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done; "
|
||||
+ "fi; "
|
||||
+ "if [ -n \"$" + YARN_MEMORY_VARIABLE + "\" ]; then "
|
||||
+ "JDK_JAVA_OPTIONS=\"" + yarnOpens() + "\" yarn resourcemanager & "
|
||||
+ "JDK_JAVA_OPTIONS=\"" + yarnOpens() + "\" yarn nodemanager & n=$((n + 2)); "
|
||||
+ "until curl -sf -m 5 " + RESOURCE_MANAGER_METRICS + " | grep -q \"\\\"activeNodes\\\":1,\"; do "
|
||||
+ "JDK_JAVA_OPTIONS=\"" + yarnOpens() + "\" yarn resourcemanager & n=$((n + 1)); "
|
||||
+ "if [ -z \"$" + NODE_WORKERS_VARIABLE + "\" ]; then "
|
||||
+ "JDK_JAVA_OPTIONS=\"" + yarnOpens() + "\" yarn nodemanager & n=$((n + 1)); fi; "
|
||||
+ "until curl -sf -m 5 " + RESOURCE_MANAGER_METRICS
|
||||
+ " | grep -q \"\\\"activeNodes\\\":[1-9]\"; do "
|
||||
+ "[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done; "
|
||||
+ "fi; "
|
||||
+ "touch " + HDFS_READY + "; "
|
||||
@@ -243,6 +299,25 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
+ "while [ \"$(jobs -rp | wc -l)\" = $n ]; do sleep 1; done; rm -f " + HDFS_READY
|
||||
+ "; kill $(jobs -rp) 2>/dev/null; exit 1'");
|
||||
|
||||
// A core or task node, started as root: a NodeManager and, on a core node, a DataNode, which reach the primary node
|
||||
// by its name on the cluster's network and register under the node's own. It is ready once the ResourceManager, and
|
||||
// on a core node the NameNode, knows it. A daemon that exits ends the container, as on the primary node.
|
||||
private static final String NODE_SCRIPT = String.join("\n",
|
||||
NODE_SETUP,
|
||||
"exec setpriv --reuid=hadoop --regid=hadoop --clear-groups bash -c '"
|
||||
+ "n=1; if [ -n \"$" + NODE_CORE_VARIABLE + "\" ]; then hdfs datanode & n=2; fi; "
|
||||
+ "JDK_JAVA_OPTIONS=\"" + yarnOpens() + "\" yarn nodemanager & "
|
||||
+ "until curl -sf -m 5 \"http://$FLOCI_HDFS_HOST:8088/ws/v1/cluster/nodes?states=RUNNING\""
|
||||
+ " | grep -q \"\\\"nodeHostName\\\":\\\"$" + NODE_HOST_VARIABLE + "\\\"\"; do "
|
||||
+ "[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done; "
|
||||
+ "if [ -n \"$" + NODE_CORE_VARIABLE + "\" ]; then "
|
||||
+ "until curl -sf -m 5 \"http://$FLOCI_HDFS_HOST:9870/jmx?qry=Hadoop:service=NameNode,"
|
||||
+ "name=NameNodeInfo\" | grep -q \"$" + NODE_HOST_VARIABLE + ":9866\"; do "
|
||||
+ "[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done; fi; "
|
||||
+ "touch " + HDFS_READY + "; "
|
||||
+ "while [ \"$(jobs -rp | wc -l)\" = $n ]; do sleep 1; done; rm -f " + HDFS_READY
|
||||
+ "; kill $(jobs -rp) 2>/dev/null; exit 1'");
|
||||
|
||||
// One start at a time in a namespace the steps share, whatever the cluster, as it holds one HDFS.
|
||||
private final Object sharedNamespaceStarts = new Object();
|
||||
// One start at a time for each cluster's HDFS; a step coming while it starts waits, then finds it running.
|
||||
@@ -254,6 +329,19 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
private final Map<String, Map<String, Long>> archivedLogs = new ConcurrentHashMap<>();
|
||||
// The HDFS containers this process has started or found running, by name, which a reset or a shutdown removes.
|
||||
private final Set<String> running = ConcurrentHashMap.newKeySet();
|
||||
// The core and task nodes' containers this process has started or found, by name.
|
||||
private final Set<String> runningNodes = ConcurrentHashMap.newKeySet();
|
||||
// What each cluster's last step started its nodes from, which a resize starts new ones from.
|
||||
private final Map<String, NodeRequest> nodeRequests = new ConcurrentHashMap<>();
|
||||
// For each cluster, the nodes being decommissioned, by container name.
|
||||
private final Map<String, Map<String, Draining>> draining = new ConcurrentHashMap<>();
|
||||
// For each cluster, the core nodes that have gone and are still in HDFS's exclude list, by host name, with the
|
||||
// nanoTime they went at.
|
||||
private final Map<String, Map<String, Long>> departed = new ConcurrentHashMap<>();
|
||||
// The clusters a thread is decommissioning nodes of.
|
||||
private final Set<String> decommissioning = ConcurrentHashMap.newKeySet();
|
||||
private final Executor decommissions;
|
||||
private final Duration decommissionPoll;
|
||||
private final ContainerLifecycleManager lifecycleManager;
|
||||
private final ContainerBuilder containerBuilder;
|
||||
private final LaunchedContainerAwsEnv awsEnv;
|
||||
@@ -272,13 +360,26 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
CurrentContainerNetworkResolver currentContainer, EmulatorConfig config,
|
||||
S3Service s3Service) {
|
||||
this(lifecycleManager, containerBuilder, awsEnv, roleCredentials, currentContainer, config, s3Service,
|
||||
HDFS_START_TIMEOUT, System::nanoTime);
|
||||
HDFS_START_TIMEOUT, System::nanoTime,
|
||||
Executors.newCachedThreadPool(Thread.ofPlatform().daemon().name("emr-decommission-", 0).factory()),
|
||||
DECOMMISSION_POLL);
|
||||
}
|
||||
|
||||
EmrClusterStorage(ContainerLifecycleManager lifecycleManager, ContainerBuilder containerBuilder,
|
||||
LaunchedContainerAwsEnv awsEnv, LambdaExecutionRoleCredentials roleCredentials,
|
||||
CurrentContainerNetworkResolver currentContainer, EmulatorConfig config, S3Service s3Service,
|
||||
Duration hdfsStartTimeout, LongSupplier nanoTime) {
|
||||
this(lifecycleManager, containerBuilder, awsEnv, roleCredentials, currentContainer, config, s3Service,
|
||||
hdfsStartTimeout, nanoTime, Runnable::run, Duration.ZERO);
|
||||
}
|
||||
|
||||
EmrClusterStorage(ContainerLifecycleManager lifecycleManager, ContainerBuilder containerBuilder,
|
||||
LaunchedContainerAwsEnv awsEnv, LambdaExecutionRoleCredentials roleCredentials,
|
||||
CurrentContainerNetworkResolver currentContainer, EmulatorConfig config, S3Service s3Service,
|
||||
Duration hdfsStartTimeout, LongSupplier nanoTime, Executor decommissions,
|
||||
Duration decommissionPoll) {
|
||||
this.decommissions = decommissions;
|
||||
this.decommissionPoll = decommissionPoll;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.awsEnv = awsEnv;
|
||||
@@ -307,12 +408,30 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
|
||||
@Override
|
||||
public void archiveContainerLogs(String clusterId, String accountId, String region, String logFolder) {
|
||||
String name = hdfsName(clusterId);
|
||||
archiveNodeLogs(clusterId, hdfsName(clusterId), accountId, region, logFolder);
|
||||
Collection<String> nodes;
|
||||
try {
|
||||
nodes = nodeContainers(clusterId).keySet();
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not find the nodes of EMR cluster {0} to write their container logs to {1}: {2}",
|
||||
clusterId, logFolder, e.getMessage());
|
||||
return;
|
||||
}
|
||||
for (String node : nodes) {
|
||||
archiveNodeLogs(clusterId, node, accountId, region, logFolder);
|
||||
}
|
||||
}
|
||||
|
||||
private void archiveNodeLogs(String clusterId, String name, String accountId, String region, String logFolder) {
|
||||
Map<String, Long> archived = archivedLogs.computeIfAbsent(name, node -> new ConcurrentHashMap<>());
|
||||
// One step's end at a time for a node, so of two reading a log that is still growing the later is written last.
|
||||
synchronized (archived) {
|
||||
try {
|
||||
S3Uri folder = S3Uri.parseAnyScheme(logFolder);
|
||||
if (lifecycleManager.probeContainer(name) == ContainerLiveness.NOT_RUNNING) {
|
||||
archiveStoppedNodeLogs(name, archived, accountId, region, folder);
|
||||
return;
|
||||
}
|
||||
for (String log : changedLogs(name, archived)) {
|
||||
archiveLog(name, log, archived, accountId, region, folder);
|
||||
}
|
||||
@@ -325,9 +444,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
|
||||
// The node's container logs whose size is not the one already in S3, as <application>/<container>/<file>, but the
|
||||
// launch scripts: only those are read from Docker, so a step's end does not bring every earlier application's again.
|
||||
// A primary node whose core nodes run the NodeManagers has no such folder, and so none.
|
||||
private List<String> changedLogs(String name, Map<String, Long> archived) {
|
||||
ContainerExec.Result listed = ContainerExec.run(lifecycleManager.getDockerClient(), name,
|
||||
new String[]{"find", YARN_LOGS, "-mindepth", "3", "-maxdepth", "3", "-type", "f", "-printf", "%s %P\\n"},
|
||||
new String[]{"bash", "-c", "[ ! -d " + YARN_LOGS + " ] || exec find " + YARN_LOGS
|
||||
+ " -mindepth 3 -maxdepth 3 -type f -printf '%s %P\\n'"},
|
||||
LOG_LISTING_SECONDS);
|
||||
if (listed.exitCode() != 0) {
|
||||
throw new IllegalStateException("Could not list them: " + listed.stderr());
|
||||
@@ -343,6 +464,28 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
return changed;
|
||||
}
|
||||
|
||||
// A stopped node answers no command, a decommissioned one among them, whose NodeManager exits once it is, which ends
|
||||
// its container, but Docker still copies its files: the whole folder, as this is the last look at a node that goes.
|
||||
private void archiveStoppedNodeLogs(String name, Map<String, Long> archived, String accountId, String region,
|
||||
S3Uri folder) throws IOException {
|
||||
try (InputStream archive = lifecycleManager.getDockerClient().copyArchiveFromContainerCmd(name, YARN_LOGS)
|
||||
.exec(); TarArchiveInputStream entries = new TarArchiveInputStream(archive)) {
|
||||
TarArchiveEntry entry;
|
||||
while ((entry = entries.getNextEntry()) != null) {
|
||||
// logs/<application>/<container>/<file>, as Docker archives the folder.
|
||||
String[] path = entry.getName().split("/");
|
||||
if (!entry.isFile() || path.length != 4 || CONTAINER_LAUNCH_SCRIPT.equals(path[3])) {
|
||||
continue;
|
||||
}
|
||||
String log = path[1] + "/" + path[2] + "/" + path[3];
|
||||
if (!Objects.equals(archived.get(log), entry.getSize())) {
|
||||
putContainerLog(entries, accountId, region, folder.bucket(), folder.key() + log + ".gz");
|
||||
archived.put(log, entry.getSize());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void archiveLog(String name, String log, Map<String, Long> archived, String accountId, String region,
|
||||
S3Uri folder) throws IOException {
|
||||
try (InputStream archive = lifecycleManager.getDockerClient()
|
||||
@@ -381,7 +524,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
|
||||
@Override
|
||||
public SparkJobRunner.Storage hdfs(String clusterId, String accountId, String region, String host, String image,
|
||||
String dockerNetwork, HiveMetastore hiveMetastore, Yarn yarn,
|
||||
String dockerNetwork, HiveMetastore hiveMetastore, Supplier<Yarn> yarnNow,
|
||||
BooleanSupplier stopped) {
|
||||
String name = hdfsName(clusterId);
|
||||
String network = network(dockerNetwork);
|
||||
@@ -399,7 +542,12 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
boolean shared = sharesNamespace(network);
|
||||
long deadline = nanoTime.getAsLong() + hdfsStartTimeout.toNanos();
|
||||
synchronized (starting.computeIfAbsent(clusterId, id -> new Object())) {
|
||||
// Read here, so a resize before this took the lock counts, and one after it waits and finds these nodes.
|
||||
Yarn yarn = yarnNow != null ? yarnNow.get() : null;
|
||||
NodeRequest nodeRequest = yarn == null ? null
|
||||
: new NodeRequest(clusterId, accountId, region, host, imageId, yarn);
|
||||
String containerId = null;
|
||||
List<String> nodes = List.of();
|
||||
// One found running whose daemon has just exited stops before it is ready, and is started again, once.
|
||||
for (int attempt = 0; containerId == null; attempt++) {
|
||||
stopIfStopped(clusterId, teardown, stopped);
|
||||
@@ -416,6 +564,8 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
running.add(name);
|
||||
String candidate = found ? name
|
||||
: start(clusterId, accountId, region, host, imageId, dockerNetwork, hiveMetastore, yarn);
|
||||
// Before it is awaited, as its readiness needs a DataNode of theirs.
|
||||
nodes = nodeRequest != null ? reconcileNodes(nodeRequest, teardown) : List.of();
|
||||
if (awaitReady(clusterId, candidate, deadline, teardown, stopped)) {
|
||||
containerId = candidate;
|
||||
} else if (!found) {
|
||||
@@ -428,12 +578,401 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
if (shared) {
|
||||
return volumes(clusterId).withHdfs(host, LOOPBACK, null);
|
||||
}
|
||||
if (nodeRequest != null) {
|
||||
awaitNodes(nodeRequest, nodes, deadline, teardown, stopped);
|
||||
nodeRequests.put(clusterId, nodeRequest);
|
||||
}
|
||||
SparkJobRunner.Storage storage = volumes(clusterId).withHdfs(host, address(clusterId, containerId), name);
|
||||
if (hiveMetastore != null) {
|
||||
storage = storage.withHiveMetastore("thrift://" + host + ":" + HIVE_METASTORE_PORT);
|
||||
}
|
||||
if (yarn == null) {
|
||||
return storage;
|
||||
}
|
||||
// Its executors reach Floci's S3 from the node, at Floci's address on the cluster's network.
|
||||
return yarn != null ? storage.withYarn(host, flociEndpointOn(name)) : storage;
|
||||
storage = storage.withYarn(host, flociEndpointOn(name));
|
||||
return yarn.nodes().stream().anyMatch(Node::core) ? storage.withReplication(yarn.replication()) : storage;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resize(String clusterId, Supplier<Yarn> yarn) {
|
||||
long teardown = teardowns.get();
|
||||
try {
|
||||
synchronized (starting.computeIfAbsent(clusterId, id -> new Object())) {
|
||||
NodeRequest known = nodeRequests.get(clusterId);
|
||||
if (known == null) {
|
||||
return;
|
||||
}
|
||||
// Read here too, so of two resizes the one that takes the lock last applies what the cluster says now.
|
||||
NodeRequest request = known.resizedTo(yarn.get());
|
||||
nodeRequests.put(clusterId, request);
|
||||
reconcileNodes(request, teardown);
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not resize the nodes of EMR cluster {0}: {1}", clusterId, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// A cluster's core and task nodes: one wanted and not running in the image starts, on the data its volume keeps, one
|
||||
// no longer wanted is decommissioned on a thread of its own, and one being decommissioned that is wanted again
|
||||
// carries on. A core node found only as its volume, as a shutdown leaves one it cut off while it was decommissioned,
|
||||
// starts again on its data to be decommissioned, so HDFS moves its blocks; a task node's volume goes, as it holds
|
||||
// none. The names of those wanted.
|
||||
private List<String> reconcileNodes(NodeRequest request, long teardown) {
|
||||
String clusterId = request.clusterId();
|
||||
Map<String, Container> present = nodeContainers(clusterId);
|
||||
Map<String, Draining> leaving = draining.computeIfAbsent(clusterId, id -> new ConcurrentHashMap<>());
|
||||
boolean changed = false;
|
||||
List<String> wanted = new ArrayList<>();
|
||||
for (Node node : request.yarn().nodes()) {
|
||||
String name = nodeName(clusterId, node);
|
||||
wanted.add(name);
|
||||
changed |= leaving.remove(name) != null;
|
||||
Container container = present.get(name);
|
||||
if (container == null || !"running".equals(container.getState())
|
||||
|| !request.imageId().equals(container.getImageId())) {
|
||||
startNode(request, node.host(), node.core(), name, teardown);
|
||||
} else {
|
||||
runningNodes.add(name);
|
||||
}
|
||||
}
|
||||
for (Map.Entry<String, Container> node : present.entrySet()) {
|
||||
if (!wanted.contains(node.getKey()) && !leaving.containsKey(node.getKey())) {
|
||||
leaving.put(node.getKey(), draining(node.getValue().getLabels()));
|
||||
runningNodes.add(node.getKey());
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
for (Map.Entry<String, Map<String, String>> volume : nodeVolumes(clusterId).entrySet()) {
|
||||
String name = volume.getKey();
|
||||
if (wanted.contains(name) || present.containsKey(name) || leaving.containsKey(name)) {
|
||||
continue;
|
||||
}
|
||||
Draining node = draining(volume.getValue());
|
||||
if (node.core()) {
|
||||
startNode(request, node.host(), true, name, teardown);
|
||||
leaving.put(name, node);
|
||||
changed = true;
|
||||
} else {
|
||||
lifecycleManager.removeVolume(name);
|
||||
}
|
||||
}
|
||||
if (changed) {
|
||||
syncExcludes(clusterId, leaving.values());
|
||||
}
|
||||
if (!leaving.isEmpty() && decommissioning.add(clusterId)) {
|
||||
decommissions.execute(() -> decommission(request, teardown));
|
||||
}
|
||||
return wanted;
|
||||
}
|
||||
|
||||
// A node being decommissioned, as its container's or its volume's labels say, with an hour and a minute to go in.
|
||||
private Draining draining(Map<String, String> labels) {
|
||||
Map<String, String> known = labels != null ? labels : Map.of();
|
||||
return new Draining(known.get(NODE_HOST_LABEL), Boolean.parseBoolean(known.get(NODE_CORE_LABEL)),
|
||||
nanoTime.getAsLong() + GRACEFUL_DECOMMISSION.plus(DECOMMISSION_MARGIN).toNanos());
|
||||
}
|
||||
|
||||
// A node's container, started on the data its volume keeps; one whose start a teardown passed goes, as the teardown's
|
||||
// sweep may have looked before it was there.
|
||||
private void startNode(NodeRequest request, String host, boolean core, String name, long teardown) {
|
||||
String clusterId = request.clusterId();
|
||||
Yarn yarn = request.yarn();
|
||||
// Known before it starts, so a teardown while it starts removes it.
|
||||
runningNodes.add(name);
|
||||
lifecycleManager.removeIfExistsStrict(name);
|
||||
// Its volume says whose it is too, so a shutdown that removes its container leaves it findable.
|
||||
Map<String, String> volumeLabels = labels(clusterId, request.accountId(), request.region(), COMPONENT);
|
||||
volumeLabels.put(NODE_HOST_LABEL, host);
|
||||
volumeLabels.put(NODE_CORE_LABEL, String.valueOf(core));
|
||||
lifecycleManager.ensureVolume(name, volumeLabels);
|
||||
Map<String, String> labels = labels(clusterId, request.accountId(), request.region(), NODE_COMPONENT);
|
||||
labels.put(NODE_HOST_LABEL, host);
|
||||
labels.put(NODE_CORE_LABEL, String.valueOf(core));
|
||||
ContainerBuilder.Builder spec = containerBuilder.newContainer(request.imageId())
|
||||
.withName(name)
|
||||
.withUser("root")
|
||||
.withEntrypoint(List.of("/bin/bash", "-c", NODE_SCRIPT))
|
||||
.withEnv("FLOCI_HDFS_HOST", request.host())
|
||||
.withEnv("FLOCI_HDFS_BIND", "0.0.0.0")
|
||||
.withEnv(NODE_HOST_VARIABLE, host)
|
||||
.withEnv(REPLICATION_VARIABLE, String.valueOf(yarn.replication()))
|
||||
.withEnv(YARN_MEMORY_VARIABLE, String.valueOf(yarn.memoryMb()))
|
||||
.withEnv(YARN_VCORES_VARIABLE, String.valueOf(yarn.vcores()))
|
||||
.withEnv("HADOOP_CONF_DIR", HDFS_CONF)
|
||||
.withEnv("HADOOP_LOG_DIR", "/tmp/floci-hdfs-logs")
|
||||
.withNamedVolume(name, "/mnt")
|
||||
.withDockerNetwork(Optional.of(hdfsName(clusterId)))
|
||||
.withDnsName(host)
|
||||
.withLogRotation()
|
||||
.withLabels(labels)
|
||||
// Its executors reach Floci, Floci on the host by its address, Floci's own certificate trusted.
|
||||
.withHostDockerInternalOnLinux()
|
||||
.withJavaTrustStore();
|
||||
if (core) {
|
||||
spec.withEnv(NODE_CORE_VARIABLE, "1");
|
||||
}
|
||||
if (yarn.hadoopFolder() != null) {
|
||||
spec.withEnv(HADOOP_FOLDER_VARIABLE, yarn.hadoopFolder());
|
||||
}
|
||||
lifecycleManager.createAndStart(spec.build());
|
||||
if (teardowns.get() != teardown) {
|
||||
removeNode(name, false);
|
||||
return;
|
||||
}
|
||||
LOG.infov("Started the {0} node {1} of EMR cluster {2}", core ? "core" : "task", host, clusterId);
|
||||
}
|
||||
|
||||
// Each node ready by the deadline; one that stopped before it was is started again, once.
|
||||
private void awaitNodes(NodeRequest request, List<String> nodes, long deadline, long teardown,
|
||||
BooleanSupplier stopped) {
|
||||
List<String> wanted = nodes;
|
||||
for (int attempt = 0; ; attempt++) {
|
||||
boolean ready = true;
|
||||
for (String node : wanted) {
|
||||
ready = ready && awaitReady(request.clusterId(), node, deadline, teardown, stopped);
|
||||
}
|
||||
if (ready) {
|
||||
return;
|
||||
}
|
||||
stopIfStopped(request.clusterId(), teardown, stopped);
|
||||
if (attempt > 0) {
|
||||
throw new IllegalStateException("A node of EMR cluster " + request.clusterId()
|
||||
+ " stopped before it was ready");
|
||||
}
|
||||
wanted = reconcileNodes(request, teardown);
|
||||
}
|
||||
}
|
||||
|
||||
// The containers of a cluster's core and task nodes, running or not, by name.
|
||||
private Map<String, Container> nodeContainers(String clusterId) {
|
||||
Map<String, Container> nodes = new LinkedHashMap<>();
|
||||
List<Container> containers = lifecycleManager.getDockerClient().listContainersCmd().withShowAll(true)
|
||||
.withLabelFilter(Map.of(ContainerStorageHelper.COMPONENT_LABEL, NODE_COMPONENT,
|
||||
ContainerStorageHelper.RESOURCE_ID_LABEL, clusterId,
|
||||
ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)))
|
||||
.exec();
|
||||
for (Container container : containers) {
|
||||
nodes.put(container.getNames()[0].substring(1), container);
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
|
||||
// The volumes of a cluster's core and task nodes, with their labels, by name, whether a container has them or not.
|
||||
private Map<String, Map<String, String>> nodeVolumes(String clusterId) {
|
||||
ListVolumesResponse response = lifecycleManager.getDockerClient().listVolumesCmd()
|
||||
.withFilter("label", List.of(ContainerStorageHelper.COMPONENT_LABEL + "=" + COMPONENT,
|
||||
ContainerStorageHelper.RESOURCE_ID_LABEL + "=" + clusterId,
|
||||
ContainerStorageHelper.OWNER_LABEL + "=" + ContainerStorageHelper.ownerIdentity(config),
|
||||
NODE_HOST_LABEL))
|
||||
.exec();
|
||||
Map<String, Map<String, String>> volumes = new LinkedHashMap<>();
|
||||
if (response != null && response.getVolumes() != null) {
|
||||
for (InspectVolumeResponse volume : response.getVolumes()) {
|
||||
Map<String, String> labels = volume.getLabels() != null ? volume.getLabels() : Map.of();
|
||||
if (clusterId.equals(labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL))
|
||||
&& labels.containsKey(NODE_HOST_LABEL)) {
|
||||
volumes.put(volume.getName(), labels);
|
||||
}
|
||||
}
|
||||
}
|
||||
return volumes;
|
||||
}
|
||||
|
||||
// Writes the lists of the nodes being decommissioned on the primary node, when they changed, a primary node started
|
||||
// again holding none, and has HDFS and YARN read them: "both YARN NodeManager and HDFS DataNode daemons must be
|
||||
// decommissioned" on a core node, and only the first on a task node. A node leaves YARN's list once it has gone, as
|
||||
// a node that comes back under its name is a new one, and HDFS's once the NameNode has it dead (DEAD_NODE_WAIT). A
|
||||
// refresh that fails takes its list away, so the next round's differs and is read again.
|
||||
private void syncExcludes(String clusterId, Collection<Draining> nodes) {
|
||||
String yarnHosts = hostLines(nodes.stream().filter(Draining::hdfsDone).map(Draining::host).toList());
|
||||
List<String> dfs = new ArrayList<>(nodes.stream().filter(Draining::core).map(Draining::host).toList());
|
||||
dfs.addAll(departed.getOrDefault(clusterId, Map.of()).keySet());
|
||||
String dfsHosts = hostLines(dfs);
|
||||
String script = String.join("\n", HADOOP_FOLDER_SETUP,
|
||||
"printf '" + yarnHosts + "' > " + YARN_EXCLUDE + ".new || exit 1",
|
||||
"printf '" + dfsHosts + "' > " + DFS_EXCLUDE + ".new || exit 1",
|
||||
"if ! cmp -s " + YARN_EXCLUDE + ".new " + YARN_EXCLUDE + "; then mv " + YARN_EXCLUDE + ".new "
|
||||
+ YARN_EXCLUDE + " && yarn rmadmin -refreshNodes -g " + GRACEFUL_DECOMMISSION.toSeconds()
|
||||
+ " -server || { rm -f " + YARN_EXCLUDE + "; exit 1; }; fi",
|
||||
"if ! cmp -s " + DFS_EXCLUDE + ".new " + DFS_EXCLUDE + "; then mv " + DFS_EXCLUDE + ".new "
|
||||
+ DFS_EXCLUDE + " && hdfs dfsadmin -refreshNodes || { rm -f " + DFS_EXCLUDE + "; exit 1; }; fi");
|
||||
try {
|
||||
ContainerExec.Result result = ContainerExec.run(lifecycleManager.getDockerClient(), hdfsName(clusterId),
|
||||
new String[]{"bash", "-c", script}, NODE_COMMAND_SECONDS);
|
||||
if (result.exitCode() != 0) {
|
||||
LOG.warnv("Could not tell EMR cluster {0} which nodes to decommission, which the next round tries"
|
||||
+ " again: {1}", clusterId, result.stderr());
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not tell EMR cluster {0} which nodes to decommission, which the next round tries"
|
||||
+ " again: {1}", clusterId, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static String hostLines(List<String> hosts) {
|
||||
return hosts.stream().map(host -> host + "\\n").collect(Collectors.joining());
|
||||
}
|
||||
|
||||
// A thread's work: each node being decommissioned goes once HDFS and YARN have let it, or the time it was given is
|
||||
// up, and its containers' logs with it. It ends once the last core node to go is dead to the NameNode, or with its
|
||||
// cluster or a teardown. A round that fails, Docker or a command on the primary node failing, leaves every node as it
|
||||
// is, and the next asks again.
|
||||
private void decommission(NodeRequest request, long teardown) {
|
||||
String clusterId = request.clusterId();
|
||||
boolean ended = false;
|
||||
boolean failing = false;
|
||||
try {
|
||||
while (true) {
|
||||
try {
|
||||
synchronized (starting.computeIfAbsent(clusterId, id -> new Object())) {
|
||||
if (decommissionRound(request, teardown)) {
|
||||
// Under the lock, so a resize from now on starts a thread of its own.
|
||||
decommissioning.remove(clusterId);
|
||||
ended = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
failing = false;
|
||||
} catch (RuntimeException e) {
|
||||
if (failing) {
|
||||
LOG.debugv(e, "Could not decommission the nodes of EMR cluster {0} again: {1}", clusterId,
|
||||
e.getMessage());
|
||||
} else {
|
||||
LOG.warnv(e, "Could not decommission the nodes of EMR cluster {0}, which the next round tries"
|
||||
+ " again: {1}", clusterId, e.getMessage());
|
||||
}
|
||||
failing = true;
|
||||
}
|
||||
Thread.sleep(decommissionPoll.toMillis());
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
} finally {
|
||||
if (!ended) {
|
||||
decommissioning.remove(clusterId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// One round of a cluster's decommissioning, under its lock: true once there is nothing left to do.
|
||||
private boolean decommissionRound(NodeRequest request, long teardown) {
|
||||
String clusterId = request.clusterId();
|
||||
Map<String, Draining> leaving = draining.get(clusterId);
|
||||
if (leaving == null || teardowns.get() != teardown) {
|
||||
return true;
|
||||
}
|
||||
Map<String, Long> gone = departed.computeIfAbsent(clusterId, id -> new ConcurrentHashMap<>());
|
||||
long now = nanoTime.getAsLong();
|
||||
gone.values().removeIf(at -> now - at >= DEAD_NODE_WAIT.toNanos());
|
||||
syncExcludes(clusterId, leaving.values());
|
||||
for (Map.Entry<String, Draining> node : List.copyOf(leaving.entrySet())) {
|
||||
boolean late = now >= node.getValue().deadline();
|
||||
if (late || decommissioned(request, node.getKey(), node.getValue(), teardown)) {
|
||||
if (late) {
|
||||
LOG.warnv("Node {0} of EMR cluster {1} was not decommissioned in time, and goes anyway",
|
||||
node.getValue().host(), clusterId);
|
||||
}
|
||||
if (removeDecommissioned(request, node.getKey())) {
|
||||
leaving.remove(node.getKey());
|
||||
if (node.getValue().core()) {
|
||||
gone.put(node.getValue().host(), nanoTime.getAsLong());
|
||||
}
|
||||
}
|
||||
} else if (!node.getValue().hdfsDone() && hdfsDecommissioned(clusterId, node.getValue())) {
|
||||
// YARN is told on the next round.
|
||||
leaving.put(node.getKey(), node.getValue().hdfsDecommissioned());
|
||||
}
|
||||
}
|
||||
if (leaving.isEmpty() && gone.isEmpty()) {
|
||||
syncExcludes(clusterId, leaving.values());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Whether YARN has finished with a node HDFS has finished with, or it has stopped with nothing left for HDFS to move.
|
||||
// A core node that stopped before HDFS moved its blocks holds them still, so it starts again on its data, and one
|
||||
// Docker cannot tell the state of is asked about again on the next round.
|
||||
private boolean decommissioned(NodeRequest request, String name, Draining node, long teardown) {
|
||||
ContainerLiveness liveness = lifecycleManager.probeContainer(name);
|
||||
if (liveness == ContainerLiveness.UNKNOWN) {
|
||||
return false;
|
||||
}
|
||||
if (liveness == ContainerLiveness.NOT_RUNNING) {
|
||||
if (node.hdfsDone()) {
|
||||
return true;
|
||||
}
|
||||
LOG.infov("The core node {0} of EMR cluster {1} stopped before HDFS moved its blocks, and starts again on"
|
||||
+ " its data", node.host(), request.clusterId());
|
||||
startNode(request, node.host(), true, name, teardown);
|
||||
return false;
|
||||
}
|
||||
return node.hdfsDone() && onPrimary(request.clusterId(), "curl -sf -m 5 '" + RESOURCE_MANAGER_NODES
|
||||
+ "DECOMMISSIONED' | grep -q '\"nodeHostName\":\"" + node.host() + "\"'");
|
||||
}
|
||||
|
||||
// Whether HDFS has moved a core node's blocks to the nodes that stay.
|
||||
private boolean hdfsDecommissioned(String clusterId, Draining node) {
|
||||
return onPrimary(clusterId, "curl -sf -m 5 '" + NAMENODE_JMX + "NameNodeInfo' | grep -Eq '" + node.host()
|
||||
+ ":9866[^}]*Decommissioned'");
|
||||
}
|
||||
|
||||
private boolean onPrimary(String clusterId, String command) {
|
||||
return ContainerExec.run(lifecycleManager.getDockerClient(), hdfsName(clusterId),
|
||||
new String[]{"bash", "-c", command}, NODE_COMMAND_SECONDS).exitCode() == 0;
|
||||
}
|
||||
|
||||
// A node that has been decommissioned goes, with its data, as an EC2 instance's disks go with it, its containers'
|
||||
// logs in S3 first, while its container is there. Whether it has gone: one Docker keeps, or keeps the data of, is
|
||||
// tried again on the next round.
|
||||
private boolean removeDecommissioned(NodeRequest request, String name) {
|
||||
if (request.yarn().logFolder() != null && runningNodes.contains(name)) {
|
||||
archiveNodeLogs(request.clusterId(), name, request.accountId(), request.region(),
|
||||
request.yarn().logFolder());
|
||||
}
|
||||
if (!removeNode(name, true)) {
|
||||
LOG.warnv("Docker kept node {0} of EMR cluster {1} or its data, which the next round removes",
|
||||
name, request.clusterId());
|
||||
return false;
|
||||
}
|
||||
LOG.infov("Node {0} of EMR cluster {1} was decommissioned", name, request.clusterId());
|
||||
return true;
|
||||
}
|
||||
|
||||
// Removes a node's container and, when asked, its volume; a removal Docker refuses leaves it known, so the next
|
||||
// reset or shutdown tries again. Whether it has gone.
|
||||
private boolean removeNode(String name, boolean withVolume) {
|
||||
try {
|
||||
lifecycleManager.removeIfExistsStrict(name);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not remove the EMR node container {0}: {1}", name, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
runningNodes.remove(name);
|
||||
archivedLogs.remove(name);
|
||||
return !withVolume || lifecycleManager.removeVolume(name);
|
||||
}
|
||||
|
||||
private record NodeRequest(String clusterId, String accountId, String region, String host, String imageId,
|
||||
Yarn yarn) {
|
||||
|
||||
NodeRequest resizedTo(Yarn resized) {
|
||||
return new NodeRequest(clusterId, accountId, region, host, imageId, resized);
|
||||
}
|
||||
}
|
||||
|
||||
// A node being decommissioned, which goes anyway at the nanoTime deadline, its own, so one a later resize adds has
|
||||
// the whole time too. A core node goes to YARN's decommission only once HDFS has moved its blocks: a decommissioned
|
||||
// NodeManager exits, which ends its container, the DataNode with it.
|
||||
private record Draining(String host, boolean core, boolean hdfsDone, long deadline) {
|
||||
Draining(String host, boolean core, long deadline) {
|
||||
this(host, core, !core, deadline);
|
||||
}
|
||||
|
||||
Draining hdfsDecommissioned() {
|
||||
return new Draining(host, core, true, deadline);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -560,9 +1099,17 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
.withDockerNetwork(Optional.of(shared ? network : name))
|
||||
.withLogRotation()
|
||||
.withLabels(labels(clusterId, accountId, region, HDFS_COMPONENT));
|
||||
if (!shared) {
|
||||
// Its core and task nodes reach it by its name on the network, which a new address does not change.
|
||||
spec.withDnsName(host);
|
||||
}
|
||||
if (yarn != null) {
|
||||
spec.withEnv(YARN_MEMORY_VARIABLE, String.valueOf(yarn.memoryMb()))
|
||||
.withEnv(YARN_VCORES_VARIABLE, String.valueOf(yarn.vcores()));
|
||||
.withEnv(YARN_VCORES_VARIABLE, String.valueOf(yarn.vcores()))
|
||||
.withEnv(REPLICATION_VARIABLE, String.valueOf(yarn.replication()));
|
||||
if (!yarn.primaryWorks()) {
|
||||
spec.withEnv(NODE_WORKERS_VARIABLE, "1");
|
||||
}
|
||||
if (yarn.hadoopFolder() != null) {
|
||||
spec.withEnv(HADOOP_FOLDER_VARIABLE, yarn.hadoopFolder());
|
||||
}
|
||||
@@ -700,7 +1247,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
|
||||
// What a node that did not become ready last wrote, in Floci's log, as the container goes with its cluster.
|
||||
private void logNodeOutput(String clusterId, String containerId) {
|
||||
LOG.warnv("The primary node of EMR cluster {0} did not become ready. It last wrote:\n{1}", clusterId,
|
||||
LOG.warnv("A node of EMR cluster {0}, {1}, did not become ready. It last wrote:\n{2}", clusterId, containerId,
|
||||
lifecycleManager.lastLogLines(containerId, NODE_LOG_LINES, NODE_LOG_READ));
|
||||
}
|
||||
|
||||
@@ -717,6 +1264,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
}
|
||||
}
|
||||
|
||||
// The name of a cluster's core or task node's container, and of the volume its data is in.
|
||||
private String nodeName(String clusterId, Node node) {
|
||||
return ContainerStorageHelper.dockerName(config, SERVICE + "-" + clusterId + "-node-" + node.id());
|
||||
}
|
||||
|
||||
// The name of a cluster's HDFS container, of the volume its data is in, and of the Docker network it is on.
|
||||
private String hdfsName(String clusterId) {
|
||||
return ContainerStorageHelper.dockerName(config, SERVICE + "-" + clusterId + "-hdfs");
|
||||
@@ -735,6 +1287,23 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
// Its HDFS goes first, as its container holds the volume of its data and its network, and its lock with it, so
|
||||
// the clusters that have ended leave none behind.
|
||||
starting.remove(clusterId);
|
||||
nodeRequests.remove(clusterId);
|
||||
draining.remove(clusterId);
|
||||
departed.remove(clusterId);
|
||||
boolean nodesGone = true;
|
||||
try {
|
||||
for (String node : nodeContainers(clusterId).keySet()) {
|
||||
nodesGone &= removeNode(node, true);
|
||||
}
|
||||
// A node's data whose container a shutdown removed, which no list of containers finds.
|
||||
for (String volume : nodeVolumes(clusterId).keySet()) {
|
||||
nodesGone &= lifecycleManager.removeVolume(volume);
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
// The rest is removed all the same, and the cluster's storage is asked for again.
|
||||
LOG.warnv(e, "Could not find the nodes of EMR cluster {0} to remove: {1}", clusterId, e.getMessage());
|
||||
nodesGone = false;
|
||||
}
|
||||
boolean containerGone = removeKnown(hdfsName(clusterId));
|
||||
SparkJobRunner.Storage storage = volumes(clusterId);
|
||||
// Each is tried, so one Docker refused does not keep the others.
|
||||
@@ -742,7 +1311,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
boolean homeGone = lifecycleManager.removeVolume(storage.home());
|
||||
boolean mntGone = lifecycleManager.removeVolume(storage.mnt());
|
||||
return lifecycleManager.removeVolume(hdfsName(clusterId)) && mntGone && homeGone && networkGone
|
||||
&& containerGone;
|
||||
&& containerGone && nodesGone;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -754,6 +1323,12 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
@Override
|
||||
public void stopManagedContainers() {
|
||||
teardowns.incrementAndGet();
|
||||
nodeRequests.clear();
|
||||
draining.clear();
|
||||
departed.clear();
|
||||
for (String name : List.copyOf(runningNodes)) {
|
||||
removeNode(name, false);
|
||||
}
|
||||
for (String name : List.copyOf(running)) {
|
||||
removeKnown(name);
|
||||
}
|
||||
@@ -786,6 +1361,21 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
|
||||
@Override
|
||||
public void removeAllBut(Set<String> kept) {
|
||||
// Each sweep on its own, so Docker refusing one list does not keep the others from going.
|
||||
try {
|
||||
for (Container container : lifecycleManager.getDockerClient().listContainersCmd().withShowAll(true)
|
||||
.withLabelFilter(Map.of(ContainerStorageHelper.COMPONENT_LABEL, NODE_COMPONENT,
|
||||
ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)))
|
||||
.exec()) {
|
||||
Map<String, String> labels = container.getLabels() != null ? container.getLabels() : Map.of();
|
||||
String name = container.getNames()[0].substring(1);
|
||||
runningNodes.add(name);
|
||||
if (!kept.contains(labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL))) {
|
||||
removeNode(name, false);
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not remove the nodes of EMR clusters that have ended: {0}", e.getMessage());
|
||||
}
|
||||
try {
|
||||
for (Container container : lifecycleManager.getDockerClient().listContainersCmd().withShowAll(true)
|
||||
.withLabelFilter(Map.of(ContainerStorageHelper.COMPONENT_LABEL, HDFS_COMPONENT,
|
||||
|
||||
@@ -332,8 +332,10 @@ public class EmrHandler {
|
||||
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, terminated));
|
||||
arr.add(syntheticInstanceNode(cluster, group, first + i, EmrService.privateIpAddress(number, i + 1),
|
||||
terminated));
|
||||
}
|
||||
if (group != primary) {
|
||||
next += count;
|
||||
@@ -752,13 +754,12 @@ public class EmrHandler {
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode syntheticInstanceNode(EmrCluster cluster, EmrInstanceGroup group, int index,
|
||||
private ObjectNode syntheticInstanceNode(EmrCluster cluster, EmrInstanceGroup group, int index, String privateIp,
|
||||
boolean terminated) {
|
||||
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()));
|
||||
String privateIp = EmrService.privateIpAddress(index);
|
||||
node.put("PrivateDnsName", AwsRegions.ec2PrivateIpDnsName(privateIp, cluster.getRegion()));
|
||||
node.put("PrivateIpAddress", privateIp);
|
||||
node.put("InstanceGroupId", group.getId());
|
||||
|
||||
@@ -132,6 +132,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
|
||||
private final String dockerNetwork;
|
||||
// What the NodeManager of a cluster that runs YARN offers its containers.
|
||||
private final ClusterStorage.Yarn nodeManager;
|
||||
private final int maxWorkerNodes;
|
||||
// The steps a thread is running, by account and id; a RUNNING container step not here was left by a restart.
|
||||
private final Set<String> executing = new HashSet<>();
|
||||
// Likewise the clusters a thread is bootstrapping.
|
||||
@@ -253,6 +254,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
|
||||
this.dockerNetwork = config.services().emr().dockerNetwork().orElse(null);
|
||||
this.nodeManager = new ClusterStorage.Yarn(config.services().emr().yarnNodeMemoryMb(),
|
||||
config.services().emr().yarnNodeVcores());
|
||||
this.maxWorkerNodes = config.services().emr().yarnMaxWorkerNodes();
|
||||
this.lifecycle = new EmrClusterLifecycle(config.services().emr().clusterStartupDelaySeconds(),
|
||||
config.services().emr().stepDurationSeconds(),
|
||||
config.services().emr().clusterTerminationDelaySeconds(), eventPublisher,
|
||||
@@ -389,6 +391,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
|
||||
f.setProvisionedSpotCapacity(f.getTargetSpotCapacity());
|
||||
f.setState("RUNNING");
|
||||
}
|
||||
cluster.setProvisionedCoreNodes(coreNodes(cluster));
|
||||
cluster.getSteps().forEach(step -> step.setId("s-" + randomId(13)));
|
||||
lifecycle.start(cluster, now(), region);
|
||||
store(cluster);
|
||||
@@ -575,6 +578,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
|
||||
ids.add(group.getId());
|
||||
}
|
||||
clusterStore.put(clusterId, cluster);
|
||||
resizeNodes(cluster);
|
||||
return ids;
|
||||
});
|
||||
}
|
||||
@@ -630,6 +634,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
|
||||
}
|
||||
}
|
||||
touched.forEach(clusterStore::put);
|
||||
touched.values().forEach(this::resizeNodes);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -669,6 +674,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
|
||||
fleet.setState("RUNNING");
|
||||
cluster.getInstanceFleets().add(fleet);
|
||||
clusterStore.put(clusterId, cluster);
|
||||
resizeNodes(cluster);
|
||||
return fleet.getId();
|
||||
});
|
||||
}
|
||||
@@ -712,6 +718,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
|
||||
fleet.setProvisionedOnDemandCapacity(onDemand);
|
||||
fleet.setProvisionedSpotCapacity(spot);
|
||||
clusterStore.put(clusterId, cluster);
|
||||
resizeNodes(cluster);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1516,8 +1523,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
|
||||
String clusterId = cluster.getId();
|
||||
String hdfsHost = masterPrivateDnsName(cluster);
|
||||
String hdfsImage = hdfsImage(cluster.getReleaseLabel());
|
||||
ClusterStorage.Yarn nodeYarn = yarn
|
||||
? nodeManager.withHadoopFolder(EmrReleaseImages.hadoopFolder(cluster.getReleaseLabel())) : null;
|
||||
Supplier<ClusterStorage.Yarn> nodeYarn = yarn ? currentYarn(cluster, accountId, region) : null;
|
||||
ClusterStorage.HiveMetastore hiveMetastore = EmrSparkSteps.installsHive(cluster.getReleaseLabel(),
|
||||
cluster.getApplications(), SNAPSHOT_MAPPER)
|
||||
? new ClusterStorage.HiveMetastore(instanceProfileRole(cluster, accountId),
|
||||
@@ -1692,6 +1698,118 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
|
||||
return () -> releaseImages.image(release, spark, hive, withHive);
|
||||
}
|
||||
|
||||
/**
|
||||
* The YARN a cluster runs: the service's capacity on each node, its core and task nodes, its HDFS's copies. Its
|
||||
* primary node holds a DataNode and a NodeManager unless the cluster was created with core nodes that run, so one
|
||||
* created without keeps both as core nodes are added, the blocks it holds staying in reach.
|
||||
*/
|
||||
private ClusterStorage.Yarn yarnOf(EmrCluster cluster) {
|
||||
List<ClusterStorage.Node> nodes = workerNodes(cluster);
|
||||
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))
|
||||
.withPrimaryWorking(cluster.getProvisionedCoreNodes() == 0 || coreNodes == 0);
|
||||
}
|
||||
|
||||
// What a cluster asks of YARN when it is read, which may be later than now; what it asks now, if it has gone by then.
|
||||
private Supplier<ClusterStorage.Yarn> currentYarn(EmrCluster cluster, String accountId, String region) {
|
||||
String clusterId = cluster.getId();
|
||||
ClusterStorage.Yarn asked = yarnOf(cluster);
|
||||
return () -> RequestScopes.callAs(accountId, region,
|
||||
() -> call(() -> clusterStore.get(clusterId).map(this::yarnOf).orElse(asked)));
|
||||
}
|
||||
|
||||
// A resize reaches the nodes of a cluster a step has started them on, on another thread, as they take a while;
|
||||
// on any other cluster the first step starts those it asks for then.
|
||||
private void resizeNodes(EmrCluster cluster) {
|
||||
if (cluster.isStorageCreated() && runsYarn(cluster)) {
|
||||
Supplier<ClusterStorage.Yarn> yarn = currentYarn(cluster, regionResolver.getAccountId(), regionOf(cluster));
|
||||
String clusterId = cluster.getId();
|
||||
stepExecutor.execute(() -> clusterStorage.resize(clusterId, yarn));
|
||||
}
|
||||
}
|
||||
|
||||
// A cluster's core and task nodes as containers: "Core nodes run the Data Node daemon" and "a core node runs YARN
|
||||
// NodeManager daemons", and "Task nodes don't run the Data Node daemon". No more than the setting allows, core
|
||||
// nodes first, as they hold HDFS, and no fewer core nodes than HDFS keeps copies, as "Amazon EMR will not allow
|
||||
// clusters to scale core nodes below dfs.replication". A fleet's unit of capacity is one node.
|
||||
private List<ClusterStorage.Node> workerNodes(EmrCluster cluster) {
|
||||
int floor = Math.min(cluster.getProvisionedCoreNodes(), replication(cluster));
|
||||
List<ClusterStorage.Node> core = new ArrayList<>();
|
||||
List<ClusterStorage.Node> task = new ArrayList<>();
|
||||
for (EmrInstanceGroup group : cluster.getInstanceGroups()) {
|
||||
boolean isCore = "CORE".equals(group.getInstanceGroupType());
|
||||
if (isCore || "TASK".equals(group.getInstanceGroupType())) {
|
||||
int count = group.getRequestedInstanceCount();
|
||||
addNodes(cluster, groupNumber(cluster.getInstanceGroups(), group), isCore ? Math.max(count, floor) : count,
|
||||
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;
|
||||
}
|
||||
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<ClusterStorage.Node> nodes = new ArrayList<>(core);
|
||||
nodes.addAll(task);
|
||||
if (nodes.size() > maxWorkerNodes) {
|
||||
LOG.infov("EMR cluster {0} asks for {1} core and task nodes, and runs the first {2}, as yarn-max-worker-nodes"
|
||||
+ " says", cluster.getId(), nodes.size(), maxWorkerNodes);
|
||||
return List.copyOf(nodes.subList(0, maxWorkerNodes));
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
|
||||
private static void addNodes(EmrCluster cluster, int group, int count, boolean core,
|
||||
List<ClusterStorage.Node> nodes) {
|
||||
for (int ordinal = 1; ordinal <= count; ordinal++) {
|
||||
nodes.add(new ClusterStorage.Node(group + "-" + ordinal,
|
||||
AwsRegions.ec2PrivateIpDnsName(privateIpAddress(group, ordinal), cluster.getRegion()), core));
|
||||
}
|
||||
}
|
||||
|
||||
// "Amazon EMR sets this value based on the number of core nodes the cluster is provisioned with": 1 "for clusters
|
||||
// that are provisioned with less than four core nodes", 2 "for clusters that are provisioned with less than ten
|
||||
// core nodes", 3 "for all other clusters". "To overwrite the default value, use the hdfs-site classification."
|
||||
private int replication(EmrCluster cluster) {
|
||||
String configured = EmrSparkSteps.hdfsSite(cluster.getConfigurations(), SNAPSHOT_MAPPER).get("dfs.replication");
|
||||
if (configured != null) {
|
||||
Integer copies = aboveZero(configured);
|
||||
if (copies != null) {
|
||||
return copies;
|
||||
}
|
||||
LOG.warnv("The dfs.replication of EMR cluster {0}, {1}, is not a whole number above zero, so it keeps EMR's"
|
||||
+ " default", cluster.getId(), configured);
|
||||
}
|
||||
int core = cluster.getProvisionedCoreNodes();
|
||||
return core < 4 ? 1 : core < 10 ? 2 : 3;
|
||||
}
|
||||
|
||||
// The whole number a setting gives, when it is one above zero, else null.
|
||||
private static Integer aboveZero(String setting) {
|
||||
try {
|
||||
int number = Integer.parseInt(setting.trim());
|
||||
return number > 0 ? number : null;
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static int coreNodes(EmrCluster cluster) {
|
||||
int groups = cluster.getInstanceGroups().stream().filter(group -> "CORE".equals(group.getInstanceGroupType()))
|
||||
.mapToInt(EmrInstanceGroup::getRequestedInstanceCount).sum();
|
||||
int fleets = cluster.getInstanceFleets().stream().filter(fleet -> "CORE".equals(fleet.getInstanceFleetType()))
|
||||
.mapToInt(fleet -> fleet.getTargetOnDemandCapacity() + fleet.getTargetSpotCapacity()).sum();
|
||||
return groups + fleets;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a cluster's primary node runs YARN, which its steps' Spark runs on: "the primary node runs the YARN
|
||||
* ResourceManager service", and a core node "YARN NodeManager daemons, Hadoop MapReduce tasks, and Spark executors".
|
||||
@@ -1820,9 +1938,33 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
|
||||
return "i-" + String.format("%017d", index);
|
||||
}
|
||||
|
||||
/** The private IPv4 address ListInstances gives a cluster's instance {@code index}, counted from 1. */
|
||||
static String privateIpAddress(int index) {
|
||||
return "10.0.0." + index;
|
||||
/**
|
||||
* 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) {
|
||||
return "10." + group + "." + (ordinal - 1) / 254 + "." + ((ordinal - 1) % 254 + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* A cluster's instance group's number in its instances' addresses: 0 for the primary node's group, the first MASTER
|
||||
* group, and from 1 for the others in the order the cluster has them, which only adds to the end.
|
||||
*/
|
||||
static int groupNumber(List<EmrInstanceGroup> groups, EmrInstanceGroup group) {
|
||||
EmrInstanceGroup primary = groups.stream().filter(EmrService::isMasterGroup).findFirst().orElse(null);
|
||||
if (group == primary) {
|
||||
return 0;
|
||||
}
|
||||
int number = 1;
|
||||
for (EmrInstanceGroup other : groups) {
|
||||
if (other == group) {
|
||||
return number;
|
||||
}
|
||||
if (other != primary) {
|
||||
number++;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("The instance group is not one of the cluster's");
|
||||
}
|
||||
|
||||
// The primary instance's: the first of the MASTER group, which ListInstances numbers before the others.
|
||||
@@ -1833,7 +1975,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
|
||||
// The primary instance's private DNS name, as ListInstances gives it, which names the cluster's HDFS: the same
|
||||
// while the other groups resize, so an hdfs:// path naming it keeps leading there.
|
||||
static String masterPrivateDnsName(EmrCluster cluster) {
|
||||
return AwsRegions.ec2PrivateIpDnsName(privateIpAddress(1), cluster.getRegion());
|
||||
return AwsRegions.ec2PrivateIpDnsName(privateIpAddress(0, 1), cluster.getRegion());
|
||||
}
|
||||
|
||||
static boolean isMasterGroup(EmrInstanceGroup group) {
|
||||
|
||||
@@ -53,6 +53,7 @@ final class EmrSparkSteps {
|
||||
// The release pages' core-site, which will "Change values in Hadoop's core-site.xml file", and spark-log4j2,
|
||||
// which will "Change values in Spark's log4j2.properties file".
|
||||
private static final String CORE_SITE = "core-site";
|
||||
private static final String HDFS_SITE = "hdfs-site";
|
||||
private static final String SPARK_LOG4J2 = "spark-log4j2";
|
||||
// And mapred-site, which will "Change values in the MapReduce application's mapred-site.xml file", hadoop-log4j
|
||||
// "Change values in Hadoop's log4j.properties file", and hadoop-env "Change values in the Hadoop environment for
|
||||
@@ -282,6 +283,11 @@ final class EmrSparkSteps {
|
||||
return properties;
|
||||
}
|
||||
|
||||
/** The properties of a cluster's {@code hdfs-site}, of which Floci's HDFS applies {@code dfs.replication}. */
|
||||
static Map<String, String> hdfsSite(String configurations, ObjectMapper objectMapper) {
|
||||
return properties(configurations, objectMapper, HDFS_SITE);
|
||||
}
|
||||
|
||||
/** The properties of a cluster's {@code core-site}, which its steps' {@code hadoop} command gets too. */
|
||||
static Map<String, String> coreSite(String configurations, ObjectMapper objectMapper) {
|
||||
return properties(configurations, objectMapper, CORE_SITE);
|
||||
|
||||
@@ -56,6 +56,9 @@ public class EmrCluster {
|
||||
// Whether the docker runner mode has made the cluster's storage, which goes once the cluster has ended; Floci's
|
||||
// own, as the API has none.
|
||||
private boolean storageCreated;
|
||||
// The core nodes the cluster was created with, which its HDFS's copies of a block follow; Floci's own, as the API
|
||||
// has none.
|
||||
private int provisionedCoreNodes;
|
||||
// The cluster's ManagedScalingPolicy and AutoTerminationPolicy as given, raw JSON; null when none.
|
||||
private String managedScalingPolicy;
|
||||
private String autoTerminationPolicy;
|
||||
@@ -190,6 +193,9 @@ public class EmrCluster {
|
||||
public boolean isStorageCreated() { return storageCreated; }
|
||||
public void setStorageCreated(boolean storageCreated) { this.storageCreated = storageCreated; }
|
||||
|
||||
public int getProvisionedCoreNodes() { return provisionedCoreNodes; }
|
||||
public void setProvisionedCoreNodes(int provisionedCoreNodes) { this.provisionedCoreNodes = provisionedCoreNodes; }
|
||||
|
||||
public String getManagedScalingPolicy() { return managedScalingPolicy; }
|
||||
public void setManagedScalingPolicy(String managedScalingPolicy) { this.managedScalingPolicy = managedScalingPolicy; }
|
||||
|
||||
|
||||
@@ -84,6 +84,9 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
private static final String HADOOP_SITE_VARIABLE = "FLOCI_HADOOP_SITE";
|
||||
private static final String SPARK_LOG4J2_VARIABLE = "FLOCI_SPARK_LOG4J2";
|
||||
private static final String MAPRED_SITE_VARIABLE = "FLOCI_MAPRED_SITE";
|
||||
// The copies of a block a cluster's core nodes keep, as an hdfs-site.xml property: there, as the image's own says two
|
||||
// and a Hadoop client reads hdfs-site.xml after core-site.xml.
|
||||
private static final String HDFS_SITE_VARIABLE = "FLOCI_HDFS_SITE";
|
||||
private static final String HADOOP_LOG4J_VARIABLE = "FLOCI_HADOOP_LOG4J";
|
||||
private static final String HADOOP_ENV_VARIABLE = "FLOCI_HADOOP_ENV";
|
||||
private static final Pattern SHELL_NAME = Pattern.compile("[A-Za-z_][A-Za-z0-9_]*");
|
||||
@@ -167,6 +170,9 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
" }",
|
||||
" site core-site.xml \"$" + HADOOP_SITE_VARIABLE + "\"",
|
||||
" site mapred-site.xml \"$" + MAPRED_SITE_VARIABLE + "\"",
|
||||
" if [ -n \"${" + HDFS_SITE_VARIABLE + ":-}\" ]; then",
|
||||
" site hdfs-site.xml \"$" + HDFS_SITE_VARIABLE + "\"",
|
||||
" fi",
|
||||
" if [ ! -s \"$hadoop_conf/log4j.properties\" ]; then",
|
||||
" printf '%s\\n' '" + String.join("' '", HADOOP_CONSOLE_LOG) + "' > \"$hadoop_conf/log4j.properties\"",
|
||||
" fi",
|
||||
@@ -415,6 +421,10 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
if (job.storage() != null && job.engine() == Engine.SPARK) {
|
||||
container.withEnv(HADOOP_SITE_VARIABLE, hadoopSite(job, endpoint))
|
||||
.withEnv(MAPRED_SITE_VARIABLE, mapredSite(job));
|
||||
if (job.storage() != null && job.storage().replication() > 0) {
|
||||
container.withEnv(HDFS_SITE_VARIABLE, siteProperty("dfs.replication",
|
||||
String.valueOf(job.storage().replication())));
|
||||
}
|
||||
if (!job.hadoopLog4j().isEmpty()) {
|
||||
container.withEnv(HADOOP_LOG4J_VARIABLE, hadoopLog4jFile(job));
|
||||
}
|
||||
@@ -516,7 +526,8 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
for (Container container : containers) {
|
||||
Map<String, String> labels = container.getLabels() != null ? container.getLabels() : Map.of();
|
||||
// A live EMR cluster's HDFS, which its storage keeps, carries the service's labels too.
|
||||
if (Storage.HDFS_COMPONENT.equals(labels.get(ContainerStorageHelper.COMPONENT_LABEL))) {
|
||||
String component = labels.get(ContainerStorageHelper.COMPONENT_LABEL);
|
||||
if (Storage.HDFS_COMPONENT.equals(component) || Storage.NODE_COMPONENT.equals(component)) {
|
||||
continue;
|
||||
}
|
||||
if (aliases.consistent(container.getId(), labels)
|
||||
@@ -984,10 +995,18 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
}
|
||||
|
||||
// A cluster's HDFS, as Hadoop settings: its NameNode, on the cluster's primary node, which hdfs:// paths without a
|
||||
// host, and paths without a scheme, lead to; none before it runs.
|
||||
// host, and paths without a scheme, lead to, and, as it is a client that says how many copies of a block it writes
|
||||
// and the image's hdfs-site.xml says two, the copies its core nodes keep; none before it runs.
|
||||
private static List<SparkSetting> hdfsSettings(Storage storage) {
|
||||
return storage == null || storage.hdfsHost() == null ? List.of()
|
||||
: List.of(new SparkSetting("fs.defaultFS", "hdfs://" + storage.hdfsHost() + ":" + HDFS_PORT));
|
||||
if (storage == null || storage.hdfsHost() == null) {
|
||||
return List.of();
|
||||
}
|
||||
List<SparkSetting> settings = new ArrayList<>();
|
||||
settings.add(new SparkSetting("fs.defaultFS", "hdfs://" + storage.hdfsHost() + ":" + HDFS_PORT));
|
||||
if (storage.replication() > 0) {
|
||||
settings.add(new SparkSetting("dfs.replication", String.valueOf(storage.replication())));
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
|
||||
// The cluster's HDFS for a MapReduce job in local mode, which reads the core-site.xml of the hadoop command's
|
||||
|
||||
@@ -112,10 +112,11 @@ public interface SparkJobRunner {
|
||||
* node, named {@code hdfsHost}, which a step's container reaches at {@code hdfsAddress} on the Docker network
|
||||
* {@code hdfsNetwork}, the cluster's own, which the container joins (all three null until it runs, the network
|
||||
* also on the host's own network, which steps share with it); and, on a cluster with Hive or HCatalog, the URI of
|
||||
* the Hive metastore service on that node, or null.
|
||||
* the Hive metastore service on that node, or null; and how many copies of a block its HDFS keeps, when its core
|
||||
* nodes hold it, else 0.
|
||||
*/
|
||||
record Storage(String home, String mnt, String hdfsHost, String hdfsAddress, String hdfsNetwork,
|
||||
String hiveMetastore, String resourceManager, String flociEndpoint) {
|
||||
String hiveMetastore, String resourceManager, String flociEndpoint, int replication) {
|
||||
|
||||
/**
|
||||
* The component label of an EMR cluster's HDFS container, which carries its service's labels as a driver
|
||||
@@ -123,19 +124,24 @@ public interface SparkJobRunner {
|
||||
*/
|
||||
public static final String HDFS_COMPONENT = "emr-hdfs";
|
||||
|
||||
/** The component label of an EMR cluster's core or task node's container, its storage's as the HDFS is. */
|
||||
public static final String NODE_COMPONENT = "emr-node";
|
||||
|
||||
/** A cluster's volumes, before its HDFS runs. */
|
||||
public Storage(String home, String mnt) {
|
||||
this(home, mnt, null, null, null, null, null, null);
|
||||
this(home, mnt, null, null, null, null, null, null, 0);
|
||||
}
|
||||
|
||||
/** This storage, its HDFS's NameNode on {@code host}, at {@code address} on {@code network}. */
|
||||
public Storage withHdfs(String host, String address, String network) {
|
||||
return new Storage(home, mnt, host, address, network, hiveMetastore, resourceManager, flociEndpoint);
|
||||
return new Storage(home, mnt, host, address, network, hiveMetastore, resourceManager, flociEndpoint,
|
||||
replication);
|
||||
}
|
||||
|
||||
/** This storage, its Hive metastore service at {@code uri}. */
|
||||
public Storage withHiveMetastore(String uri) {
|
||||
return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, uri, resourceManager, flociEndpoint);
|
||||
return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, uri, resourceManager, flociEndpoint,
|
||||
replication);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -143,7 +149,14 @@ public interface SparkJobRunner {
|
||||
* Floci's address on the HDFS's network.
|
||||
*/
|
||||
public Storage withYarn(String host, String flociEndpoint) {
|
||||
return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, hiveMetastore, host, flociEndpoint);
|
||||
return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, hiveMetastore, host, flociEndpoint,
|
||||
replication);
|
||||
}
|
||||
|
||||
/** This storage, its HDFS keeping {@code copies} copies of a block on its core nodes. */
|
||||
public Storage withReplication(int copies) {
|
||||
return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, hiveMetastore, resourceManager,
|
||||
flociEndpoint, copies);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -634,6 +634,7 @@ floci:
|
||||
# hive-image-template: "registry.internal/emr-serverless/hive/%s:20250425" # every cluster's HDFS, and Hive
|
||||
yarn-node-memory-mb: 4096 # memory a cluster's NodeManager offers its YARN containers
|
||||
yarn-node-vcores: 4 # virtual cores it offers them
|
||||
yarn-max-worker-nodes: 4 # the most core and task nodes a cluster runs as containers of their own
|
||||
# Remove the step drivers a previous run of this deployment left on the daemon, and the images
|
||||
# bootstrap actions left for clusters that are gone or have ended, when the EMR service starts.
|
||||
# Scoped to this deployment's own containers and images.
|
||||
|
||||
+23
@@ -121,6 +121,29 @@ class ContainerLifecycleManagerCpuLimitTest {
|
||||
assertEquals(16_000_000_000L, hostConfig.getNanoCPUs());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDnsNameIsTheContainersHostNameAndItsAliasOnItsNetwork() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.docker().resourceNamespace()).thenReturn(Optional.empty());
|
||||
ContainerSpec spec = new ContainerBuilder(config, mock(DockerHostResolver.class), mock(EmbeddedDnsServer.class))
|
||||
.newContainer("app:latest").withDnsName("ip-10-1-0-1.ec2.internal").build();
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
stubDaemonCpuCount(dockerClient, EIGHT_CPU_HOST);
|
||||
CreateContainerCmd createCmd = mock(CreateContainerCmd.class, RETURNS_SELF);
|
||||
when(dockerClient.createContainerCmd("app:latest")).thenReturn(createCmd);
|
||||
CreateContainerResponse response = mock(CreateContainerResponse.class);
|
||||
when(response.getId()).thenReturn("app-id");
|
||||
when(createCmd.exec()).thenReturn(response);
|
||||
ImageCacheService imageCacheService = mock(ImageCacheService.class);
|
||||
when(imageCacheService.ensureImageExists(any())).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
|
||||
new ContainerLifecycleManager(dockerClient, imageCacheService, mock(ContainerDetector.class), config)
|
||||
.create(spec);
|
||||
|
||||
verify(createCmd).withHostName("ip-10-1-0-1.ec2.internal");
|
||||
verify(createCmd).withAliases("ip-10-1-0-1.ec2.internal");
|
||||
}
|
||||
|
||||
private static HostConfig createHostConfig(Integer hostCpus,
|
||||
UnaryOperator<ContainerBuilder.Builder> customizer) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
|
||||
@@ -71,6 +71,7 @@ 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.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
@@ -78,6 +79,7 @@ import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.RETURNS_SELF;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
@@ -94,6 +96,14 @@ class EmrClusterStorageTest {
|
||||
private static final String HOST = "ip-10-0-0-1.ec2.internal";
|
||||
private static final String READY = "test -f /tmp/floci-hdfs-ready";
|
||||
private static final BooleanSupplier NOT_STOPPED = () -> false;
|
||||
private static final String CORE_HOST = "ip-10-1-0-1.ec2.internal";
|
||||
private static final String TASK_HOST = "ip-10-2-0-1.ec2.internal";
|
||||
private static final ClusterStorage.Node CORE_NODE = new ClusterStorage.Node("1-1", CORE_HOST, true);
|
||||
private static final ClusterStorage.Node TASK_NODE = new ClusterStorage.Node("2-1", TASK_HOST, false);
|
||||
private static final ClusterStorage.Yarn TWO_NODES = new ClusterStorage.Yarn(4096, 4)
|
||||
.onNodes(List.of(CORE_NODE, TASK_NODE), 1, "s3://logs/j-1/containers/");
|
||||
private static final ClusterStorage.Yarn CORE_ONLY = new ClusterStorage.Yarn(4096, 4)
|
||||
.onNodes(List.of(CORE_NODE), 1, "s3://logs/j-1/containers/");
|
||||
// A cluster with Hive, whose EC2 instance profile's role is r, with no core-site or hive-site.
|
||||
private static final ClusterStorage.HiveMetastore METASTORE =
|
||||
new ClusterStorage.HiveMetastore("arn:aws:iam::123456789012:role/r", Map.of());
|
||||
@@ -108,8 +118,10 @@ class EmrClusterStorageTest {
|
||||
private final CurrentContainerNetworkResolver currentContainer = mock(CurrentContainerNetworkResolver.class);
|
||||
private final S3Service s3 = mock(S3Service.class);
|
||||
private final EmrClusterStorage storage = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv,
|
||||
roleCredentials, currentContainer, config, s3);
|
||||
roleCredentials, currentContainer, config, s3, Duration.ofSeconds(120), System::nanoTime);
|
||||
private final String hdfsName = ContainerStorageHelper.dockerName(config, "emr-j-1-hdfs");
|
||||
private final String coreName = ContainerStorageHelper.dockerName(config, "emr-j-1-node-1-1");
|
||||
private final String taskName = ContainerStorageHelper.dockerName(config, "emr-j-1-node-2-1");
|
||||
|
||||
@BeforeEach
|
||||
void docker() {
|
||||
@@ -125,6 +137,661 @@ class EmrClusterStorageTest {
|
||||
ListContainersCmd running = mock(ListContainersCmd.class, RETURNS_SELF);
|
||||
when(docker.listContainersCmd()).thenReturn(running);
|
||||
when(running.exec()).thenReturn(List.of());
|
||||
// No node's volume is there without its container, and Docker removes the volumes it is asked to.
|
||||
nodeVolumes();
|
||||
when(lifecycle.removeVolume(anyString())).thenReturn(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterWithCoreAndTaskNodesRunsEachInAContainerOfItsOwn() {
|
||||
nodesStart(coreName, taskName);
|
||||
|
||||
SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network",
|
||||
null, () -> TWO_NODES, NOT_STOPPED);
|
||||
|
||||
assertEquals(1, started.replication());
|
||||
verify(spec).withName(coreName);
|
||||
verify(spec).withName(taskName);
|
||||
verify(lifecycle).ensureVolume(eq(coreName), any());
|
||||
verify(spec).withNamedVolume(coreName, "/mnt");
|
||||
verify(spec).withNamedVolume(taskName, "/mnt");
|
||||
// Each under the name ListInstances gives it, on the cluster's network.
|
||||
verify(spec).withDnsName(CORE_HOST);
|
||||
verify(spec).withDnsName(TASK_HOST);
|
||||
verify(spec).withDnsName(HOST);
|
||||
verify(spec).withEnv("FLOCI_NODE_HOST", CORE_HOST);
|
||||
verify(spec).withEnv("FLOCI_NODE_HOST", TASK_HOST);
|
||||
// Only a core node holds a DataNode, and with one the primary node holds neither.
|
||||
verify(spec).withEnv("FLOCI_NODE_CORE", "1");
|
||||
verify(spec).withEnv("FLOCI_NODE_WORKERS", "1");
|
||||
// What the primary node has of YARN too, and Floci in reach.
|
||||
verify(spec, times(3)).withEnv("FLOCI_YARN_MEMORY_MB", "4096");
|
||||
verify(spec, times(3)).withEnv("FLOCI_YARN_VCORES", "4");
|
||||
verify(spec, times(3)).withHostDockerInternalOnLinux();
|
||||
verify(spec, times(3)).withJavaTrustStore();
|
||||
verify(spec, times(2)).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(
|
||||
"n=1; if [ -n \"$FLOCI_NODE_CORE\" ]; then hdfs datanode & n=2; fi;")));
|
||||
// It is ready once the ResourceManager knows it, not when it starts.
|
||||
verify(spec, times(2)).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(
|
||||
"until curl -sf -m 5 \"http://$FLOCI_HDFS_HOST:8088/ws/v1/cluster/nodes?states=RUNNING\""
|
||||
+ " | grep -q \"\\\"nodeHostName\\\":\\\"$FLOCI_NODE_HOST\\\"\"")));
|
||||
verify(spec, times(2)).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(
|
||||
"grep -q \"$FLOCI_NODE_HOST:9866\"")));
|
||||
verify(spec, times(3)).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(
|
||||
"<name>dfs.hosts.exclude</name><value>/tmp/floci-hdfs-conf/dfs.exclude</value>")));
|
||||
// A node that stops is dead to the NameNode after 40s, which a core node that has gone waits for.
|
||||
verify(spec, times(3)).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(
|
||||
"<name>dfs.namenode.heartbeat.recheck-interval</name><value>5000</value>")));
|
||||
verify(spec, times(3)).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(
|
||||
"<name>yarn.resourcemanager.nodes.exclude-path</name><value>/tmp/floci-hdfs-conf/yarn.exclude</value>")));
|
||||
// The primary node runs its own DataNode and NodeManager only without core nodes, but a DataNode on a volume
|
||||
// holding one's data, so the blocks on it stay in reach.
|
||||
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(
|
||||
"hdfs namenode & n=1; if [ -z \"$FLOCI_NODE_WORKERS\" ] || [ -d /mnt/datanode/current ]; then "
|
||||
+ "hdfs datanode & n=2; fi;")));
|
||||
// The primary node's readiness needs a DataNode of theirs, so they start before it is awaited.
|
||||
InOrder order = inOrder(lifecycle, docker);
|
||||
order.verify(lifecycle, times(3)).createAndStart(any());
|
||||
order.verify(docker).execCreateCmd("c-1");
|
||||
order.verify(docker).execCreateCmd(coreName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCoreNodesDataNodeRegistersUnderItsNameAndACopyCountComesFromTheCluster() {
|
||||
nodesStart(coreName, taskName);
|
||||
|
||||
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null,
|
||||
() -> new ClusterStorage.Yarn(4096, 4).onNodes(List.of(CORE_NODE, TASK_NODE), 2, null), NOT_STOPPED);
|
||||
|
||||
verify(spec, times(3)).withEnv("FLOCI_HDFS_REPLICATION", "2");
|
||||
verify(spec, times(3)).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(
|
||||
"<name>dfs.replication</name><value>${FLOCI_HDFS_REPLICATION:-1}</value>")
|
||||
&& entrypoint.get(2).contains("datanode_name=; [ -z \"$FLOCI_NODE_HOST\" ] || datanode_name=\"<property>"
|
||||
+ "<name>dfs.datanode.hostname</name><value>$FLOCI_NODE_HOST</value></property>\"")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyNodeRunsItsDaemonsFromTheHadoopItsImageKeepsApart() {
|
||||
nodesStart(coreName, taskName);
|
||||
|
||||
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null,
|
||||
() -> TWO_NODES.withHadoopFolder("/opt"), NOT_STOPPED);
|
||||
|
||||
verify(spec, times(3)).withEnv("FLOCI_HADOOP_FOLDER", "/opt");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNodeRunningInTheImageIsLeftRunning() {
|
||||
nodesStart(coreName, taskName);
|
||||
runningNodes(node(coreName, "running", IMAGE, CORE_HOST, true), node(taskName, "running", IMAGE, TASK_HOST, false));
|
||||
|
||||
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES,
|
||||
NOT_STOPPED);
|
||||
|
||||
verify(spec, never()).withName(coreName);
|
||||
verify(spec, never()).withName(taskName);
|
||||
verify(lifecycle, never()).removeIfExistsStrict(coreName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNodeInAnotherImageOrStoppedStartsAgainOnItsData() {
|
||||
nodesStart(coreName, taskName);
|
||||
runningNodes(node(coreName, "running", "sha256:older", CORE_HOST, true),
|
||||
node(taskName, "exited", IMAGE, TASK_HOST, false));
|
||||
|
||||
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES,
|
||||
NOT_STOPPED);
|
||||
|
||||
verify(lifecycle).removeIfExistsStrict(coreName);
|
||||
verify(spec).withName(coreName);
|
||||
verify(spec).withName(taskName);
|
||||
verify(lifecycle, never()).removeVolume(coreName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNodeThatStopsBeforeItIsReadyStartsAgainOnceThenFailsTheStep() {
|
||||
nodesStart(coreName);
|
||||
when(lifecycle.probeContainer(coreName)).thenReturn(ContainerLiveness.NOT_RUNNING);
|
||||
|
||||
IllegalStateException failed = assertThrows(IllegalStateException.class,
|
||||
() -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null,
|
||||
() -> CORE_ONLY, NOT_STOPPED));
|
||||
|
||||
assertEquals("A node of EMR cluster j-1 stopped before it was ready", failed.getMessage());
|
||||
verify(spec, times(2)).withName(coreName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterWithOnlyTaskNodesKeepsItsDataNodeAndNodeManagerOnThePrimaryNode() {
|
||||
nodesStart(taskName);
|
||||
|
||||
SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network",
|
||||
null, () -> new ClusterStorage.Yarn(4096, 4).onNodes(List.of(TASK_NODE), 1, null), NOT_STOPPED);
|
||||
|
||||
verify(spec, never()).withEnv(eq("FLOCI_NODE_WORKERS"), any());
|
||||
verify(spec, never()).withEnv(eq("FLOCI_NODE_CORE"), any());
|
||||
assertEquals(0, started.replication());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPrimaryNodeThatWorksKeepsItsDataNodeAndNodeManagerBesideItsCoreNodes() {
|
||||
nodesStart(coreName, taskName);
|
||||
|
||||
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null,
|
||||
() -> TWO_NODES.withPrimaryWorking(true), NOT_STOPPED);
|
||||
|
||||
verify(spec).withEnv("FLOCI_NODE_CORE", "1");
|
||||
verify(spec, never()).withEnv(eq("FLOCI_NODE_WORKERS"), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aResizeBeforeAStepHasStartedTheNodesStartsNone() {
|
||||
storage.resize("j-1", () -> TWO_NODES);
|
||||
|
||||
verify(lifecycle, never()).createAndStart(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNewNodeStartsOnAResizeFromWhatItsClusterSaysThen() {
|
||||
nodesStart(coreName, taskName);
|
||||
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> CORE_ONLY,
|
||||
NOT_STOPPED);
|
||||
runningNodes(node(coreName, "running", IMAGE, CORE_HOST, true));
|
||||
|
||||
storage.resize("j-1", () -> TWO_NODES);
|
||||
|
||||
verify(spec).withName(taskName);
|
||||
verify(spec, times(1)).withName(coreName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedResizeIsLoggedAndLeavesTheClusterAsItIs() {
|
||||
nodesStart(coreName);
|
||||
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> CORE_ONLY,
|
||||
NOT_STOPPED);
|
||||
when(docker.listContainersCmd()).thenThrow(new IllegalStateException("Docker went away"));
|
||||
|
||||
assertDoesNotThrow(() -> storage.resize("j-1", () -> TWO_NODES));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTaskNodeNoLongerWantedIsDecommissionedAndGoesWithItsData() throws IOException {
|
||||
nodesStart(coreName, taskName);
|
||||
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES,
|
||||
NOT_STOPPED);
|
||||
runningNodes(node(coreName, "running", IMAGE, CORE_HOST, true), node(taskName, "running", IMAGE, TASK_HOST, false));
|
||||
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
|
||||
String taskLog = "application_1_0001/container_1_0001_01_000002/stdout";
|
||||
nodeLogs(taskName, Map.of(taskLog, "from task"));
|
||||
clearInvocations(lifecycle);
|
||||
|
||||
storage.resize("j-1", () -> CORE_ONLY);
|
||||
|
||||
// Told first: YARN lets a task node go alone, as it holds no HDFS.
|
||||
String told = commands.get(0).get(2);
|
||||
assertTrue(told.contains("printf '" + TASK_HOST + "\\n' > /tmp/floci-hdfs-conf/yarn.exclude.new"), told);
|
||||
assertTrue(told.contains("printf '' > /tmp/floci-hdfs-conf/dfs.exclude.new"), told);
|
||||
assertTrue(told.contains("yarn rmadmin -refreshNodes -g 3600 -server"), told);
|
||||
assertTrue(told.contains("hdfs dfsadmin -refreshNodes"), told);
|
||||
// A refresh that fails takes its list away, so the next round's differs and is read again.
|
||||
assertTrue(told.contains("-server || { rm -f /tmp/floci-hdfs-conf/yarn.exclude; exit 1; }"), told);
|
||||
assertTrue(told.contains("hdfs dfsadmin -refreshNodes || { rm -f /tmp/floci-hdfs-conf/dfs.exclude; exit 1; }"),
|
||||
told);
|
||||
String asked = commands.get(2).get(2);
|
||||
assertTrue(asked.contains("cluster/nodes?states=DECOMMISSIONED' | grep -q '\"nodeHostName\":\"" + TASK_HOST), asked);
|
||||
assertFalse(asked.contains("Decommissioned"), asked);
|
||||
verify(docker).copyArchiveFromContainerCmd(taskName, "/mnt/yarn/logs/" + taskLog);
|
||||
verify(lifecycle).removeIfExistsStrict(taskName);
|
||||
verify(lifecycle).removeVolume(taskName);
|
||||
verify(lifecycle, never()).removeIfExistsStrict(coreName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCoreNodeGoesOnlyOnceHdfsHasMovedItsBlocksAndYarnHasLetItGo() {
|
||||
// Ten seconds on each reading, so the thread sees the NameNode's dead-node interval pass.
|
||||
AtomicLong clock = new AtomicLong();
|
||||
EmrClusterStorage ticking = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv, roleCredentials,
|
||||
currentContainer, config, s3, Duration.ofSeconds(120),
|
||||
() -> clock.getAndAdd(Duration.ofSeconds(10).toNanos()), Runnable::run, Duration.ZERO);
|
||||
nodesStart(coreName, taskName);
|
||||
ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES,
|
||||
NOT_STOPPED);
|
||||
runningNodes(node(coreName, "running", IMAGE, CORE_HOST, true), node(taskName, "running", IMAGE, TASK_HOST, false));
|
||||
// HDFS told; told again and asked, not yet done; told again and asked, done; YARN told and asked, done; told
|
||||
// while the NameNode has the node live, then not.
|
||||
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, hdfsName,
|
||||
List.of(0L, 0L, 1L, 0L, 0L, 0L, 0L), "", "");
|
||||
clearInvocations(lifecycle);
|
||||
|
||||
ticking.resize("j-1", () -> new ClusterStorage.Yarn(4096, 4).onNodes(List.of(TASK_NODE), 1, null));
|
||||
|
||||
String excluded = "printf '" + CORE_HOST + "\\n' > /tmp/floci-hdfs-conf/dfs.exclude.new";
|
||||
String told = commands.get(0).get(2);
|
||||
assertTrue(told.contains(excluded), told);
|
||||
assertTrue(told.contains("printf '' > /tmp/floci-hdfs-conf/yarn.exclude.new"), told);
|
||||
String hdfsAsked = commands.get(2).get(2);
|
||||
assertTrue(hdfsAsked.contains("grep -Eq '" + CORE_HOST + ":9866[^}]*Decommissioned'"), hdfsAsked);
|
||||
String yarnTold = commands.get(5).get(2);
|
||||
assertTrue(yarnTold.contains("printf '" + CORE_HOST + "\\n' > /tmp/floci-hdfs-conf/yarn.exclude.new"),
|
||||
yarnTold);
|
||||
String yarnAsked = commands.get(6).get(2);
|
||||
assertTrue(yarnAsked.contains("DECOMMISSIONED' | grep -q '\"nodeHostName\":\"" + CORE_HOST), yarnAsked);
|
||||
assertEquals(2, commands.stream().filter(command -> command.get(2).contains("Decommissioned'")).count());
|
||||
assertEquals(1, commands.stream().filter(command -> command.get(2).contains("DECOMMISSIONED'")).count());
|
||||
String gone = commands.get(7).get(2);
|
||||
assertTrue(gone.contains(excluded), gone);
|
||||
String dead = commands.get(commands.size() - 1).get(2);
|
||||
assertTrue(dead.contains("printf '' > /tmp/floci-hdfs-conf/dfs.exclude.new"), dead);
|
||||
verify(lifecycle).removeIfExistsStrict(coreName);
|
||||
verify(lifecycle).removeVolume(coreName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNodeThatStoppedWhileItLeftGoesWithoutWaiting() {
|
||||
nodesStart(coreName, taskName);
|
||||
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES,
|
||||
NOT_STOPPED);
|
||||
runningNodes(node(coreName, "running", IMAGE, CORE_HOST, true), node(taskName, "running", IMAGE, TASK_HOST, false));
|
||||
ContainerExecStubs.completeEveryExec(docker, hdfsName, 1L, "", "");
|
||||
when(lifecycle.probeContainer(taskName)).thenReturn(ContainerLiveness.NOT_RUNNING);
|
||||
clearInvocations(lifecycle);
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(20), () -> storage.resize("j-1", () -> CORE_ONLY));
|
||||
|
||||
verify(lifecycle).removeIfExistsStrict(taskName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNodeNotDecommissionedInTimeGoesAnyway() {
|
||||
AtomicLong clock = new AtomicLong();
|
||||
EmrClusterStorage ticking = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv, roleCredentials,
|
||||
currentContainer, config, s3, Duration.ofSeconds(120),
|
||||
() -> clock.getAndAdd(Duration.ofHours(2).toNanos()), Runnable::run, Duration.ZERO);
|
||||
nodesStart(coreName, taskName);
|
||||
ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES,
|
||||
NOT_STOPPED);
|
||||
runningNodes(node(coreName, "running", IMAGE, CORE_HOST, true), node(taskName, "running", IMAGE, TASK_HOST, false));
|
||||
ContainerExecStubs.completeEveryExec(docker, hdfsName, 1L, "", "");
|
||||
clearInvocations(lifecycle);
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(20), () -> ticking.resize("j-1", () -> CORE_ONLY));
|
||||
|
||||
verify(lifecycle).removeIfExistsStrict(taskName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNodeALaterResizeLetsGoHasTheWholeTimeToo() {
|
||||
// A minute on each reading, so the rounds go by.
|
||||
AtomicLong clock = new AtomicLong();
|
||||
EmrClusterStorage ticking = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv, roleCredentials,
|
||||
currentContainer, config, s3, Duration.ofSeconds(120),
|
||||
() -> clock.getAndAdd(Duration.ofMinutes(1).toNanos()), Runnable::run, Duration.ZERO);
|
||||
nodesStart(coreName, taskName);
|
||||
ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES,
|
||||
NOT_STOPPED);
|
||||
runningNodes(node(coreName, "running", IMAGE, CORE_HOST, true), node(taskName, "running", IMAGE, TASK_HOST, false));
|
||||
// Neither HDFS nor YARN lets a node go, so each goes when its time is up.
|
||||
ContainerExecStubs.completeEveryExec(docker, hdfsName, 1L, "", "");
|
||||
AtomicLong coreLetGo = new AtomicLong();
|
||||
AtomicBoolean shrunk = new AtomicBoolean();
|
||||
when(lifecycle.probeContainer(taskName)).thenAnswer(asked -> {
|
||||
// Fifty-nine minutes into the task node's decommissioning, a resize lets the core node go too.
|
||||
if (shrunk.compareAndSet(false, true)) {
|
||||
clock.addAndGet(Duration.ofMinutes(59).toNanos());
|
||||
coreLetGo.set(clock.get());
|
||||
ticking.resize("j-1", () -> new ClusterStorage.Yarn(4096, 4).onNodes(List.of(), 1, null));
|
||||
}
|
||||
return ContainerLiveness.RUNNING;
|
||||
});
|
||||
AtomicLong coreGone = new AtomicLong();
|
||||
doAnswer(removing -> {
|
||||
coreGone.set(clock.get());
|
||||
return null;
|
||||
}).when(lifecycle).removeIfExistsStrict(coreName);
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(20), () -> ticking.resize("j-1", () -> CORE_ONLY));
|
||||
|
||||
assertTrue(coreGone.get() - coreLetGo.get() >= Duration.ofHours(1).toNanos(),
|
||||
"gone " + Duration.ofNanos(coreGone.get() - coreLetGo.get()) + " after it was let go");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNodeDockerCannotTellTheStateOfIsAskedAgainRatherThanTakenAsGone() {
|
||||
AtomicLong clock = new AtomicLong();
|
||||
EmrClusterStorage ticking = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv, roleCredentials,
|
||||
currentContainer, config, s3, Duration.ofSeconds(120),
|
||||
() -> clock.getAndAdd(Duration.ofMinutes(30).toNanos()), Runnable::run, Duration.ZERO);
|
||||
nodesStart(coreName, taskName);
|
||||
ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES,
|
||||
NOT_STOPPED);
|
||||
runningNodes(node(coreName, "running", IMAGE, CORE_HOST, true), node(taskName, "running", IMAGE, TASK_HOST, false));
|
||||
ContainerExecStubs.completeEveryExec(docker, hdfsName, 1L, "", "");
|
||||
when(lifecycle.probeContainer(taskName)).thenReturn(ContainerLiveness.UNKNOWN);
|
||||
AtomicLong taskGone = new AtomicLong();
|
||||
doAnswer(removing -> {
|
||||
taskGone.set(clock.get());
|
||||
return null;
|
||||
}).when(lifecycle).removeIfExistsStrict(taskName);
|
||||
long letGo = clock.get();
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(20), () -> ticking.resize("j-1", () -> CORE_ONLY));
|
||||
|
||||
// Not on the first round, as a stopped node would: only once its time was up.
|
||||
assertTrue(taskGone.get() - letGo > Duration.ofHours(1).toNanos(),
|
||||
"gone " + Duration.ofNanos(taskGone.get() - letGo) + " after it was let go");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCoreNodeThatStopsBeforeHdfsMovedItsBlocksStartsAgainOnItsData() {
|
||||
AtomicLong clock = new AtomicLong();
|
||||
EmrClusterStorage ticking = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv, roleCredentials,
|
||||
currentContainer, config, s3, Duration.ofSeconds(120),
|
||||
() -> clock.getAndAdd(Duration.ofMinutes(30).toNanos()), Runnable::run, Duration.ZERO);
|
||||
nodesStart(coreName, taskName);
|
||||
ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES,
|
||||
NOT_STOPPED);
|
||||
runningNodes(node(coreName, "running", IMAGE, CORE_HOST, true), node(taskName, "running", IMAGE, TASK_HOST, false));
|
||||
ContainerExecStubs.completeEveryExec(docker, hdfsName, 1L, "", "");
|
||||
// It stops before HDFS has moved its blocks, and runs once started again.
|
||||
when(lifecycle.probeContainer(coreName)).thenReturn(ContainerLiveness.NOT_RUNNING, ContainerLiveness.RUNNING);
|
||||
clearInvocations(spec, lifecycle);
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(20),
|
||||
() -> ticking.resize("j-1", () -> new ClusterStorage.Yarn(4096, 4).onNodes(List.of(TASK_NODE), 1, null)));
|
||||
|
||||
verify(spec).withName(coreName);
|
||||
verify(spec).withNamedVolume(coreName, "/mnt");
|
||||
// Its data goes only after that, here once its time was up.
|
||||
InOrder order = inOrder(lifecycle);
|
||||
order.verify(lifecycle).createAndStart(any());
|
||||
order.verify(lifecycle).removeVolume(coreName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRoundThatFailsIsTriedAgainOnTheNext() {
|
||||
nodesStart(coreName, taskName);
|
||||
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES,
|
||||
NOT_STOPPED);
|
||||
runningNodes(node(coreName, "running", IMAGE, CORE_HOST, true), node(taskName, "running", IMAGE, TASK_HOST, false));
|
||||
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
|
||||
when(lifecycle.probeContainer(taskName)).thenThrow(new IllegalStateException("Docker went away"))
|
||||
.thenReturn(ContainerLiveness.NOT_RUNNING);
|
||||
clearInvocations(lifecycle);
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(20), () -> storage.resize("j-1", () -> CORE_ONLY));
|
||||
|
||||
verify(lifecycle).removeIfExistsStrict(taskName);
|
||||
verify(lifecycle).removeVolume(taskName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNodeWhoseDataDockerKeepsStaysToBeRemovedOnTheNextRound() {
|
||||
nodesStart(coreName, taskName);
|
||||
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES,
|
||||
NOT_STOPPED);
|
||||
runningNodes(node(coreName, "running", IMAGE, CORE_HOST, true), node(taskName, "running", IMAGE, TASK_HOST, false));
|
||||
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
|
||||
when(lifecycle.probeContainer(taskName)).thenReturn(ContainerLiveness.NOT_RUNNING);
|
||||
when(lifecycle.removeVolume(taskName)).thenReturn(false, true);
|
||||
clearInvocations(lifecycle);
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(20), () -> storage.resize("j-1", () -> CORE_ONLY));
|
||||
|
||||
verify(lifecycle, times(2)).removeVolume(taskName);
|
||||
// Its logs are read once, while its container is there.
|
||||
verify(docker, times(1)).copyArchiveFromContainerCmd(taskName, "/mnt/yarn/logs");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCoreNodeAShutdownCutOffWhileItLeftStartsAgainOnItsDataToBeDecommissioned() {
|
||||
List<Runnable> queued = new ArrayList<>();
|
||||
EmrClusterStorage queuing = queuingDecommissions(queued);
|
||||
nodesStart(coreName, taskName);
|
||||
// Its container went with the shutdown, and only its volume says it was a core node.
|
||||
nodeVolumes(nodeVolume(coreName, CORE_HOST, true));
|
||||
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
|
||||
|
||||
queuing.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null,
|
||||
() -> new ClusterStorage.Yarn(4096, 4).onNodes(List.of(TASK_NODE), 1, null), NOT_STOPPED);
|
||||
|
||||
verify(spec).withName(coreName);
|
||||
verify(spec).withNamedVolume(coreName, "/mnt");
|
||||
verify(lifecycle, never()).removeVolume(coreName);
|
||||
String told = commands.get(0).get(2);
|
||||
assertTrue(told.contains("printf '" + CORE_HOST + "\\n' > /tmp/floci-hdfs-conf/dfs.exclude.new"), told);
|
||||
assertEquals(1, queued.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTaskNodesDataAShutdownLeftGoesAsItHoldsNoBlocks() {
|
||||
nodesStart(coreName);
|
||||
nodeVolumes(nodeVolume(taskName, TASK_HOST, false));
|
||||
|
||||
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> CORE_ONLY,
|
||||
NOT_STOPPED);
|
||||
|
||||
verify(lifecycle).removeVolume(taskName);
|
||||
verify(spec, never()).withName(taskName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNodeWhoseStartATeardownPassedGoes() {
|
||||
nodesStart(coreName);
|
||||
AtomicLong starts = new AtomicLong();
|
||||
when(lifecycle.createAndStart(any())).thenAnswer(starting -> {
|
||||
// The second is the core node's, and a shutdown sweeps while Docker creates it.
|
||||
if (starts.incrementAndGet() == 2) {
|
||||
storage.stopManagedContainers();
|
||||
}
|
||||
return new ContainerLifecycleManager.ContainerInfo("c-1", Map.of());
|
||||
});
|
||||
|
||||
assertThrows(ClusterStorage.Stopped.class, () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
|
||||
"floci-network", null, () -> CORE_ONLY, NOT_STOPPED));
|
||||
|
||||
// Before it was created, by the sweep, and once it was.
|
||||
verify(lifecycle, times(3)).removeIfExistsStrict(coreName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNodeWantedAgainWhileItLeavesCarriesOn() {
|
||||
List<Runnable> queued = new ArrayList<>();
|
||||
EmrClusterStorage queuing = queuingDecommissions(queued);
|
||||
nodesStart(coreName, taskName);
|
||||
queuing.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES,
|
||||
NOT_STOPPED);
|
||||
runningNodes(node(coreName, "running", IMAGE, CORE_HOST, true), node(taskName, "running", IMAGE, TASK_HOST, false));
|
||||
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
|
||||
queuing.resize("j-1", () -> CORE_ONLY);
|
||||
assertEquals(1, queued.size());
|
||||
clearInvocations(lifecycle);
|
||||
|
||||
queuing.resize("j-1", () -> TWO_NODES);
|
||||
queued.get(0).run();
|
||||
|
||||
assertTrue(commands.get(1).get(2).contains("printf '' > /tmp/floci-hdfs-conf/yarn.exclude.new"),
|
||||
commands.get(1).get(2));
|
||||
verify(lifecycle, never()).removeIfExistsStrict(taskName);
|
||||
verify(lifecycle, never()).removeVolume(taskName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void oneThreadDecommissionsACluster() {
|
||||
List<Runnable> queued = new ArrayList<>();
|
||||
EmrClusterStorage queuing = queuingDecommissions(queued);
|
||||
nodesStart(coreName, taskName);
|
||||
queuing.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES,
|
||||
NOT_STOPPED);
|
||||
runningNodes(node(coreName, "running", IMAGE, CORE_HOST, true), node(taskName, "running", IMAGE, TASK_HOST, false));
|
||||
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
|
||||
|
||||
queuing.resize("j-1", () -> CORE_ONLY);
|
||||
queuing.resize("j-1", () -> new ClusterStorage.Yarn(4096, 4).onNodes(List.of(), 1, null));
|
||||
|
||||
assertEquals(1, queued.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterThatEndsWhileANodeLeavesEndsItsDecommissioning() {
|
||||
List<Runnable> queued = new ArrayList<>();
|
||||
EmrClusterStorage queuing = queuingDecommissions(queued);
|
||||
nodesStart(coreName, taskName);
|
||||
queuing.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES,
|
||||
NOT_STOPPED);
|
||||
runningNodes(node(coreName, "running", IMAGE, CORE_HOST, true), node(taskName, "running", IMAGE, TASK_HOST, false));
|
||||
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
|
||||
queuing.resize("j-1", () -> CORE_ONLY);
|
||||
int told = commands.size();
|
||||
|
||||
queuing.remove("j-1");
|
||||
queued.get(0).run();
|
||||
|
||||
assertEquals(told, commands.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClustersEndRemovesItsNodesAndTheirDataBeforeItsNetwork() {
|
||||
when(lifecycle.removeNetwork(any())).thenReturn(true);
|
||||
when(lifecycle.removeVolume(any())).thenReturn(true);
|
||||
runningNodes(node(coreName, "running", IMAGE, CORE_HOST, true), node(taskName, "running", IMAGE, TASK_HOST, false));
|
||||
|
||||
assertTrue(storage.remove("j-1"));
|
||||
|
||||
InOrder order = inOrder(lifecycle);
|
||||
order.verify(lifecycle).removeIfExistsStrict(coreName);
|
||||
order.verify(lifecycle).removeVolume(coreName);
|
||||
order.verify(lifecycle).removeIfExistsStrict(taskName);
|
||||
order.verify(lifecycle).removeVolume(taskName);
|
||||
order.verify(lifecycle).removeIfExistsStrict(hdfsName);
|
||||
order.verify(lifecycle).removeNetwork(hdfsName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNodeDockerWillNotRemoveKeepsItsClustersEndGoing() {
|
||||
when(lifecycle.removeNetwork(any())).thenReturn(true);
|
||||
when(lifecycle.removeVolume(any())).thenReturn(true);
|
||||
runningNodes(node(coreName, "running", IMAGE, CORE_HOST, true));
|
||||
doThrow(new IllegalStateException("busy")).when(lifecycle).removeIfExistsStrict(coreName);
|
||||
|
||||
assertFalse(storage.remove("j-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClustersEndRemovesTheDataOfANodeAShutdownLeftWithoutItsContainer() {
|
||||
when(lifecycle.removeNetwork(any())).thenReturn(true);
|
||||
nodeVolumes(nodeVolume(coreName, CORE_HOST, true));
|
||||
|
||||
assertTrue(storage.remove("j-1"));
|
||||
|
||||
verify(lifecycle).removeVolume(coreName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClustersEndThatCannotFindItsNodesRemovesTheRestAndIsAskedForAgain() {
|
||||
when(lifecycle.removeNetwork(any())).thenReturn(true);
|
||||
when(docker.listContainersCmd()).thenThrow(new IllegalStateException("Docker went away"));
|
||||
|
||||
assertFalse(storage.remove("j-1"));
|
||||
|
||||
verify(lifecycle).removeIfExistsStrict(hdfsName);
|
||||
verify(lifecycle).removeNetwork(hdfsName);
|
||||
verify(lifecycle).removeVolume(hdfsName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aResetRemovesTheNodesAndLeavesTheirDataForTheNextStep() {
|
||||
nodesStart(coreName);
|
||||
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> CORE_ONLY,
|
||||
NOT_STOPPED);
|
||||
clearInvocations(lifecycle);
|
||||
|
||||
storage.stopManagedContainers();
|
||||
|
||||
verify(lifecycle).removeIfExistsStrict(coreName);
|
||||
verify(lifecycle, never()).removeVolume(coreName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theNodesOfAClusterThatHasEndedGoAtStartAndThoseOfOneUpStay() {
|
||||
Map<String, Container> byCluster = new LinkedHashMap<>();
|
||||
String otherName = ContainerStorageHelper.dockerName(config, "emr-j-2-node-1-1");
|
||||
Container gone = nodeOf("j-1", coreName);
|
||||
Container up = nodeOf("j-2", otherName);
|
||||
byCluster.put(coreName, gone);
|
||||
byCluster.put(otherName, up);
|
||||
AtomicReference<Map<String, String>> filter = new AtomicReference<>();
|
||||
ListContainersCmd list = mock(ListContainersCmd.class, RETURNS_SELF);
|
||||
when(docker.listContainersCmd()).thenReturn(list);
|
||||
when(list.withLabelFilter(any(Map.class))).thenAnswer(asked -> {
|
||||
filter.set(asked.getArgument(0));
|
||||
return list;
|
||||
});
|
||||
when(list.exec()).thenAnswer(reading -> "emr-node".equals(filter.get().get(ContainerStorageHelper.COMPONENT_LABEL))
|
||||
? List.copyOf(byCluster.values()) : List.of());
|
||||
ListNetworksCmd networks = mock(ListNetworksCmd.class, RETURNS_SELF);
|
||||
when(docker.listNetworksCmd()).thenReturn(networks);
|
||||
when(networks.exec()).thenReturn(List.of());
|
||||
ListVolumesCmd volumes = mock(ListVolumesCmd.class, RETURNS_SELF);
|
||||
when(docker.listVolumesCmd()).thenReturn(volumes);
|
||||
when(volumes.exec()).thenReturn(mock(ListVolumesResponse.class));
|
||||
|
||||
storage.removeAllBut(Set.of("j-2"));
|
||||
|
||||
verify(lifecycle).removeIfExistsStrict(coreName);
|
||||
verify(lifecycle, never()).removeIfExistsStrict(otherName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStoppedNodesLogsComeFromTheWholeFolderOnceAndNeverItsLaunchScript() throws IOException {
|
||||
runningNodes(node(taskName, "exited", IMAGE, TASK_HOST, false));
|
||||
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
|
||||
// A decommissioned node's NodeManager exits, which ends its container, and Docker refuses a command there.
|
||||
when(lifecycle.probeContainer(taskName)).thenReturn(ContainerLiveness.NOT_RUNNING);
|
||||
String container = "logs/application_1_0001/container_1_0001_01_000002/";
|
||||
byte[] logs = tar(Map.of(container + "stdout", "from task", container + "launch_container.sh", "secret"));
|
||||
CopyArchiveFromContainerCmd copy = mock(CopyArchiveFromContainerCmd.class);
|
||||
when(copy.exec()).thenAnswer(reading -> new ByteArrayInputStream(logs));
|
||||
when(docker.copyArchiveFromContainerCmd(taskName, "/mnt/yarn/logs")).thenReturn(copy);
|
||||
|
||||
storage.archiveContainerLogs("j-1", "123456789012", "us-east-1", "s3://logs/j-1/containers/");
|
||||
storage.archiveContainerLogs("j-1", "123456789012", "us-east-1", "s3://logs/j-1/containers/");
|
||||
|
||||
verify(s3, times(1)).putObjectFromStream(eq("logs"),
|
||||
eq("j-1/containers/application_1_0001/container_1_0001_01_000002/stdout.gz"), any(), anyString(), any());
|
||||
verify(s3, times(1)).putObjectFromStream(anyString(), anyString(), any(), anyString(), any());
|
||||
verify(docker, never()).execCreateCmd(taskName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStoppedPrimaryNodeWithNoNodeManagerHasNoLogsAndNoFailure() {
|
||||
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
|
||||
when(docker.copyArchiveFromContainerCmd(hdfsName, "/mnt/yarn/logs")).thenThrow(new NotFoundException("none"));
|
||||
|
||||
assertDoesNotThrow(() -> storage.archiveContainerLogs("j-1", "123456789012", "us-east-1",
|
||||
"s3://logs/j-1/containers/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nodesThatCannotBeFoundLeaveTheStepAsItEnded() {
|
||||
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
|
||||
when(docker.copyArchiveFromContainerCmd(hdfsName, "/mnt/yarn/logs")).thenThrow(new NotFoundException("none"));
|
||||
when(docker.listContainersCmd()).thenThrow(new IllegalStateException("Docker went away"));
|
||||
|
||||
assertDoesNotThrow(() -> storage.archiveContainerLogs("j-1", "123456789012", "us-east-1",
|
||||
"s3://logs/j-1/containers/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void containerLogsComeFromEveryNode() throws IOException {
|
||||
runningNodes(node(coreName, "running", IMAGE, CORE_HOST, true), node(taskName, "running", IMAGE, TASK_HOST, false));
|
||||
// The primary node runs no NodeManager, so it lists none.
|
||||
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
|
||||
nodeLogs(coreName, Map.of("application_1_0001/container_1_0001_01_000001/stdout", "from core"));
|
||||
nodeLogs(taskName, Map.of("application_1_0001/container_1_0001_01_000002/stdout", "from task"));
|
||||
|
||||
storage.archiveContainerLogs("j-1", "123456789012", "us-east-1", "s3://logs/j-1/containers/");
|
||||
|
||||
verify(s3, times(2)).putObjectFromStream(anyString(), anyString(), any(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -181,7 +848,8 @@ class EmrClusterStorageTest {
|
||||
// cluster's sharing its namespace.
|
||||
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(String.join(" ",
|
||||
"cid=$(sed -n \"s/^clusterID=//p\" /mnt/namenode/current/VERSION);"
|
||||
+ " hdfs namenode & hdfs datanode & n=2;",
|
||||
+ " hdfs namenode & n=1; if [ -z \"$FLOCI_NODE_WORKERS\" ] || [ -d /mnt/datanode/current ];"
|
||||
+ " then hdfs datanode & n=2; fi;",
|
||||
"until curl -sf -m 5 \"http://127.0.0.1:9870/jmx?qry=Hadoop:service=NameNode,name=NameNodeInfo\"",
|
||||
"| grep -q \"\\\"ClusterId\\\" : \\\"$cid\\\"\"; do",
|
||||
"[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done;"))));
|
||||
@@ -191,7 +859,7 @@ class EmrClusterStorageTest {
|
||||
// exits ends it.
|
||||
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(String.join(" ",
|
||||
"until curl -sf -m 5 \"http://127.0.0.1:9870/jmx?qry=Hadoop:service=NameNode,name=FSNamesystemState\"",
|
||||
"| grep -q \"\\\"NumLiveDataNodes\\\" : 1,\"; do",
|
||||
"| grep -q \"\\\"NumLiveDataNodes\\\" : [1-9]\"; do",
|
||||
"[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done;",
|
||||
"until curl -sf -m 5 \"http://127.0.0.1:9870/jmx?qry=Hadoop:service=NameNode,name=NameNodeInfo\"",
|
||||
"| grep -q \"\\\"Safemode\\\" : \\\"\\\"\"; do",
|
||||
@@ -275,7 +943,7 @@ class EmrClusterStorageTest {
|
||||
when(awsEnv.flociEndpoint(false)).thenReturn("http://host.docker.internal:4566");
|
||||
|
||||
SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
|
||||
"floci-network", null, new ClusterStorage.Yarn(4096, 4), NOT_STOPPED);
|
||||
"floci-network", null, () -> new ClusterStorage.Yarn(4096, 4), NOT_STOPPED);
|
||||
|
||||
// The steps' Spark submits to the ResourceManager on the primary node, its executors reaching Floci there.
|
||||
assertEquals(HOST, started.resourceManager());
|
||||
@@ -297,14 +965,14 @@ class EmrClusterStorageTest {
|
||||
+ "<value>$FLOCI_YARN_VCORES</value></property>\""))
|
||||
// Each daemon through a variable Java 8, which refuses these options, ignores.
|
||||
&& Pattern.compile("JDK_JAVA_OPTIONS=\"--add-opens=java\\.base/java\\.lang=ALL-UNNAMED[^\"]*\""
|
||||
+ " yarn resourcemanager & "
|
||||
+ " yarn resourcemanager & n=\\$\\(\\(n \\+ 1\\)\\); if \\[ -z \"\\$FLOCI_NODE_WORKERS\" \\]; then "
|
||||
+ "JDK_JAVA_OPTIONS=\"--add-opens=java\\.base/java\\.lang=ALL-UNNAMED[^\"]*\""
|
||||
+ " yarn nodemanager &").matcher(entrypoint.get(2)).find()));
|
||||
// Ready once the NodeManager has registered, and the node gone if either daemon exits while starting.
|
||||
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(
|
||||
"yarn nodemanager & n=$((n + 2)); "
|
||||
"yarn nodemanager & n=$((n + 1)); fi; "
|
||||
+ "until curl -sf -m 5 http://127.0.0.1:8088/ws/v1/cluster/metrics"
|
||||
+ " | grep -q \"\\\"activeNodes\\\":1,\"; do "
|
||||
+ " | grep -q \"\\\"activeNodes\\\":[1-9]\"; do "
|
||||
+ "[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done; fi;"
|
||||
+ " touch /tmp/floci-hdfs-ready")));
|
||||
}
|
||||
@@ -319,7 +987,7 @@ class EmrClusterStorageTest {
|
||||
when(awsEnv.flociEndpoint(false)).thenReturn("http://host.docker.internal:4566");
|
||||
|
||||
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null,
|
||||
new ClusterStorage.Yarn(4096, 4, "/opt"), NOT_STOPPED);
|
||||
() -> new ClusterStorage.Yarn(4096, 4).withHadoopFolder("/opt"), NOT_STOPPED);
|
||||
|
||||
verify(spec).withEnv("FLOCI_HADOOP_FOLDER", "/opt");
|
||||
// Its homes and commands, before the daemons start as the image's user, who keeps the environment.
|
||||
@@ -414,8 +1082,9 @@ class EmrClusterStorageTest {
|
||||
String later = "application_1_0002/container_1_0002_01_000001/stdout";
|
||||
List<List<String>> listings = nodeLogs(Map.of(earlier, "one"));
|
||||
storage.archiveContainerLogs("j-1", "123456789012", "us-east-1", "s3://logs/j-1/containers/");
|
||||
assertEquals(List.of(List.of("find", "/mnt/yarn/logs", "-mindepth", "3", "-maxdepth", "3", "-type", "f", "-printf",
|
||||
"%s %P\\n")), listings);
|
||||
// A primary node whose core nodes run the NodeManagers has no such folder, which is none to list and no failure.
|
||||
assertEquals(List.of(List.of("bash", "-c", "[ ! -d /mnt/yarn/logs ] || exec find /mnt/yarn/logs -mindepth 3"
|
||||
+ " -maxdepth 3 -type f -printf '%s %P\\n'")), listings);
|
||||
|
||||
nodeLogs(Map.of(earlier, "one", later, "two"));
|
||||
storage.archiveContainerLogs("j-1", "123456789012", "us-east-1", "s3://logs/j-1/containers/");
|
||||
@@ -1516,21 +2185,83 @@ class EmrClusterStorageTest {
|
||||
verify(lifecycle, never()).disconnectFromNetwork("floci-container", "emr-j-up-hdfs");
|
||||
}
|
||||
|
||||
// The files, by their paths in the archive, as Docker archives a folder.
|
||||
// The primary node's container logs, by their path under the NodeManager's folder, as it lists and gives them. What
|
||||
// it is asked to list.
|
||||
private List<List<String>> nodeLogs(Map<String, String> logs) throws IOException {
|
||||
return nodeLogs(hdfsName, logs);
|
||||
}
|
||||
|
||||
private List<List<String>> nodeLogs(String node, Map<String, String> logs) throws IOException {
|
||||
StringBuilder listing = new StringBuilder();
|
||||
for (Map.Entry<String, String> log : logs.entrySet()) {
|
||||
listing.append(log.getValue().length()).append(' ').append(log.getKey()).append('\n');
|
||||
byte[] archive = tar(Map.of(log.getKey().substring(log.getKey().lastIndexOf('/') + 1), log.getValue()));
|
||||
CopyArchiveFromContainerCmd copy = mock(CopyArchiveFromContainerCmd.class);
|
||||
when(copy.exec()).thenAnswer(reading -> new ByteArrayInputStream(archive));
|
||||
when(docker.copyArchiveFromContainerCmd(hdfsName, "/mnt/yarn/logs/" + log.getKey())).thenReturn(copy);
|
||||
when(docker.copyArchiveFromContainerCmd(node, "/mnt/yarn/logs/" + log.getKey())).thenReturn(copy);
|
||||
}
|
||||
return ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, listing.toString(), "");
|
||||
return ContainerExecStubs.completeEveryExec(docker, node, 0L, listing.toString(), "");
|
||||
}
|
||||
|
||||
// The primary node starts and answers ready, and so does each node named.
|
||||
private void nodesStart(String... names) {
|
||||
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
|
||||
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-1", Map.of()));
|
||||
when(lifecycle.probeContainer("c-1")).thenReturn(ContainerLiveness.RUNNING);
|
||||
when(lifecycle.resolveContainerNetworkIp("c-1", hdfsName)).thenReturn("172.18.0.5");
|
||||
ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", "");
|
||||
for (String name : names) {
|
||||
when(lifecycle.probeContainer(name)).thenReturn(ContainerLiveness.RUNNING);
|
||||
ContainerExecStubs.completeEveryExec(docker, name, 0L, "", "");
|
||||
}
|
||||
}
|
||||
|
||||
private void runningNodes(Container... nodes) {
|
||||
ListContainersCmd list = mock(ListContainersCmd.class, RETURNS_SELF);
|
||||
when(docker.listContainersCmd()).thenReturn(list);
|
||||
when(list.exec()).thenReturn(List.of(nodes));
|
||||
}
|
||||
|
||||
private static Container node(String name, String state, String image, String host, boolean core) {
|
||||
Container container = mock(Container.class);
|
||||
when(container.getNames()).thenReturn(new String[]{"/" + name});
|
||||
when(container.getState()).thenReturn(state);
|
||||
when(container.getImageId()).thenReturn(image);
|
||||
when(container.getLabels()).thenReturn(Map.of("io.floci.emr.node-host", host, "io.floci.emr.node-core",
|
||||
String.valueOf(core)));
|
||||
return container;
|
||||
}
|
||||
|
||||
// The volumes of cluster j-1's nodes Docker lists, whatever their containers.
|
||||
private void nodeVolumes(InspectVolumeResponse... volumes) {
|
||||
ListVolumesCmd list = mock(ListVolumesCmd.class, RETURNS_SELF);
|
||||
when(docker.listVolumesCmd()).thenReturn(list);
|
||||
ListVolumesResponse response = mock(ListVolumesResponse.class);
|
||||
when(response.getVolumes()).thenReturn(List.of(volumes));
|
||||
when(list.exec()).thenReturn(response);
|
||||
}
|
||||
|
||||
private static InspectVolumeResponse nodeVolume(String name, String host, boolean core) {
|
||||
InspectVolumeResponse volume = mock(InspectVolumeResponse.class);
|
||||
when(volume.getName()).thenReturn(name);
|
||||
when(volume.getLabels()).thenReturn(Map.of(ContainerStorageHelper.RESOURCE_ID_LABEL, "j-1",
|
||||
"io.floci.emr.node-host", host, "io.floci.emr.node-core", String.valueOf(core)));
|
||||
return volume;
|
||||
}
|
||||
|
||||
private static Container nodeOf(String clusterId, String name) {
|
||||
Container container = mock(Container.class);
|
||||
when(container.getNames()).thenReturn(new String[]{"/" + name});
|
||||
when(container.getLabels()).thenReturn(Map.of(ContainerStorageHelper.RESOURCE_ID_LABEL, clusterId));
|
||||
return container;
|
||||
}
|
||||
|
||||
private EmrClusterStorage queuingDecommissions(List<Runnable> queued) {
|
||||
return new EmrClusterStorage(lifecycle, containerBuilder, awsEnv, roleCredentials, currentContainer, config, s3,
|
||||
Duration.ofSeconds(120), System::nanoTime, queued::add, Duration.ZERO);
|
||||
}
|
||||
|
||||
// The files, by their paths in the archive, as Docker archives a folder.
|
||||
private static byte[] tar(Map<String, String> files) throws IOException {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
try (TarArchiveOutputStream out = new TarArchiveOutputStream(bytes)) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.floci.aws.services.emr;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.github.dockerjava.api.exception.NotFoundException;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.docker.ContainerExec;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
@@ -210,6 +211,45 @@ class EmrDockerRunnerDockerIntegrationTest {
|
||||
driverLogs.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClustersCoreAndTaskNodesRunItsExecutorsAndAShrinkKeepsItsHdfsData() {
|
||||
put("side/nodes.py", """
|
||||
import socket
|
||||
import sys
|
||||
from pyspark.sql import SparkSession
|
||||
spark = SparkSession.builder.getOrCreate()
|
||||
lines = spark.sparkContext.parallelize(range(8), 8) \\
|
||||
.map(lambda i: (socket.gethostname(), "line " + str(i))).cache()
|
||||
lines.map(lambda line: line[1]).saveAsTextFile("hdfs:///kept")
|
||||
hosts = " ".join(sorted(set(lines.map(lambda line: line[0]).collect())))
|
||||
spark.createDataFrame([(hosts,)], ["value"]).coalesce(1).write.text(sys.argv[1])
|
||||
""");
|
||||
startCluster("[]", null, ",{\"Name\":\"core\",\"InstanceRole\":\"CORE\",\"InstanceType\":\"m5.xlarge\","
|
||||
+ "\"InstanceCount\":2},{\"Name\":\"task\",\"InstanceRole\":\"TASK\",\"InstanceType\":\"m5.xlarge\","
|
||||
+ "\"InstanceCount\":1}");
|
||||
|
||||
// Its executors run on its core and task nodes, each named as ListInstances names it, not on its primary node.
|
||||
assertEquals("COMPLETED", runStep("command-runner.jar", "spark-submit", s3Uri("side/nodes.py"),
|
||||
s3Uri("hosts/")));
|
||||
List<String> instances = emr("ListInstances", "{\"ClusterId\":\"" + clusterId + "\"}").jsonPath()
|
||||
.getList("Instances.PrivateDnsName");
|
||||
for (String host : partFiles("hosts/").trim().split(" ")) {
|
||||
assertTrue(instances.subList(1, instances.size()).contains(host), host + " among " + instances);
|
||||
}
|
||||
|
||||
// A core node goes, once HDFS has moved its blocks to the one that stays, and every line is still there.
|
||||
String core = emr("ListInstanceGroups", "{\"ClusterId\":\"" + clusterId + "\"}").jsonPath()
|
||||
.getString("InstanceGroups.find { it.InstanceGroupType == 'CORE' }.Id");
|
||||
emr("ModifyInstanceGroups", "{\"ClusterId\":\"" + clusterId + "\",\"InstanceGroups\":[{\"InstanceGroupId\":\""
|
||||
+ core + "\",\"InstanceCount\":1}]}").then().statusCode(200);
|
||||
String leaving = ContainerStorageHelper.dockerName(config, "emr-" + clusterId + "-node-1-2");
|
||||
await("core node " + leaving + " to go").atMost(Duration.ofMinutes(5)).pollInterval(Duration.ofSeconds(1))
|
||||
.until(() -> gone(leaving));
|
||||
assertEquals("COMPLETED", runStep("command-runner.jar", "s3-dist-cp", "--src", "hdfs:///kept/",
|
||||
"--dest", s3Uri("kept/")));
|
||||
assertEquals("line 0\nline 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\n", partFiles("kept/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClustersHdfsWhoseDataNodeExitsStartsAgainOnItsDataForTheNextStep() {
|
||||
startCluster("[]");
|
||||
@@ -344,16 +384,31 @@ class EmrDockerRunnerDockerIntegrationTest {
|
||||
|
||||
/** The same, its logs under {@code logUri} when that is not null, as the cluster's {@code LogUri}. */
|
||||
private void startCluster(String configurations, String logUri) {
|
||||
startCluster(configurations, logUri, "");
|
||||
}
|
||||
|
||||
/** The same, with the instance groups {@code moreGroups}, each led by a comma, after its primary node's. */
|
||||
private void startCluster(String configurations, String logUri, String moreGroups) {
|
||||
clusterId = emr("RunJobFlow", "{\"Name\":\"docker-runner\",\"ReleaseLabel\":\"emr-7.5.0\","
|
||||
+ (logUri == null ? "" : "\"LogUri\":\"" + logUri + "\",")
|
||||
+ "\"Applications\":[{\"Name\":\"Hadoop\"},{\"Name\":\"Spark\"}],"
|
||||
+ "\"Configurations\":" + configurations + ","
|
||||
+ "\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true,\"InstanceGroups\":[{\"Name\":\"primary\","
|
||||
+ "\"InstanceRole\":\"MASTER\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1}]}}")
|
||||
+ "\"InstanceRole\":\"MASTER\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1}" + moreGroups + "]}}")
|
||||
.then().statusCode(200).extract().jsonPath().getString("JobFlowId");
|
||||
cleanup.register(() -> terminateClusterAndAwaitCleanup(clusterId, emrService));
|
||||
}
|
||||
|
||||
/** Whether Docker no longer has the container named so. */
|
||||
private boolean gone(String name) {
|
||||
try {
|
||||
lifecycle.getDockerClient().inspectContainerCmd(name).exec();
|
||||
return false;
|
||||
} catch (NotFoundException e) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** Adds one step to the cluster and returns the state it ended in. */
|
||||
private String runStep(String jar, String... args) {
|
||||
ObjectNode request = JSON.createObjectNode().put("JobFlowId", clusterId);
|
||||
|
||||
@@ -204,7 +204,7 @@ class EmrResizeIntegrationTest {
|
||||
.body(primary + ".Ec2InstanceId", equalTo("i-00000000000000001"))
|
||||
.body(primary + ".PrivateDnsName", equalTo("ip-10-0-0-1.ec2.internal"))
|
||||
.body("Instances.findAll { it.InstanceGroupId == '" + core + "' }.PrivateIpAddress",
|
||||
equalTo(List.of("10.0.0.2", "10.0.0.3", "10.0.0.4")));
|
||||
equalTo(List.of("10.1.0.1", "10.1.0.2", "10.1.0.3")));
|
||||
emr("DescribeCluster", "{\"ClusterId\":\"" + id + "\"}").then().statusCode(200)
|
||||
.body("Cluster.MasterPublicDnsName", equalTo("ip-10-0-0-1.ec2.internal"));
|
||||
emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + id + "\"]}").then().statusCode(200);
|
||||
@@ -222,7 +222,30 @@ class EmrResizeIntegrationTest {
|
||||
emr("ListInstances", "{\"ClusterId\":\"" + id + "\"}").then().statusCode(200)
|
||||
.body("Instances.Ec2InstanceId", equalTo(List.of("i-00000000000000002", "i-00000000000000001",
|
||||
"i-00000000000000003")))
|
||||
.body("Instances.PrivateIpAddress", equalTo(List.of("10.0.0.2", "10.0.0.1", "10.0.0.3")));
|
||||
.body("Instances.PrivateIpAddress", equalTo(List.of("10.1.0.1", "10.0.0.1", "10.2.0.1")));
|
||||
emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + id + "\"]}").then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(10)
|
||||
void anInstanceKeepsItsAddressWhileAGroupListedBeforeItResizes() {
|
||||
String id = emr("RunJobFlow", "{\"Name\":\"stable-addresses\",\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true,"
|
||||
+ "\"InstanceGroups\":[{\"InstanceRole\":\"MASTER\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1},"
|
||||
+ "{\"InstanceRole\":\"CORE\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1},"
|
||||
+ "{\"InstanceRole\":\"TASK\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":2}]}}")
|
||||
.then().statusCode(200).extract().path("JobFlowId");
|
||||
String core = emr("ListInstanceGroups", "{\"ClusterId\":\"" + id + "\"}").jsonPath()
|
||||
.getString("InstanceGroups.find { it.InstanceGroupType == 'CORE' }.Id");
|
||||
String task = emr("ListInstanceGroups", "{\"ClusterId\":\"" + id + "\"}").jsonPath()
|
||||
.getString("InstanceGroups.find { it.InstanceGroupType == 'TASK' }.Id");
|
||||
emr("ModifyInstanceGroups", "{\"ClusterId\":\"" + id + "\",\"InstanceGroups\":["
|
||||
+ "{\"InstanceGroupId\":\"" + core + "\",\"InstanceCount\":2}]}").then().statusCode(200);
|
||||
|
||||
emr("ListInstances", "{\"ClusterId\":\"" + id + "\"}").then().statusCode(200)
|
||||
.body("Instances.findAll { it.InstanceGroupId == '" + task + "' }.PrivateIpAddress",
|
||||
equalTo(List.of("10.2.0.1", "10.2.0.2")))
|
||||
.body("Instances.findAll { it.InstanceGroupId == '" + task + "' }.PrivateDnsName",
|
||||
equalTo(List.of("ip-10-2-0-1.ec2.internal", "ip-10-2-0-2.ec2.internal")));
|
||||
emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + id + "\"]}").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.ContainerTeardown;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
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.services.emr.model.EmrStep;
|
||||
import io.floci.aws.services.emrserverless.EmrServerlessSparkRunner;
|
||||
@@ -337,6 +338,208 @@ class EmrServiceContainerStepsTest {
|
||||
assertEquals("COMPLETED", service.describeStep(cluster.getId(), cluster.getSteps().get(0).getId()).getState());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClustersCoreAndTaskGroupsAreItsNodesNamedAsListInstancesNamesThem() {
|
||||
fixture.clusterStorage.ownNetwork = true;
|
||||
EmrCluster requested = cluster("nodes", true, sparkStep("report", "CONTINUE"));
|
||||
requested.setInstanceGroups(new ArrayList<>(List.of(group("CORE", 2), group("MASTER", 1), group("TASK", 1))));
|
||||
service.runJobFlow(requested, REGION);
|
||||
|
||||
fixture.runStepThread();
|
||||
|
||||
ClusterStorage.Yarn yarn = fixture.clusterStorage.yarns.get(0);
|
||||
assertEquals(List.of(new ClusterStorage.Node("1-1", "ip-10-1-0-1.ec2.internal", true),
|
||||
new ClusterStorage.Node("1-2", "ip-10-1-0-2.ec2.internal", true),
|
||||
new ClusterStorage.Node("2-1", "ip-10-2-0-1.ec2.internal", false)), yarn.nodes());
|
||||
assertEquals(1, yarn.replication());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPrimaryNodeWorksUnlessItsClusterWasCreatedWithCoreNodes() {
|
||||
fixture.clusterStorage.ownNetwork = true;
|
||||
EmrCluster withoutCore = cluster("task-only", true, sparkStep("report", "CONTINUE"));
|
||||
withoutCore.setInstanceGroups(new ArrayList<>(List.of(group("MASTER", 1), group("TASK", 1))));
|
||||
EmrCluster grown = service.runJobFlow(withoutCore, REGION);
|
||||
fixture.runStepThread();
|
||||
EmrCluster withCore = cluster("with-core", true, sparkStep("report", "CONTINUE"));
|
||||
withCore.setInstanceGroups(new ArrayList<>(List.of(group("MASTER", 1), group("CORE", 1))));
|
||||
service.runJobFlow(withCore, REGION);
|
||||
fixture.runStepThread();
|
||||
|
||||
service.addInstanceGroups(grown.getId(), List.of(group("CORE", 2)));
|
||||
fixture.runStepThread();
|
||||
|
||||
assertTrue(fixture.clusterStorage.yarns.get(0).primaryWorks());
|
||||
assertFalse(fixture.clusterStorage.yarns.get(1).primaryWorks());
|
||||
// Its DataNode holds the blocks written before, which core nodes added since do not.
|
||||
ClusterStorage.Yarn withCoreNodes = fixture.clusterStorage.resizes.get(0);
|
||||
assertEquals(List.of(true, true, false), withCoreNodes.nodes().stream().map(ClusterStorage.Node::core).toList());
|
||||
assertTrue(withCoreNodes.primaryWorks());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFleetsUnitOfCapacityIsOneNode() {
|
||||
fixture.clusterStorage.ownNetwork = true;
|
||||
EmrCluster requested = cluster("fleets", true, sparkStep("report", "CONTINUE"));
|
||||
requested.setInstanceFleets(new ArrayList<>(List.of(fleet("MASTER", 1, 0), fleet("CORE", 1, 1),
|
||||
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("1-2", "ip-10-1-0-2.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;
|
||||
EmrCluster requested = cluster("capped", true, sparkStep("report", "CONTINUE"));
|
||||
requested.setInstanceGroups(new ArrayList<>(List.of(group("MASTER", 1), group("TASK", 5), group("CORE", 3))));
|
||||
service.runJobFlow(requested, REGION);
|
||||
|
||||
fixture.runStepThread();
|
||||
|
||||
List<ClusterStorage.Node> nodes = fixture.clusterStorage.yarns.get(0).nodes();
|
||||
assertEquals(4, nodes.size());
|
||||
assertEquals(List.of(true, true, true, false), nodes.stream().map(ClusterStorage.Node::core).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void itsHdfsKeepsTheCopiesEmrKeepsForTheCoreNodesItWasCreatedWith() {
|
||||
assertEquals(1, replicationOf(3, null));
|
||||
assertEquals(2, replicationOf(4, null));
|
||||
assertEquals(3, replicationOf(10, null));
|
||||
// Never more than the nodes that hold them.
|
||||
assertEquals(2, replicationOf(2, "3"));
|
||||
// "To overwrite the default value, use the hdfs-site classification."
|
||||
assertEquals(3, replicationOf(3, "3"));
|
||||
// One it cannot use keeps EMR's default, which its log says.
|
||||
assertEquals(1, replicationOf(2, "not-a-number"));
|
||||
assertEquals(2, replicationOf(4, "0"));
|
||||
assertEquals(2, replicationOf(4, "-1"));
|
||||
}
|
||||
|
||||
private int replicationOf(int coreNodes, String configured) {
|
||||
EmrServiceFixture own = EmrServiceFixture.docker(runner, null);
|
||||
own.clusterStorage.ownNetwork = true;
|
||||
EmrCluster requested = cluster("copies", true, sparkStep("report", "CONTINUE"));
|
||||
requested.setInstanceGroups(new ArrayList<>(List.of(group("MASTER", 1), group("CORE", coreNodes))));
|
||||
if (configured != null) {
|
||||
requested.setConfigurations("[{\"Classification\":\"hdfs-site\",\"Properties\":"
|
||||
+ "{\"dfs.replication\":\"" + configured + "\"}}]");
|
||||
}
|
||||
own.service.runJobFlow(requested, REGION);
|
||||
own.runStepThread();
|
||||
return own.clusterStorage.yarns.get(0).replication();
|
||||
}
|
||||
|
||||
@Test
|
||||
void itsCoreNodesAreNotShrunkBelowTheCopiesItsHdfsKeeps() {
|
||||
fixture.clusterStorage.ownNetwork = true;
|
||||
EmrCluster requested = cluster("floor", true, sparkStep("report", "CONTINUE"));
|
||||
requested.setInstanceGroups(new ArrayList<>(List.of(group("MASTER", 1), group("CORE", 4))));
|
||||
EmrCluster cluster = service.runJobFlow(requested, REGION);
|
||||
fixture.runStepThread();
|
||||
String core = cluster.getInstanceGroups().get(1).getId();
|
||||
|
||||
service.modifyInstanceGroups(cluster.getId(), REGION,
|
||||
List.of(new EmrService.InstanceGroupModification(core, 1, null)));
|
||||
fixture.runStepThread();
|
||||
|
||||
assertEquals(2, fixture.clusterStorage.resizes.get(0).nodes().size());
|
||||
assertEquals(2, fixture.clusterStorage.resizes.get(0).replication());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aResizeReachesTheNodesOnceAStepHasStartedThem() {
|
||||
fixture.clusterStorage.ownNetwork = true;
|
||||
EmrCluster requested = cluster("resize", true, sparkStep("report", "CONTINUE"));
|
||||
requested.setInstanceGroups(new ArrayList<>(List.of(group("MASTER", 1), group("CORE", 1), group("TASK", 1))));
|
||||
EmrCluster cluster = service.runJobFlow(requested, REGION);
|
||||
fixture.runStepThread();
|
||||
String task = cluster.getInstanceGroups().get(2).getId();
|
||||
|
||||
service.modifyInstanceGroups(cluster.getId(), REGION,
|
||||
List.of(new EmrService.InstanceGroupModification(task, 3, null)));
|
||||
fixture.runStepThread();
|
||||
assertEquals(4, fixture.clusterStorage.resizes.get(0).nodes().size());
|
||||
|
||||
EmrInstanceGroup added = group("TASK", 1);
|
||||
service.addInstanceGroups(cluster.getId(), List.of(added));
|
||||
fixture.runStepThread();
|
||||
assertEquals(4, fixture.clusterStorage.resizes.get(1).nodes().size());
|
||||
assertEquals(new ClusterStorage.Node("2-3", "ip-10-2-0-3.ec2.internal", false),
|
||||
fixture.clusterStorage.resizes.get(1).nodes().get(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aResizeOfAFleetReachesItsNodesToo() {
|
||||
fixture.clusterStorage.ownNetwork = true;
|
||||
EmrCluster requested = cluster("fleet-resize", true, sparkStep("report", "CONTINUE"));
|
||||
requested.setInstanceFleets(new ArrayList<>(List.of(fleet("MASTER", 1, 0), fleet("CORE", 1, 0))));
|
||||
EmrCluster cluster = service.runJobFlow(requested, REGION);
|
||||
fixture.runStepThread();
|
||||
String core = cluster.getInstanceFleets().get(1).getId();
|
||||
|
||||
service.modifyInstanceFleet(cluster.getId(), core, 2, null);
|
||||
fixture.runStepThread();
|
||||
assertEquals(2, fixture.clusterStorage.resizes.get(0).nodes().size());
|
||||
|
||||
service.addInstanceFleet(cluster.getId(), fleet("TASK", 1, 0));
|
||||
fixture.runStepThread();
|
||||
assertEquals(3, fixture.clusterStorage.resizes.get(1).nodes().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aResizeBeforeAStepHasStartedTheNodesIsLeftToThatStep() {
|
||||
fixture.clusterStorage.ownNetwork = true;
|
||||
EmrCluster requested = cluster("early", true);
|
||||
requested.setInstanceGroups(new ArrayList<>(List.of(group("MASTER", 1), group("CORE", 1))));
|
||||
EmrCluster cluster = service.runJobFlow(requested, REGION);
|
||||
String core = cluster.getInstanceGroups().get(1).getId();
|
||||
|
||||
service.modifyInstanceGroups(cluster.getId(), REGION,
|
||||
List.of(new EmrService.InstanceGroupModification(core, 2, null)));
|
||||
|
||||
assertEquals(0, fixture.stepThreadsWaiting());
|
||||
assertEquals(List.of(), fixture.clusterStorage.resizes);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStepQueuedBeforeAResizeStartsTheNodesItAsksForByThen() {
|
||||
fixture.clusterStorage.ownNetwork = true;
|
||||
EmrCluster requested = cluster("queued", true, sparkStep("report", "CONTINUE"));
|
||||
requested.setInstanceGroups(new ArrayList<>(List.of(group("MASTER", 1), group("CORE", 1))));
|
||||
EmrCluster cluster = service.runJobFlow(requested, REGION);
|
||||
String core = cluster.getInstanceGroups().get(1).getId();
|
||||
|
||||
// The step's thread has not run yet.
|
||||
service.modifyInstanceGroups(cluster.getId(), REGION,
|
||||
List.of(new EmrService.InstanceGroupModification(core, 3, null)));
|
||||
fixture.runStepThread();
|
||||
|
||||
assertEquals(3, fixture.clusterStorage.yarns.get(0).nodes().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterThatDoesNotRunYarnFollowsNoResize() {
|
||||
fixture.clusterStorage.ownNetwork = false;
|
||||
EmrCluster requested = cluster("no-yarn", true, sparkStep("report", "CONTINUE"));
|
||||
requested.setInstanceGroups(new ArrayList<>(List.of(group("MASTER", 1), group("TASK", 1))));
|
||||
EmrCluster cluster = service.runJobFlow(requested, REGION);
|
||||
fixture.runStepThread();
|
||||
String task = cluster.getInstanceGroups().get(1).getId();
|
||||
|
||||
service.modifyInstanceGroups(cluster.getId(), REGION,
|
||||
List.of(new EmrService.InstanceGroupModification(task, 2, null)));
|
||||
|
||||
assertEquals(0, fixture.stepThreadsWaiting());
|
||||
assertEquals(List.of(), fixture.clusterStorage.resizes);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStepStartsItsClustersHdfsOnItsPrimaryNodeFromTheReleasesHiveImage() {
|
||||
EmrCluster requested = cluster("hdfs", true, sparkStep("report", "CONTINUE"), sparkStep("next", "CONTINUE"));
|
||||
@@ -483,7 +686,8 @@ class EmrServiceContainerStepsTest {
|
||||
SparkJobRunner.Job job = runner.jobs.get(0);
|
||||
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, job.imageTemplate());
|
||||
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, fixture.clusterStorage.hdfs.get(0).get(2));
|
||||
assertEquals(List.of(new ClusterStorage.Yarn(4096, 4, "/opt")), fixture.clusterStorage.yarns);
|
||||
assertEquals(List.of(new ClusterStorage.Yarn(4096, 4).withHadoopFolder("/opt")),
|
||||
fixture.clusterStorage.yarns);
|
||||
assertEquals(hdfsStorage(cluster).withYarn("ip-10-0-0-1.ec2.internal",
|
||||
EmrServiceFixture.RecordingStorage.FLOCI_ON_NETWORK), job.storage());
|
||||
}
|
||||
@@ -1477,6 +1681,14 @@ class EmrServiceContainerStepsTest {
|
||||
return cluster;
|
||||
}
|
||||
|
||||
private static EmrInstanceFleet fleet(String type, int onDemand, int spot) {
|
||||
EmrInstanceFleet fleet = new EmrInstanceFleet();
|
||||
fleet.setInstanceFleetType(type);
|
||||
fleet.setTargetOnDemandCapacity(onDemand);
|
||||
fleet.setTargetSpotCapacity(spot);
|
||||
return fleet;
|
||||
}
|
||||
|
||||
private static EmrInstanceGroup group(String type, int count) {
|
||||
EmrInstanceGroup group = new EmrInstanceGroup();
|
||||
group.setInstanceGroupType(type);
|
||||
|
||||
@@ -21,6 +21,7 @@ import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
@@ -78,6 +79,8 @@ final class EmrServiceFixture {
|
||||
Consumer<BooleanSupplier> whileStartingHdfs = stopped -> { };
|
||||
final List<String> removed = new ArrayList<>();
|
||||
final List<Set<String>> kept = new ArrayList<>();
|
||||
// Each resize asked for: its cluster and the nodes it wants.
|
||||
final List<ClusterStorage.Yarn> resizes = new ArrayList<>();
|
||||
boolean refuse;
|
||||
Runnable whileCreating = () -> { };
|
||||
|
||||
@@ -97,6 +100,11 @@ final class EmrServiceFixture {
|
||||
return ownNetwork;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resize(String clusterId, Supplier<Yarn> yarn) {
|
||||
resizes.add(yarn.get());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void archiveContainerLogs(String clusterId, String accountId, String region, String logFolder) {
|
||||
containerLogs.add(List.of(clusterId, logFolder));
|
||||
@@ -104,7 +112,8 @@ final class EmrServiceFixture {
|
||||
|
||||
@Override
|
||||
public SparkJobRunner.Storage hdfs(String clusterId, String accountId, String region, String host,
|
||||
String image, String dockerNetwork, HiveMetastore hiveMetastore, Yarn yarn,
|
||||
String image, String dockerNetwork, HiveMetastore hiveMetastore,
|
||||
Supplier<Yarn> yarn,
|
||||
BooleanSupplier stopped) {
|
||||
hdfs.add(Arrays.asList(clusterId, host, image, dockerNetwork, String.valueOf(hiveMetastore != null),
|
||||
hiveMetastore != null ? hiveMetastore.role() : null));
|
||||
@@ -112,7 +121,7 @@ final class EmrServiceFixture {
|
||||
metastores.add(hiveMetastore);
|
||||
}
|
||||
if (yarn != null) {
|
||||
yarns.add(yarn);
|
||||
yarns.add(yarn.get());
|
||||
}
|
||||
whileStartingHdfs.accept(stopped);
|
||||
if (hdfsFailure != null) {
|
||||
@@ -271,6 +280,7 @@ final class EmrServiceFixture {
|
||||
when(config.services().emr().dockerNetwork()).thenReturn(Optional.empty());
|
||||
when(config.services().emr().yarnNodeMemoryMb()).thenReturn(4096);
|
||||
when(config.services().emr().yarnNodeVcores()).thenReturn(4);
|
||||
when(config.services().emr().yarnMaxWorkerNodes()).thenReturn(4);
|
||||
when(config.services().emr().reconcileContainersOnStartup()).thenReturn(reconcile);
|
||||
return config;
|
||||
}
|
||||
|
||||
@@ -617,6 +617,23 @@ class EmrServerlessSparkRunnerTest {
|
||||
"s3://bucket/jobs/report.py"), arguments.subList(20, arguments.size()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStepWritesTheCopiesOfABlockItsCoreNodesKeep() {
|
||||
SparkJobRunner.Job job = stepJob(Map.of()).onStorage(STORAGE.withReplication(2));
|
||||
|
||||
assertTrue(EmrServerlessSparkRunner.sparkSubmitArguments(job, "http://floci:4566", List.of())
|
||||
.contains("spark.hadoop.dfs.replication=2"));
|
||||
assertTrue(EmrServerlessSparkRunner.hiveArguments(job, "http://floci:4566").contains("dfs.replication=2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStepOnAClusterWhoseHdfsIsOnItsPrimaryNodeLeavesTheCopiesOfABlockAlone() {
|
||||
SparkJobRunner.Job job = stepJob(Map.of()).onStorage(STORAGE);
|
||||
|
||||
assertFalse(EmrServerlessSparkRunner.sparkSubmitArguments(job, "http://floci:4566", List.of()).toString()
|
||||
.contains("dfs.replication"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStepOnItsClustersYarnSubmitsToItsResourceManagerWithExecutorsSizedForItsNode() {
|
||||
SparkJobRunner.Job job = stepJob(Map.of("spark.executor.memory", "2g"))
|
||||
@@ -714,6 +731,34 @@ class EmrServerlessSparkRunnerTest {
|
||||
assertTrue(arguments.indexOf(glue) > metastore, arguments.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHadoopCommandOnAClusterWhoseCoreNodesHoldItsHdfsWritesTheirCopies() {
|
||||
ContainerBuilder builder = mock(ContainerBuilder.class);
|
||||
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
|
||||
when(builder.newContainer(anyString())).thenReturn(spec);
|
||||
List<String> command = List.of("bash", "-c", "hadoop fs -put data.csv /input/");
|
||||
|
||||
runner(builder).run(commandJob(command, Map.of(), STORAGE.withReplication(2)), progress);
|
||||
|
||||
// In hdfs-site.xml, as a client reads it after core-site.xml and the image's says two.
|
||||
verify(spec).withEnv("FLOCI_HDFS_SITE", "<property><name>dfs.replication</name><value>2</value></property>");
|
||||
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(String.join("\n",
|
||||
" if [ -n \"${FLOCI_HDFS_SITE:-}\" ]; then",
|
||||
" site hdfs-site.xml \"$FLOCI_HDFS_SITE\"",
|
||||
" fi"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHadoopCommandOnAClusterWhosePrimaryNodeHoldsItsHdfsLeavesTheImagesCopies() {
|
||||
ContainerBuilder builder = mock(ContainerBuilder.class);
|
||||
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
|
||||
when(builder.newContainer(anyString())).thenReturn(spec);
|
||||
|
||||
runner(builder).run(commandJob(List.of("bash", "-c", "true"), Map.of(), STORAGE), progress);
|
||||
|
||||
verify(spec, never()).withEnv(eq("FLOCI_HDFS_SITE"), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCommandOnAClusterGivesItsHadoopCommandTheClustersHdfsToo() {
|
||||
ContainerBuilder builder = mock(ContainerBuilder.class);
|
||||
@@ -1465,6 +1510,21 @@ class EmrServerlessSparkRunnerTest {
|
||||
verify(lifecycle, never()).removeIfExists("another-deployments");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNodeOfALiveClusterIsNoDriverTheSweepRemoves() {
|
||||
EmrServerlessSparkRunner runner = runner();
|
||||
when(config.port()).thenReturn(4566);
|
||||
Container node = mock(Container.class);
|
||||
when(node.getId()).thenReturn("node");
|
||||
when(node.getLabels()).thenReturn(Map.of(ContainerStorageHelper.SERVICE_LABEL, "emr",
|
||||
ContainerStorageHelper.OWNER_LABEL, "4566", ContainerStorageHelper.COMPONENT_LABEL, "emr-node"));
|
||||
when(docker.listContainersCmd().withShowAll(true).withLabelFilter(anyMap()).exec()).thenReturn(List.of(node));
|
||||
|
||||
runner.removeLeftoverDrivers("emr");
|
||||
|
||||
verify(lifecycle, never()).removeIfExists("node");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theHdfsOfALiveClusterIsNoDriverTheSweepRemoves() {
|
||||
EmrServerlessSparkRunner runner = runner();
|
||||
|
||||
Reference in new issue
Block a user