diff --git a/docs/services/emr.md b/docs/services/emr.md index 7941802c0e..288a29f597 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -150,18 +150,29 @@ but for its bootstrap actions and its storage. container of their own, `emr--hdfs`, 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. The container is on a Docker network of the cluster's own, also `emr--hdfs`, - which the cluster's steps join besides their own, so the steps of other clusters, another account's included, - cannot reach its files; each cluster whose HDFS runs takes one network from the Docker daemon's address pools. - The cluster's first step starts it, and waits for it: a step whose cluster's HDFS is not ready within two minutes - fails ("The step could not start: The HDFS of EMR cluster ... did not start within 120 seconds"). If its NameNode or DataNode exits, its container ends with it, and the - cluster's next step starts it again on its data. Their warnings and errors are the container's output, which - `docker logs` shows. With `docker-network` set to `host`, steps reach it on the host's loopback, and its daemons - listen there only, as anyone reaching them could change its files, on the host's own ports (8020, 9870, 9866, - 9864, 9867), so only one cluster's HDFS runs at a time. With `container:`, its container joins that - namespace as the steps do, and listens on its loopback in the same way; the primary node's name goes in the hosts - file that namespace's containers share, ``'s own included. With `none`, steps have no network, so the - cluster runs no HDFS, and its steps run as without one. Steps reach + and permissions off. On a cluster whose `Applications` name Hive, the same container runs Hive's metastore + service, 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` and `hive-site` after its own + settings, as EMR's primary node does, so a `hive-site` setting of `hive.metastore.warehouse.dir`, say, holds for the + service as for the Hive steps. A primary node with the service that an earlier Floci left running starts again, on + the data its volume keeps, as its session went with that Floci. The container is on a Docker network of the cluster's own, also + `emr--hdfs`, which the cluster's steps join besides their own, so the steps of other clusters, another + account's included, cannot reach its files or tables; each cluster whose HDFS runs takes one network from the + Docker daemon's address pools. When Floci runs in a container, that container joins the network of each cluster + with Hive too, as `floci`, which is how the metastore reaches Floci's S3, and leaves it when the HDFS container + goes. The cluster's first step starts it, and waits for it: a step whose cluster's HDFS is not ready within two + minutes fails ("The step could not start: The HDFS of EMR cluster ... did not start within 120 seconds"). If its + NameNode, DataNode or metastore exits, its container ends with it, and the cluster's next step starts it again on + its data. Their warnings and errors are the container's output, which `docker logs` shows. With `docker-network` + set to `host`, steps reach it on the host's loopback, and its daemons listen there only, as anyone reaching them + could change its files, on the host's own ports (8020, 9870, 9866, 9864, 9867), so only one cluster's HDFS runs at + a time. With `container:`, its container joins that namespace as the steps do, and listens on its loopback in + the same way; the primary node's name goes in the hosts file that namespace's containers share, ``'s own + included. In both, the metastore service does not run: Hive 3's has no setting for the address it listens on, so + it would take 9083 on every interface of the namespace, the host's own for `host`, and Hive steps keep a metastore + of their own (see **Hive steps**). With `none`, steps have no network, so the cluster runs no HDFS, and its steps + run as without one. Steps reach it by the primary node's `PrivateDnsName`, as `ListInstances` gives it (`ip-10-0-0-1.ec2.internal`, say), on port 8020: `hdfs://` paths without a host, and paths without a scheme ("hdfs:// (or no prefix)"), lead there through `fs.defaultFS`, a relative path under `/user/hadoop`, and the cluster's `spark-defaults` and `core-site` can set @@ -228,23 +239,28 @@ but for its bootstrap actions and its storage. running `hive-script`, as the AWS CLI writes a `Type=Hive` step (`hive-script --run-hive-script --args` and the step's `Args`), or `hive` itself, runs Hive: `hive-script` runs `hive` with the arguments after `--args`, as the image's `hadoop` user in `/home/hadoop`, with Tez in local mode in its JVM, as an [EMR Serverless Hive job - run](emr-serverless.md#running-hive-job-runs)'s does, on the cluster's storage. It gets the cluster's - `core-site`, `tez-site` and `hive-site` properties, each a `--hiveconf`, then the step's own arguments, so a - `--hiveconf` of the step's wins over a classification's, as it does over `hive-site.xml`; the cluster's - `hive-env` exports are its environment. Floci's settings come before them all, and any of them replaces one: S3A - on Floci's S3 for `s3://`, Tez in local mode, the cluster's HDFS, and its metastore. "By default, Hive records - metastore information in a MySQL database on the primary node's file system", which Floci keeps as an embedded - Derby database in the cluster's `/mnt`, so a table one Hive step makes is there for the next, until the cluster - ends. The `hive-site` setting of `hive.metastore.client.factory.class` the Release Guide gives for the Glue Data - Catalog uses Floci's Glue instead, with the cluster's account as its `hive.metastore.glue.catalogid`, which a - `hive-site` one replaces. A table without a `LOCATION` is in the cluster's HDFS, under `/user/hive/warehouse` ("By - default, this is a location in HDFS"), which other steps read as `hdfs:///user/hive/warehouse/`, and an - `hdfs://` `LOCATION` is there too. Spark steps do not use the cluster's Hive metastore, so they see a Hive step's - tables only through the Glue Data Catalog. Only one Hive step at a time can use the cluster's metastore: with - `StepConcurrencyLevel` above 1, a Hive step that starts while another runs fails ("Another instance of Derby may - have already booted the database"). What the bootstrap actions installed is there for every step, Hive's - included. A script or command that starts `hive` itself gets none of these settings: only a Hive step runs Hive. - Hive's own log stays in the container. + run](emr-serverless.md#running-hive-job-runs)'s does, on the cluster's storage. It gets the cluster's `core-site`, + `tez-site` and `hive-site` properties, each a `--hiveconf`, then the step's own arguments, so a `--hiveconf` of + the step's wins over a classification's, as it does over `hive-site.xml`; the cluster's `hive-env` exports are its + environment. Floci's settings come before them all, and any of them replaces one: S3A on Floci's S3 for `s3://`, + Tez in local mode, the cluster's HDFS, and its metastore. "By default, Hive records metastore information in a + MySQL database on the primary node's file system", which Floci keeps in a Derby database of the metastore service + its primary node runs (see **Storage**), so a table one Hive step makes is there for the next, until the cluster + ends, and any number of Hive steps use it at once. The `hive-site` setting of + `hive.metastore.client.factory.class` the Release Guide gives for the Glue Data Catalog uses Floci's Glue instead, + with the cluster's account as its `hive.metastore.glue.catalogid`, which a `hive-site` one replaces. A table + without a `LOCATION` is in the cluster's HDFS, under `/user/hive/warehouse` ("By default, this is a location in + HDFS"), which other steps read as `hdfs:///user/hive/warehouse/
`, and an `hdfs://` `LOCATION` is there too. + The cluster's Spark steps use that metastore too, so a Spark step with Hive support reads a Hive step's tables and + makes tables Hive steps read, as the Glue Data Catalog is the one to pick "when you require a persistent Hive + metastore or a Hive metastore shared by different clusters"; a `spark-hive-site` naming its client factory still + uses Floci's Glue. Where that service does not run, with `docker-network` set to `host` or `container:`, or to + `none`, the metastore is an embedded Derby database in the cluster's `/mnt` instead, which only one Hive step at a + time can use: with `StepConcurrencyLevel` above 1, a Hive step that starts while another runs fails ("Another + instance of Derby may have already booted the database"), and Spark steps see a Hive step's tables only through + the Glue Data Catalog. What the bootstrap actions installed is there for every step, Hive's included. A script or + command that starts `hive` itself gets none of these settings: only a Hive step runs Hive. Hive's own log stays in + the container. * **S3DistCp**: the image has no `s3-dist-cp`, so a `command-runner.jar` step whose first argument is `s3-dist-cp`, the Release Guide's form, runs Floci's own program instead, through `spark-submit` in the step's container, copying through Hadoop's file systems: `--src` and `--dest` take @@ -378,6 +394,15 @@ but for its bootstrap actions and its storage. release. A release with no EMR Serverless image, or another with no EMR Serverless Hive image, fails its steps with "The step could not start: Could not pull image". +### Known limitations + +- **No Hive metastore service in a network namespace the steps share.** With `docker-network` set to `host` or + `container:`, the primary node runs HDFS but not Hive's metastore service: Hive 3's has no setting for the + address it listens on, so it would serve its tables, and the files under them, on every interface of the + namespace, the host's own for `host`. Hive steps there keep an embedded Derby database in the cluster's `/mnt`, so + only one Hive step at a time can use it, and Spark steps see a Hive step's tables only through the Glue Data + Catalog. On a cluster's own network, the default, the service runs (see **Storage** and **Hive steps**). + ## EventBridge events Every state a cluster or a step enters is sent to the default EventBridge bus of its Region, in the diff --git a/src/main/java/io/floci/aws/core/common/dns/EmbeddedDnsServer.java b/src/main/java/io/floci/aws/core/common/dns/EmbeddedDnsServer.java index 327c2a54d7..b02031c748 100644 --- a/src/main/java/io/floci/aws/core/common/dns/EmbeddedDnsServer.java +++ b/src/main/java/io/floci/aws/core/common/dns/EmbeddedDnsServer.java @@ -6,6 +6,7 @@ import io.floci.aws.config.TlsConfigSource; import io.floci.aws.core.common.DomainNames; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.docker.ContainerDetector; +import io.floci.aws.core.common.docker.CurrentContainerNetworkResolver; import io.quarkus.runtime.Startup; import io.vertx.core.Future; import io.vertx.core.Vertx; @@ -22,6 +23,7 @@ import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.SocketTimeoutException; +import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -110,6 +112,16 @@ public class EmbeddedDnsServer { this(suffixes, List.of()); } + /** + * This container's address on the network the containers it launches join, which is how they reach this server. + * The host's own lookup takes the first of its networks by name, which after a crash can be one Floci made and + * is still on; it answers only when that network cannot be told. + */ + static String ownAddress(CurrentContainerNetworkResolver currentContainer) throws UnknownHostException { + Optional address = currentContainer.resolveContainerIp(); + return address.isPresent() ? address.get() : InetAddress.getLocalHost().getHostAddress(); + } + /** * The certificate generator cannot read application.yml, so DNS spoofing without AWS SANs on * the certificate only happens when the flag and TLS are on but the flag is not visible to it. @@ -144,7 +156,8 @@ public class EmbeddedDnsServer { public EmbeddedDnsServer(EmulatorConfig config, ContainerDetector containerDetector, Vertx vertx, Instance recordSources, Instance forwardingRuleSources, - Instance clientVpcSources) { + Instance clientVpcSources, + CurrentContainerNetworkResolver currentContainer) { this.recordSources = recordSources; this.forwardingRuleSources = forwardingRuleSources; this.clientVpcSources = clientVpcSources; @@ -152,7 +165,7 @@ public class EmbeddedDnsServer { return; } try { - String myIp = InetAddress.getLocalHost().getHostAddress(); + String myIp = ownAddress(currentContainer); upstreamDnsServers = composeUpstreams(readResolvConfNameservers(), config.dns().containerFallbackServers()); diff --git a/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java index 1628bf27be..299adc34ea 100644 --- a/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java +++ b/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java @@ -1031,6 +1031,53 @@ public class ContainerLifecycleManager { .exec(); } + /** + * Connects the running container {@code containerId} to {@code networkName}, where its other containers reach it + * as {@code alias}, unless it is on it already. + */ + public void ensureConnected(String containerId, String networkName, String alias) { + if (networksOf(containerId).containsKey(networkName)) { + return; + } + dockerClient.connectToNetworkCmd() + .withContainerId(containerId) + .withNetworkId(networkName) + .withContainerNetwork(new ContainerNetwork().withAliases(alias)) + .exec(); + LOG.debugv("Connected {0} to network {1} as {2}", containerId, networkName, alias); + } + + /** + * Disconnects the container {@code containerId} from {@code networkName} when it is on it: true once it is not, + * false when Docker kept it there. + */ + public boolean disconnectFromNetwork(String containerId, String networkName) { + try { + if (networksOf(containerId).containsKey(networkName)) { + dockerClient.disconnectFromNetworkCmd() + .withContainerId(containerId) + .withNetworkId(networkName) + .withForce(true) + .exec(); + LOG.debugv("Disconnected {0} from network {1}", containerId, networkName); + } + return true; + } catch (NotFoundException e) { + return true; + } catch (Exception e) { + LOG.warnv("Error disconnecting {0} from network {1}: {2}", containerId, networkName, e.getMessage()); + return false; + } + } + + // The networks a container is on, by name. + private Map networksOf(String containerId) { + InspectContainerResponse inspect = dockerClient.inspectContainerCmd(containerId).exec(); + Map networks = inspect.getNetworkSettings() != null + ? inspect.getNetworkSettings().getNetworks() : null; + return networks != null ? networks : Map.of(); + } + /** * Removes the network {@code networkName}: true once it is gone, false when Docker kept it, as * {@link #removeVolume} says of a volume. diff --git a/src/main/java/io/floci/aws/core/common/docker/CurrentContainerNetworkResolver.java b/src/main/java/io/floci/aws/core/common/docker/CurrentContainerNetworkResolver.java index d8d8db7272..cbe4e029ea 100644 --- a/src/main/java/io/floci/aws/core/common/docker/CurrentContainerNetworkResolver.java +++ b/src/main/java/io/floci/aws/core/common/docker/CurrentContainerNetworkResolver.java @@ -15,6 +15,7 @@ import java.util.Map; import java.util.Optional; import java.util.OptionalInt; import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Predicate; /** * Resolves the Docker network used by the Floci container itself. @@ -154,13 +155,25 @@ public class CurrentContainerNetworkResolver { } } + // Docker lists a container's networks by name. One Floci made and joined, an EC2 VPC's or an EMR cluster's, is not + // where its containers belong: a Floci that crashed is still on it when it starts again, and what it launches would + // join that network, reaching what only its owner should. It is taken only when Floci is on no other. private Optional selectNetwork(Map networks) { + return selectNetwork(networks, networkName -> !isMadeByFloci(networkName)) + .or(() -> selectNetwork(networks, networkName -> true)); + } + + // The first usable network eligible says, a user-defined one before the others. + private Optional selectNetwork(Map networks, + Predicate eligible) { return networks.entrySet().stream() .filter(entry -> isUsable(entry.getValue())) .filter(entry -> isUserDefinedNetwork(entry.getKey())) + .filter(entry -> eligible.test(entry.getKey())) .findFirst() .or(() -> networks.entrySet().stream() .filter(entry -> isUsable(entry.getValue())) + .filter(entry -> eligible.test(entry.getKey())) .findFirst()) .map(entry -> new CurrentContainerNetwork(entry.getKey(), entry.getValue().getIpAddress())); } @@ -173,6 +186,21 @@ public class CurrentContainerNetworkResolver { return !"bridge".equals(networkName) && !"host".equals(networkName) && !"none".equals(networkName); } + // Whether Floci made the network, as its owner label says, or the label an EC2 VPC's had before it. One Docker + // cannot inspect is taken as Floci's, so it is not mistaken for the user's own. + private boolean isMadeByFloci(String networkName) { + try { + Map labels = dockerClient.inspectNetworkCmd().withNetworkId(networkName).exec().getLabels(); + return labels != null && (labels.containsKey(ContainerStorageHelper.OWNER_LABEL) + || ContainerStorageHelper.NETWORK_LABEL_ALIASES.legacyValue(labels, + ContainerStorageHelper.OWNER_LABEL) != null); + } catch (Exception e) { + LOG.warnv(e, "Could not inspect Docker network {0}, so it is not taken for Floci's own: {1}", networkName, + e.getMessage()); + return true; + } + } + String currentContainerId() { try { return Files.readString(Path.of(HOSTNAME_FILE)).trim(); diff --git a/src/main/java/io/floci/aws/services/emr/ClusterStorage.java b/src/main/java/io/floci/aws/services/emr/ClusterStorage.java index aa8977aaae..828b01e9c6 100644 --- a/src/main/java/io/floci/aws/services/emr/ClusterStorage.java +++ b/src/main/java/io/floci/aws/services/emr/ClusterStorage.java @@ -2,6 +2,7 @@ package io.floci.aws.services.emr; import io.floci.aws.services.emrserverless.SparkJobRunner; +import java.util.Map; import java.util.Set; import java.util.function.BooleanSupplier; @@ -20,14 +21,24 @@ public interface ClusterStorage { void create(String clusterId, String accountId, String region); /** - * Starts {@code clusterId}'s HDFS, a NameNode and a DataNode keeping their data in a volume of their own, in a - * container of {@code image} on a Docker network of the cluster's own, or on the host's when its steps run there, - * unless it is running, and returns the cluster's storage with it: its primary node's {@code host} name, which a - * step's container resolves to the address given, on the network given. A failure to start it is thrown, and - * {@link Stopped} once {@code stopped} says the step is past starting, or a teardown has stopped the HDFS. + * Starts {@code clusterId}'s HDFS, a NameNode and a DataNode keeping their data in a volume of their own, and, + * unless {@code hiveMetastore} is null, Hive's metastore service, in a container of {@code image} on a Docker + * network of the cluster's own, or on the host's when its steps run there, 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, and the metastore's URI, null in a namespace the steps share, where it + * does not run. 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, BooleanSupplier stopped); + String dockerNetwork, HiveMetastore hiveMetastore, BooleanSupplier stopped); + + /** + * Hive's metastore service on a cluster's primary node, which reaches S3 as the cluster's EC2 instance profile's + * {@code role} does, or as its account when that is null, with the cluster's {@code settings}, its + * {@code core-site} and {@code hive-site} properties, after its own. + */ + record HiveMetastore(String role, Map settings) { + } /** * Removes {@code clusterId}'s HDFS and the volumes of its storage once it no longer needs them: true when the diff --git a/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java b/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java index 1c953e2fe8..71ba72e4d2 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java +++ b/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java @@ -12,13 +12,18 @@ import io.floci.aws.core.common.docker.ContainerBuilder; import io.floci.aws.core.common.docker.ContainerExec; import io.floci.aws.core.common.docker.ContainerLifecycleManager; import io.floci.aws.core.common.docker.ContainerLiveness; -import io.floci.aws.core.common.docker.ContainerSpec; import io.floci.aws.core.common.docker.ContainerStorageHelper; +import io.floci.aws.core.common.docker.CurrentContainerNetworkResolver; +import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv; +import io.floci.aws.services.emrserverless.EmrServerlessSparkRunner; import io.floci.aws.services.emrserverless.SparkJobRunner; +import io.floci.aws.services.iam.model.SessionCreds; +import io.floci.aws.services.lambda.launcher.LambdaExecutionRoleCredentials; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.net.URI; import java.time.Duration; import java.util.LinkedHashMap; import java.util.List; @@ -39,7 +44,9 @@ import java.util.function.LongSupplier; * emr-7.14.0 on, "When you select Trino as the only application at launch, Amazon EMR no longer starts YARN and * HDFS", a cluster Floci does not run), is a NameNode and a DataNode in a container of their own, the cluster's * 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. + * step's, which fills it from the step's image. On a cluster with Hive 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. */ @ApplicationScoped public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { @@ -58,7 +65,19 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // starting a JVM of hdfs's own each time it is asked; each look is given five seconds, so one the NameNode does not // answer while it starts is asked again. private static final String NAMENODE_JMX = "http://127.0.0.1:9870/jmx?qry=Hadoop:service=NameNode,name="; - // How long a cluster's HDFS may take to start, its NameNode formatted the first time, before a step gives up. + // The metastore service's --hiveconf settings, Floci's S3 among them; set only on a cluster with Hive. + private static final String HIVE_METASTORE_VARIABLE = "FLOCI_HIVE_METASTORE"; + // The cluster's core-site and hive-site, as --hiveconf settings one to a line, which the service gets after its own. + private static final String HIVE_METASTORE_SITE_VARIABLE = "FLOCI_HIVE_METASTORE_SITE"; + private static final int HIVE_METASTORE_PORT = 9083; + // The folder a Hive session uploads Hive's exec jar to when it is not there, named after its SHA-256, under the + // image's hive.user.install.directory: the primary node puts it there first, as two sessions uploading it at once + // can leave one with a jar that changed under it, whose Tez tasks then fail to launch. + private static final String HIVE_JARS = "/tmp/hadoop/.hiveJars"; + // The name Floci's own container has on a cluster's network, which it joins for the metastore service to reach it. + private static final String FLOCI_ALIAS = "floci"; + // How long a cluster's HDFS and metastore may take to start, the NameNode formatted the first time, before a step + // gives up. private static final Duration HDFS_START_TIMEOUT = Duration.ofSeconds(120); private static final Duration HDFS_POLL_INTERVAL = Duration.ofMillis(500); // The primary node's HDFS, started as root: its daemons log their warnings and errors to the container's output, @@ -71,9 +90,14 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // 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, and HDFS_READY says it is ready. A - // daemon that exits, before or after, ends the container, its readiness gone, so the next step starts it again on - // its data. + // 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 image's Hadoop configuration, 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. 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. 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", @@ -114,6 +138,26 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { + " | grep -q \"\\\"Safemode\\\" : \\\"\\\"\"; do " + "[ \"$(jobs -rp | wc -l)\" = 2 ] || exit 1; sleep 0.2; done; " + "hdfs dfs -mkdir -p /tmp /user/hadoop || exit 1; " + + "if [ -n \"$" + HIVE_METASTORE_VARIABLE + "\" ]; then " + + "hdfs dfs -mkdir -p /user/hive/warehouse " + HIVE_JARS + " || exit 1; " + + "jar=$(ls /usr/lib/hive/lib/hive-exec-[0-9]*.jar | head -1); " + + "hdfs dfs -put -f \"$jar\" " + HIVE_JARS + + "/$(basename \"$jar\" .jar)-$(sha256sum \"$jar\" | cut -d\" \" -f1).jar || exit 1; " + + "[ -z \"$" + HIVE_METASTORE_SITE_VARIABLE + "\" ] || mapfile -t site <<< \"$" + + HIVE_METASTORE_SITE_VARIABLE + "\"; " + + "cd /tmp; LOGS_DIR=/tmp/floci-hive-logs HADOOP_CONF_DIR=/etc/hadoop/conf" + + " hive --service metastore -p " + HIVE_METASTORE_PORT + + " --hiveconf fs.defaultFS=hdfs://$FLOCI_HDFS_HOST:8020 $" + + HIVE_METASTORE_VARIABLE + + " --hiveconf \"javax.jdo.option.ConnectionURL=jdbc:derby:;" + + "databaseName=/mnt/var/lib/hive/metastore_db;create=true\"" + + " --hiveconf datanucleus.schema.autoCreateAll=true" + + " --hiveconf hive.metastore.schema.verification=false" + + " --hiveconf hive.metastore.warehouse.dir=hdfs://$FLOCI_HDFS_HOST:8020/user/hive/warehouse" + + " \"${site[@]}\" & " + + "until (exec 3<>/dev/tcp/127.0.0.1/" + HIVE_METASTORE_PORT + ") 2>/dev/null; do " + + "[ \"$(jobs -rp | wc -l)\" = 3 ] || exit 1; sleep 0.2; done; " + + "fi; " + "touch " + HDFS_READY + "; " + "wait -n; rm -f " + HDFS_READY + "; kill $(jobs -rp) 2>/dev/null; exit 1'"); @@ -121,10 +165,16 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { 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. private final Map starting = new ConcurrentHashMap<>(); + // The metastore services this process started, by container name: the session each reaches S3 with, if any, and + // the address of Floci's it was given. + private final Map sessions = new ConcurrentHashMap<>(); // The HDFS containers this process has started or found running, by name, which a reset or a shutdown removes. private final Set running = ConcurrentHashMap.newKeySet(); private final ContainerLifecycleManager lifecycleManager; private final ContainerBuilder containerBuilder; + private final LaunchedContainerAwsEnv awsEnv; + private final LambdaExecutionRoleCredentials roleCredentials; + private final CurrentContainerNetworkResolver currentContainer; private final EmulatorConfig config; private final Duration hdfsStartTimeout; private final LongSupplier nanoTime; @@ -133,14 +183,21 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { @Inject public EmrClusterStorage(ContainerLifecycleManager lifecycleManager, ContainerBuilder containerBuilder, - EmulatorConfig config) { - this(lifecycleManager, containerBuilder, config, HDFS_START_TIMEOUT, System::nanoTime); + LaunchedContainerAwsEnv awsEnv, LambdaExecutionRoleCredentials roleCredentials, + CurrentContainerNetworkResolver currentContainer, EmulatorConfig config) { + this(lifecycleManager, containerBuilder, awsEnv, roleCredentials, currentContainer, config, HDFS_START_TIMEOUT, + System::nanoTime); } EmrClusterStorage(ContainerLifecycleManager lifecycleManager, ContainerBuilder containerBuilder, - EmulatorConfig config, Duration hdfsStartTimeout, LongSupplier nanoTime) { + LaunchedContainerAwsEnv awsEnv, LambdaExecutionRoleCredentials roleCredentials, + CurrentContainerNetworkResolver currentContainer, EmulatorConfig config, + Duration hdfsStartTimeout, LongSupplier nanoTime) { this.lifecycleManager = lifecycleManager; this.containerBuilder = containerBuilder; + this.awsEnv = awsEnv; + this.roleCredentials = roleCredentials; + this.currentContainer = currentContainer; this.config = config; this.hdfsStartTimeout = hdfsStartTimeout; this.nanoTime = nanoTime; @@ -163,7 +220,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { @Override public SparkJobRunner.Storage hdfs(String clusterId, String accountId, String region, String host, String image, - String dockerNetwork, BooleanSupplier stopped) { + String dockerNetwork, HiveMetastore hiveMetastore, BooleanSupplier stopped) { String name = hdfsName(clusterId); String network = network(dockerNetwork); if (NO_NETWORK.equals(network)) { @@ -191,10 +248,12 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { + " runs"); } boolean found = liveness == ContainerLiveness.RUNNING && attempt == 0 - && inStepsNamespace(name, shared ? network : name); + && inStepsNamespace(name, shared ? network : name) + && (shared || hiveMetastore == null || metastoreCurrent(name)); // Known before it starts, so a teardown while it starts removes it. running.add(name); - String candidate = found ? name : start(clusterId, accountId, region, host, imageId, dockerNetwork); + String candidate = found ? name + : start(clusterId, accountId, region, host, imageId, dockerNetwork, hiveMetastore); if (awaitReady(clusterId, candidate, deadline, teardown, stopped)) { containerId = candidate; } else if (!found) { @@ -206,10 +265,22 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { if (shared) { return volumes(clusterId).withHdfs(host, LOOPBACK, null); } - return volumes(clusterId).withHdfs(host, address(clusterId, containerId), name); + SparkJobRunner.Storage storage = volumes(clusterId).withHdfs(host, address(clusterId, containerId), name); + return hiveMetastore != null + ? storage.withHiveMetastore("thrift://" + host + ":" + HIVE_METASTORE_PORT) : storage; } } + // Whether the metastore service of a primary node found running is one this process started, with a session it + // holds, which reaches Floci's S3 at the address it would be given now, Floci's container joining the network again + // if it has left. One an earlier process left has a session that process's end took away, and one started while + // Floci's container could not join the network has an address there that no join repairs: both start again, on + // the data their volume keeps. + private boolean metastoreCurrent(String name) { + MetastoreSession session = sessions.get(name); + return session != null && session.endpoint().equals(flociEndpointOn(name)); + } + // Where a step reaches the cluster's HDFS: its container's address on the cluster's own Docker network. private String address(String clusterId, String containerId) { String address = lifecycleManager.resolveContainerNetworkIp(containerId, hdfsName(clusterId)); @@ -256,14 +327,16 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { } // A cluster's HDFS container, started anew on the HDFS data its volume holds, which goes with the cluster's other - // two; one a restart, a stop or a daemon's exit left goes first. It runs on a Docker network of the cluster's own, - // which only the cluster's steps join, as its HDFS serves its files to any client that reaches it: the steps of - // other clusters, of other accounts too, do not. In a namespace the steps share it listens on the loopback alone. + // two, with its metastore service when asked; one a restart, a stop or a daemon's exit left goes first. It runs on + // a Docker network of the cluster's own, which only the cluster's steps join, as its HDFS and its metastore serve + // its files and tables to any client that reaches them: the steps of other clusters, of other accounts too, do + // not. In a namespace the steps share it listens on the loopback alone, and the metastore does not run, as Hive 3's + // has no setting for the address it listens on: it would serve every interface, the host's own for one. private String start(String clusterId, String accountId, String region, String host, String imageId, - String dockerNetwork) { + String dockerNetwork, HiveMetastore hiveMetastore) { String network = network(dockerNetwork); if (!sharesNamespace(network)) { - return createContainer(clusterId, accountId, region, host, imageId, network, false); + return createContainer(clusterId, accountId, region, host, imageId, network, false, hiveMetastore); } // One namespace holds one HDFS's ports, whose daemons would answer this one's readiness and its steps: the look // for another cluster's and this one's start go together, so two clusters' steps cannot both pass it. @@ -273,22 +346,23 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { throw new IllegalStateException("The HDFS of EMR cluster " + clusterId + " cannot start while that of" + " EMR cluster " + other + " runs in the network namespace they share"); } - return createContainer(clusterId, accountId, region, host, imageId, network, true); + return createContainer(clusterId, accountId, region, host, imageId, network, true, null); } } // Creates and starts the container start() decided on, in the namespace the steps share or on a network of its // cluster's own. private String createContainer(String clusterId, String accountId, String region, String host, String imageId, - String network, boolean shared) { + String network, boolean shared, HiveMetastore hiveMetastore) { String name = hdfsName(clusterId); // One left stopped goes first, and a removal Docker refuses fails the start as it is, not as a name clash. lifecycleManager.removeIfExistsStrict(name); + releaseSession(name); lifecycleManager.ensureVolume(name, labels(clusterId, accountId, region, COMPONENT)); if (!shared) { lifecycleManager.ensureNetwork(name, labels(clusterId, accountId, region, HDFS_COMPONENT)); } - ContainerSpec spec = containerBuilder.newContainer(imageId) + ContainerBuilder.Builder spec = containerBuilder.newContainer(imageId) .withName(name) .withUser("root") .withEntrypoint(List.of("/bin/bash", "-c", HDFS_SCRIPT)) @@ -299,13 +373,79 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { .withNamedVolume(name, "/mnt") .withDockerNetwork(Optional.of(shared ? network : name)) .withLogRotation() - .withLabels(labels(clusterId, accountId, region, HDFS_COMPONENT)) - .build(); - String containerId = lifecycleManager.createAndStart(spec).containerId(); + .withLabels(labels(clusterId, accountId, region, HDFS_COMPONENT)); + String containerId; + try { + if (hiveMetastore != null) { + String endpoint = flociEndpointOn(name); + Optional credentials = roleCredentials.forRole(hiveMetastore.role(), accountId, name); + sessions.put(name, new MetastoreSession(accountId, + credentials.map(SessionCreds::accessKeyId).orElse(null), endpoint)); + spec.withEnv(awsEnv.sdkBaselineEnv(region, Optional.empty(), endpoint, credentials, accountId)) + .withEnv(HIVE_METASTORE_VARIABLE, String.join(" ", + EmrServerlessSparkRunner.hiveMetastoreSettings(region, accountId, endpoint))) + .withEnv(HIVE_METASTORE_SITE_VARIABLE, String.join("\n", + EmrServerlessSparkRunner.hiveSettings(hiveMetastore.settings()))) + .withHostDockerInternalOnLinux() + .withJavaTrustStore(); + } + containerId = lifecycleManager.createAndStart(spec.build()).containerId(); + } catch (RuntimeException e) { + // A start that fails leaves no session, nor Floci's container on a network with no service to reach it. + releaseSession(name); + if (hiveMetastore != null) { + detachFloci(name); + } + throw e; + } LOG.infov("Started the HDFS of EMR cluster {0} as {1}", clusterId, host); return containerId; } + // Where the metastore service, on the cluster's network, which Docker keeps apart from Floci's, reaches Floci's + // S3: Floci on the host at the host's address, as the steps reach it; Floci in a container of its own as + // FLOCI_ALIAS, its container joining the cluster's network, as it joins the networks of EC2 VPCs. + private String flociEndpointOn(String network) { + String endpoint = awsEnv.flociEndpoint(false); + return attachFloci(network) ? "http://" + FLOCI_ALIAS + ":" + URI.create(endpoint).getPort() : endpoint; + } + + // Whether Floci's own container is on the network, joined to it unless it was; false when Floci runs on the host, + // or its container could not join, which leaves the metastore service its address on Floci's network. + private boolean attachFloci(String network) { + Optional floci = currentContainer.resolveContainerId(); + if (floci.isEmpty()) { + return false; + } + try { + lifecycleManager.ensureConnected(floci.get(), network, FLOCI_ALIAS); + return true; + } catch (RuntimeException e) { + LOG.warnv(e, "Could not connect Floci's container {0} to the Docker network {1}, so the Hive metastore" + + " on it may not reach Floci's S3: {2}", floci.get(), network, e.getMessage()); + return false; + } + } + + // Floci's container leaves a cluster's network, which it joined for the metastore service, so the network can go, + // and Floci's container, restarted, does not find itself on it. Whether it is off it. + private boolean detachFloci(String network) { + return currentContainer.resolveContainerId() + .map(floci -> lifecycleManager.disconnectFromNetwork(floci, network)) + .orElse(true); + } + + // The session the metastore service of the container named so reached S3 with goes with the container. + private void releaseSession(String name) { + MetastoreSession session = sessions.remove(name); + if (session != null && session.accessKeyId() != null) { + roleCredentials.unregister(session.accountId(), session.accessKeyId()); + } + } + + private record MetastoreSession(String accountId, String accessKeyId, String endpoint) { + } + // The cluster of another HDFS container of this deployment running in the namespace network gives, or null. private String otherRunningHdfs(String clusterId, String network) { for (Container container : lifecycleManager.getDockerClient().listContainersCmd() @@ -416,17 +556,22 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { } } - // Removes an HDFS container, forgetting it only once Docker says it is gone: one Docker keeps stays known, so the - // next reset or shutdown tries again. Whether it is gone. + // Removes an HDFS container, forgetting it only once Docker says it is gone and Floci's container has left its + // network: one Docker keeps, or keeps Floci's container on the network of, stays known, so the next reset or + // shutdown tries again. Its metastore's session goes with it. Whether both are done. private boolean removeKnown(String name) { try { lifecycleManager.removeIfExistsStrict(name); - running.remove(name); - return true; } catch (RuntimeException e) { LOG.warnv(e, "Could not remove the HDFS container {0}: {1}", name, e.getMessage()); return false; } + releaseSession(name); + if (!detachFloci(name)) { + return false; + } + running.remove(name); + return true; } @Override @@ -464,6 +609,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { .exec()) { Map labels = network.getLabels() != null ? network.getLabels() : Map.of(); if (!kept.contains(labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL))) { + detachFloci(network.getName()); lifecycleManager.removeNetwork(network.getName()); } } diff --git a/src/main/java/io/floci/aws/services/emr/EmrService.java b/src/main/java/io/floci/aws/services/emr/EmrService.java index 079a482d96..5f62c1c778 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrService.java @@ -1470,13 +1470,17 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear String image = cluster.getBootstrapImage() != null ? cluster.getBootstrapImage() : imageTemplate; Supplier releaseImage = cluster.getBootstrapImage() == null ? releaseImage(cluster) : null; // Every EMR cluster runs HDFS on its primary node, which the step's thread starts when it is not running: - // a NameNode and a DataNode, in a container of the release's Hive image, the one with HDFS's daemons. + // a NameNode and a DataNode, in a container of the release's Hive image, the one with HDFS's daemons, and + // on a cluster with Hive its metastore service. String clusterId = cluster.getId(); String hdfsHost = masterPrivateDnsName(cluster); String hdfsImage = hdfsImage(cluster.getReleaseLabel()); + ClusterStorage.HiveMetastore hiveMetastore = EmrSparkSteps.installsHive(cluster.getApplications(), + SNAPSHOT_MAPPER) ? new ClusterStorage.HiveMetastore(instanceProfileRole(cluster, accountId), + EmrSparkSteps.hiveMetastoreSettings(cluster.getConfigurations(), SNAPSHOT_MAPPER)) : null; Function hdfs = storage == null ? null : stopped -> clusterStorage.hdfs(clusterId, accountId, region, hdfsHost, hdfsImage, dockerNetwork, - stopped); + hiveMetastore, stopped); SparkJobRunner.Job job; if (hive != null) { job = new SparkJobRunner.Job(SERVICE, step.getId(), accountId, region, cluster.getReleaseLabel(), diff --git a/src/main/java/io/floci/aws/services/emr/EmrSparkSteps.java b/src/main/java/io/floci/aws/services/emr/EmrSparkSteps.java index 2d9ea67c77..4332a3e658 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrSparkSteps.java +++ b/src/main/java/io/floci/aws/services/emr/EmrSparkSteps.java @@ -75,7 +75,8 @@ final class EmrSparkSteps { // files, a later one winning: core-site, tez-site, which will "Change values in Tez's tez-site.xml file", and // hive-site, which will "Change values in Hive's hive-site.xml"; and hive-env's exports, which will "Change // values in the Hive environment". - private static final List HIVE_CLASSIFICATIONS = List.of(CORE_SITE, "tez-site", "hive-site"); + private static final String HIVE_SITE = "hive-site"; + private static final List HIVE_CLASSIFICATIONS = List.of(CORE_SITE, "tez-site", HIVE_SITE); private static final String HIVE_ENV = "hive-env"; // EMR's MapReduce jars are in /usr/lib/hadoop-mapreduce, as the image's own hadoop-streaming script has it, // which the image does not have; its streaming jar is in /usr/lib/hadoop. @@ -262,6 +263,16 @@ final class EmrSparkSteps { return properties(configurations, objectMapper, CORE_SITE); } + /** + * The properties of a cluster's {@code core-site}, then its {@code hive-site}, which configure its Hive metastore + * service as they do on EMR's primary node. + */ + static Map hiveMetastoreSettings(String configurations, ObjectMapper objectMapper) { + Map settings = new LinkedHashMap<>(properties(configurations, objectMapper, CORE_SITE)); + settings.putAll(properties(configurations, objectMapper, HIVE_SITE)); + return settings; + } + /** The properties of a cluster's {@code spark-log4j2}, which its steps' Spark gets in its log4j2.properties. */ static Map sparkLog4j2(String configurations, ObjectMapper objectMapper) { return properties(configurations, objectMapper, SPARK_LOG4J2); diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java index e2ce531d79..5221ee5985 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java @@ -238,11 +238,13 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo new SparkSetting("tez.local.mode", "true"), new SparkSetting("tez.am.client.am.port-range", "40000-40100")); // On a cluster, Hive's metastore is the cluster's own, as "Hive records metastore information in a MySQL database - // on the primary node's file system": an embedded Derby database in the cluster's /mnt, whose tables DataNucleus - // creates on first use. A cluster's hive-site replaces it, with the Glue Data Catalog's client factory for one. - private static final List HIVE_CLUSTER_SETTINGS = List.of( - new SparkSetting("hive.metastore.client.factory.class", - "org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClientFactory"), + // on the primary node's file system": the metastore service on its primary node (see EmrClusterStorage), in place + // of the Glue Data Catalog client the image's hive-site names, or, where that does not run, an embedded Derby + // database in the cluster's /mnt, whose tables DataNucleus creates on first use. A cluster's hive-site replaces + // them, with the Glue Data Catalog's client factory for one. + private static final SparkSetting HIVE_CLUSTER_CLIENT = new SparkSetting("hive.metastore.client.factory.class", + "org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClientFactory"); + private static final List HIVE_EMBEDDED_METASTORE = List.of( new SparkSetting("javax.jdo.option.ConnectionURL", "jdbc:derby:;databaseName=/mnt/var/lib/hive/metastore_db;create=true"), new SparkSetting("hive.metastore.schema.verification", "false"), @@ -743,7 +745,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo settings.addAll(HIVE_SETTINGS); if (job.storage() != null) { settings.addAll(hdfsSettings(job.storage())); - settings.addAll(HIVE_CLUSTER_SETTINGS); + settings.addAll(hiveClusterSettings(job.storage())); } List arguments = new ArrayList<>(); for (SparkSetting setting : settings) { @@ -910,16 +912,32 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo // Floci's Hadoop settings: S3A on Floci's S3, and the Glue Data Catalog client on Floci's Glue, in the job's // account. Given none, the client from emr-7.10.0 asks STS for it, through a client no setting points at Floci. private static List hadoopSettings(Job job, String flociEndpoint) { + return hadoopSettings(job.region(), job.accountId(), flociEndpoint); + } + + /** + * The {@code --hiveconf} settings a cluster's Hive metastore service gets, so that it reaches the S3 locations of + * tables as the cluster's steps do: Floci's S3 through S3A. + */ + public static List hiveMetastoreSettings(String region, String accountId, String flociEndpoint) { + List arguments = new ArrayList<>(); + for (SparkSetting setting : hadoopSettings(region, accountId, flociEndpoint)) { + addHiveSetting(arguments, setting.key(), setting.value()); + } + return arguments; + } + + private static List hadoopSettings(String region, String accountId, String flociEndpoint) { return List.of( new SparkSetting("fs.s3a.endpoint", flociEndpoint), - new SparkSetting("fs.s3a.endpoint.region", job.region()), + new SparkSetting("fs.s3a.endpoint.region", region), new SparkSetting("fs.s3a.path.style.access", "true"), new SparkSetting("fs.s3a.committer.magic.track.commits.in.memory.enabled", "true"), new SparkSetting("fs.s3.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem"), new SparkSetting("fs.AbstractFileSystem.s3.impl", "org.apache.hadoop.fs.s3a.S3A"), new SparkSetting("aws.glue.endpoint", flociEndpoint), - new SparkSetting("hive.metastore.glue.catalogid", job.accountId()), - new SparkSetting("aws.region", job.region())); + new SparkSetting("hive.metastore.glue.catalogid", accountId), + new SparkSetting("aws.region", region)); } // A cluster's HDFS, as Hadoop settings: its NameNode, on the cluster's primary node, which hdfs:// paths without a @@ -949,9 +967,22 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo return settings; } + // The cluster's metastore, for its Hive steps (see HIVE_CLUSTER_CLIENT). + private static List hiveClusterSettings(Storage storage) { + List settings = new ArrayList<>(List.of(HIVE_CLUSTER_CLIENT)); + if (storage.hiveMetastore() != null) { + settings.add(new SparkSetting("hive.metastore.uris", storage.hiveMetastore())); + } else { + settings.addAll(HIVE_EMBEDDED_METASTORE); + } + return settings; + } + // Floci's settings, then the job's spark-defaults, in the order a later one wins. Spark's own Hadoop configuration // takes HDFS's client back from the core-site.xml's view, for Spark and its Hive client, which writes a Hive table - // in HDFS only through it. + // in HDFS only through it. On a cluster with Hive, Spark's Hive client uses the cluster's metastore too, as the + // Glue Data Catalog is the one to pick "when you require a persistent Hive metastore or a Hive metastore shared by + // different clusters"; a spark-hive-site naming its client factory still wins. private static List sparkSettings(Job job, String flociEndpoint) { List hadoop = new ArrayList<>(hadoopSettings(job, flociEndpoint)); List hdfs = hdfsSettings(job.storage()); @@ -959,6 +990,9 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo if (!hdfs.isEmpty()) { hadoop.add(new SparkSetting("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem")); } + if (job.storage() != null && job.storage().hiveMetastore() != null) { + hadoop.add(new SparkSetting("hive.metastore.uris", job.storage().hiveMetastore())); + } List settings = new ArrayList<>(); hadoop.forEach(setting -> settings.add(new SparkSetting("spark.hadoop." + setting.key(), setting.value()))); if (job.storage() != null) { diff --git a/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java b/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java index 2cc923e976..abce5349b2 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java +++ b/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java @@ -108,12 +108,14 @@ public interface SparkJobRunner { /** * An EMR cluster's storage: the Docker volumes every one of its steps' containers mounts, {@code home} at - * {@code /home/hadoop} and {@code mnt} at {@code /mnt}; and its HDFS, whose NameNode is on the cluster's - * primary 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). + * {@code /home/hadoop} and {@code mnt} at {@code /mnt}; its HDFS, whose NameNode is on the cluster's primary + * 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, the URI of the Hive + * metastore service on that node, or null. */ - record Storage(String home, String mnt, String hdfsHost, String hdfsAddress, String hdfsNetwork) { + record Storage(String home, String mnt, String hdfsHost, String hdfsAddress, String hdfsNetwork, + String hiveMetastore) { /** * The component label of an EMR cluster's HDFS container, which carries its service's labels as a driver @@ -123,12 +125,17 @@ public interface SparkJobRunner { /** A cluster's volumes, before its HDFS runs. */ public Storage(String home, String mnt) { - this(home, mnt, null, null, null); + this(home, mnt, null, null, null, null); } /** 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); + return new Storage(home, mnt, host, address, network, hiveMetastore); + } + + /** This storage, its Hive metastore service at {@code uri}. */ + public Storage withHiveMetastore(String uri) { + return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, uri); } } diff --git a/src/test/java/io/floci/aws/core/common/dns/EmbeddedDnsServerAddressTest.java b/src/test/java/io/floci/aws/core/common/dns/EmbeddedDnsServerAddressTest.java new file mode 100644 index 0000000000..ec9d40e9e3 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/dns/EmbeddedDnsServerAddressTest.java @@ -0,0 +1,70 @@ +package io.floci.aws.core.common.dns; + +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.docker.ContainerDetector; +import io.floci.aws.core.common.docker.CurrentContainerNetworkResolver; +import io.vertx.core.AsyncResult; +import io.vertx.core.Future; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; +import io.vertx.core.datagram.DatagramSocket; +import jakarta.enterprise.inject.Instance; +import org.junit.jupiter.api.Test; + +import java.net.InetAddress; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** The address the embedded DNS server gives the containers Floci launches. */ +class EmbeddedDnsServerAddressTest { + + @Test + void ownAddressIsThisContainersOnTheNetworkItsContainersJoin() throws Exception { + CurrentContainerNetworkResolver currentContainer = mock(CurrentContainerNetworkResolver.class); + // Not the host's lookup, which takes the first of its networks by name, one Floci made after a crash. + when(currentContainer.resolveContainerIp()).thenReturn(Optional.of("172.19.0.2")); + + assertEquals("172.19.0.2", EmbeddedDnsServer.ownAddress(currentContainer)); + } + + @Test + void ownAddressIsTheHostsLookupWhenThatNetworkCannotBeTold() throws Exception { + CurrentContainerNetworkResolver currentContainer = mock(CurrentContainerNetworkResolver.class); + when(currentContainer.resolveContainerIp()).thenReturn(Optional.empty()); + + assertEquals(InetAddress.getLocalHost().getHostAddress(), EmbeddedDnsServer.ownAddress(currentContainer)); + } + + @Test + @SuppressWarnings("unchecked") + void inAContainerTheServerAnswersAtThatAddress() { + ContainerDetector containerDetector = mock(ContainerDetector.class); + when(containerDetector.isRunningInContainer()).thenReturn(true); + CurrentContainerNetworkResolver currentContainer = mock(CurrentContainerNetworkResolver.class); + when(currentContainer.resolveContainerIp()).thenReturn(Optional.of("172.19.0.2")); + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.hostname()).thenReturn(Optional.empty()); + when(config.dns().extraSuffixes()).thenReturn(Optional.empty()); + when(config.dns().containerFallbackServers()).thenReturn(List.of()); + when(config.dns().spoofAwsEndpoints()).thenReturn(false); + Vertx vertx = mock(Vertx.class); + DatagramSocket socket = mock(DatagramSocket.class); + when(vertx.createDatagramSocket(any())).thenReturn(socket); + when(socket.listen(eq(53), eq("0.0.0.0"), any())).thenAnswer(invocation -> { + invocation.>>getArgument(2).handle(Future.succeededFuture(socket)); + return socket; + }); + + EmbeddedDnsServer server = new EmbeddedDnsServer(config, containerDetector, vertx, mock(Instance.class), + mock(Instance.class), mock(Instance.class), currentContainer); + + assertEquals(Optional.of("172.19.0.2"), server.getServerIp()); + } +} diff --git a/src/test/java/io/floci/aws/core/common/docker/ContainerLifecycleManagerNetworkTest.java b/src/test/java/io/floci/aws/core/common/docker/ContainerLifecycleManagerNetworkTest.java index f4f47bf27d..9c3b9c06af 100644 --- a/src/test/java/io/floci/aws/core/common/docker/ContainerLifecycleManagerNetworkTest.java +++ b/src/test/java/io/floci/aws/core/common/docker/ContainerLifecycleManagerNetworkTest.java @@ -460,6 +460,43 @@ class ContainerLifecycleManagerNetworkTest { verify(connectCmd).exec(); } + @Test + void ensureConnectedJoinsARunningContainerToTheNetworkUnderItsAliasOnlyWhenItIsNotOnIt() { + NetworkSettings networks = mock(NetworkSettings.class); + when(inspectOf("floci").getNetworkSettings()).thenReturn(networks); + when(networks.getNetworks()).thenReturn(Map.of("floci_default", new ContainerNetwork()), + Map.of("floci_default", new ContainerNetwork(), "emr-j-1-hdfs", new ContainerNetwork())); + + manager().ensureConnected("floci", "emr-j-1-hdfs", "floci"); + manager().ensureConnected("floci", "emr-j-1-hdfs", "floci"); + + verify(connectCmd).withContainerId("floci"); + verify(connectCmd).withNetworkId("emr-j-1-hdfs"); + ArgumentCaptor endpoint = ArgumentCaptor.forClass(ContainerNetwork.class); + verify(connectCmd).withContainerNetwork(endpoint.capture()); + assertEquals(List.of("floci"), endpoint.getValue().getAliases()); + // Docker refuses to join a container to a network it is on. + verify(connectCmd, times(1)).exec(); + } + + @Test + void disconnectFromNetworkLeavesOnlyANetworkTheContainerIsOnAndSaysWhetherItLeft() { + NetworkSettings networks = mock(NetworkSettings.class); + when(inspectOf("floci").getNetworkSettings()).thenReturn(networks); + when(networks.getNetworks()).thenReturn(Map.of("emr-j-1-hdfs", new ContainerNetwork())); + + assertTrue(manager().disconnectFromNetwork("floci", "emr-j-1-hdfs")); + assertTrue(manager().disconnectFromNetwork("floci", "emr-j-2-hdfs")); + + verify(disconnectCmd).withContainerId("floci"); + verify(disconnectCmd).withNetworkId("emr-j-1-hdfs"); + verify(disconnectCmd).withForce(true); + verify(disconnectCmd, times(1)).exec(); + // One Docker keeps it on is not left. + doThrow(new ConflictException("the daemon is busy")).when(disconnectCmd).exec(); + assertFalse(manager().disconnectFromNetwork("floci", "emr-j-1-hdfs")); + } + @Test void removeNetworkSaysWhetherTheNetworkIsGone() { when(dockerClient.removeNetworkCmd("removed")).thenReturn(mock(RemoveNetworkCmd.class)); diff --git a/src/test/java/io/floci/aws/core/common/docker/CurrentContainerNetworkResolverTest.java b/src/test/java/io/floci/aws/core/common/docker/CurrentContainerNetworkResolverTest.java index 744edb792f..6b22b29e25 100644 --- a/src/test/java/io/floci/aws/core/common/docker/CurrentContainerNetworkResolverTest.java +++ b/src/test/java/io/floci/aws/core/common/docker/CurrentContainerNetworkResolverTest.java @@ -3,8 +3,10 @@ package io.floci.aws.core.common.docker; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.InspectContainerCmd; import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.command.InspectNetworkCmd; import com.github.dockerjava.api.model.ContainerNetwork; import com.github.dockerjava.api.model.ExposedPort; +import com.github.dockerjava.api.model.Network; import com.github.dockerjava.api.model.Ports; import org.junit.jupiter.api.Test; @@ -12,9 +14,12 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import java.util.OptionalInt; +import java.util.Set; +import java.util.function.Function; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -45,6 +50,70 @@ class CurrentContainerNetworkResolverTest { assertEquals(Optional.of("172.24.0.2"), resolver.resolveContainerIp()); } + @Test + void resolveNetworkName_skipsANetworkFlociMadeWhichItIsStillOnAfterACrash() { + // Docker lists a container's networks by name, so the cluster's comes first. + CurrentContainerNetworkResolver resolver = resolverOn(networks( + "floci-aws-emr-j-1-hdfs", "172.20.0.2", + "floci_default", "172.19.0.2"), "floci-aws-emr-j-1-hdfs"); + + assertEquals(Optional.of("floci_default"), resolver.resolveNetworkName()); + assertEquals(Optional.of("172.19.0.2"), resolver.resolveContainerIp()); + } + + @Test + void resolveNetworkName_prefersTheDefaultBridgeToANetworkFlociMade() { + CurrentContainerNetworkResolver resolver = resolverOn(networks( + "floci-aws-emr-j-1-hdfs", "172.20.0.2", + "bridge", "172.17.0.2"), "floci-aws-emr-j-1-hdfs"); + + assertEquals(Optional.of("bridge"), resolver.resolveNetworkName()); + } + + @Test + void resolveNetworkName_takesANetworkFlociMadeWhenItIsOnNoOther() { + CurrentContainerNetworkResolver resolver = resolverOn(networks( + "floci-aws-emr-j-1-hdfs", "172.20.0.2", + "floci-aws-emr-j-2-hdfs", "172.21.0.2"), "floci-aws-emr-j-1-hdfs", "floci-aws-emr-j-2-hdfs"); + + assertEquals(Optional.of("floci-aws-emr-j-1-hdfs"), resolver.resolveNetworkName()); + } + + @Test + void resolveNetworkName_prefersTheUsersNetworkToOneDockerCannotInspect() { + CurrentContainerNetworkResolver resolver = resolverOn(networks( + "first", "172.20.0.2", + "floci_default", "172.19.0.2"), name -> { + if ("first".equals(name)) { + throw new IllegalStateException("The daemon is busy"); + } + return Map.of(); + }); + + assertEquals(Optional.of("floci_default"), resolver.resolveNetworkName()); + } + + @Test + void resolveNetworkName_takesTheFirstUserDefinedNetworkWhenDockerCannotInspectAny() { + CurrentContainerNetworkResolver resolver = resolverOn(networks( + "bridge", "172.17.0.2", + "first", "172.20.0.2"), name -> { + throw new IllegalStateException("The daemon is busy"); + }); + + assertEquals(Optional.of("first"), resolver.resolveNetworkName()); + } + + @Test + void resolveNetworkName_skipsAVpcNetworkWithOnlyItsEarlierOwnerLabel() { + CurrentContainerNetworkResolver resolver = resolverOn(networks( + "floci-vpc-1", "172.20.0.2", + "floci_default", "172.19.0.2"), name -> "floci-vpc-1".equals(name) + ? Map.of("floci_vpc_owner_port", "4566") : Map.of()); + + assertEquals(Optional.of("floci_default"), resolver.resolveNetworkName()); + } + @Test void resolveNetworkName_returnsEmptyOutsideContainer() { DockerClient dockerClient = mock(DockerClient.class); @@ -151,6 +220,44 @@ class CurrentContainerNetworkResolverTest { return inspectCmd; } + // A resolver in a container on networks, of which Floci made those named. + private static CurrentContainerNetworkResolver resolverOn(Map networks, + String... madeByFloci) { + Set made = Set.of(madeByFloci); + return resolverOn(networks, name -> made.contains(name) + ? Map.of(ContainerStorageHelper.OWNER_LABEL, "default/4566") : Map.of()); + } + + // A resolver in a container on networks, each of which Docker inspects with the labels given, or fails to. + private static CurrentContainerNetworkResolver resolverOn(Map networks, + Function> labels) { + DockerClient dockerClient = mock(DockerClient.class); + ContainerDetector containerDetector = mock(ContainerDetector.class); + when(containerDetector.isRunningInContainer()).thenReturn(true); + InspectContainerCmd inspectCmd = mock(InspectContainerCmd.class); + InspectContainerResponse inspect = mock(InspectContainerResponse.class, RETURNS_DEEP_STUBS); + when(dockerClient.inspectContainerCmd("floci-container")).thenReturn(inspectCmd); + when(inspectCmd.exec()).thenReturn(inspect); + when(inspect.getNetworkSettings().getNetworks()).thenReturn(networks); + when(dockerClient.inspectNetworkCmd()).thenAnswer(invocation -> { + InspectNetworkCmd cmd = mock(InspectNetworkCmd.class); + when(cmd.withNetworkId(anyString())).thenAnswer(id -> { + String name = id.getArgument(0); + InspectNetworkCmd named = mock(InspectNetworkCmd.class); + when(named.exec()).thenAnswer(exec -> { + // Read first: one that throws inside the stubbing below would leave Mockito half way through it. + Map found = labels.apply(name); + Network network = mock(Network.class); + when(network.getLabels()).thenReturn(found); + return network; + }); + return named; + }); + return cmd; + }); + return new TestResolver(dockerClient, containerDetector, "floci-container"); + } + private static Map networks(String firstName, String firstIp, String secondName, String secondIp) { Map networks = new LinkedHashMap<>(); diff --git a/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java b/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java index 2e97192623..7c3f8dba3d 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java @@ -24,13 +24,18 @@ import io.floci.aws.core.common.docker.ContainerLifecycleManager; import io.floci.aws.core.common.docker.ContainerLiveness; import io.floci.aws.core.common.docker.ContainerSpec; import io.floci.aws.core.common.docker.ContainerStorageHelper; +import io.floci.aws.core.common.docker.CurrentContainerNetworkResolver; +import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv; import io.floci.aws.services.emrserverless.SparkJobRunner; +import io.floci.aws.services.iam.model.SessionCreds; import io.floci.aws.services.lambda.launcher.ImageCacheService; +import io.floci.aws.services.lambda.launcher.LambdaExecutionRoleCredentials; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InOrder; import java.time.Duration; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -74,13 +79,20 @@ 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; + // 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()); private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); private final DockerClient docker = mock(DockerClient.class); private final ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); private final ContainerBuilder containerBuilder = mock(ContainerBuilder.class); private final ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF); - private final EmrClusterStorage storage = new EmrClusterStorage(lifecycle, containerBuilder, config); + private final LaunchedContainerAwsEnv awsEnv = mock(LaunchedContainerAwsEnv.class); + private final LambdaExecutionRoleCredentials roleCredentials = mock(LambdaExecutionRoleCredentials.class); + private final CurrentContainerNetworkResolver currentContainer = mock(CurrentContainerNetworkResolver.class); + private final EmrClusterStorage storage = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv, + roleCredentials, currentContainer, config); private final String hdfsName = ContainerStorageHelper.dockerName(config, "emr-j-1-hdfs"); @BeforeEach @@ -109,10 +121,10 @@ class EmrClusterStorageTest { List> looks = ContainerExecStubs.completeEveryExec(docker, "c-1", List.of(1L, 0L), "", ""); SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, - "floci-network", NOT_STOPPED); + "floci-network", null, NOT_STOPPED); SparkJobRunner.Storage volumes = storage.volumes("j-1"); - assertEquals(new SparkJobRunner.Storage(volumes.home(), volumes.mnt(), HOST, "172.18.0.5", hdfsName), started); + assertEquals(volumes.withHdfs(HOST, "172.18.0.5", hdfsName), started); verify(spec).withName(hdfsName); verify(spec).withUser("root"); verify(spec).withEnv("FLOCI_HDFS_HOST", HOST); @@ -167,9 +179,13 @@ class EmrClusterStorageTest { "until curl -sf -m 5 \"http://127.0.0.1:9870/jmx?qry=Hadoop:service=NameNode,name=NameNodeInfo\"", "| grep -q \"\\\"Safemode\\\" : \\\"\\\"\"; do", "[ \"$(jobs -rp | wc -l)\" = 2 ] || exit 1; sleep 0.2; done;", - "hdfs dfs -mkdir -p /tmp /user/hadoop || exit 1;", - "touch /tmp/floci-hdfs-ready;", + "hdfs dfs -mkdir -p /tmp /user/hadoop || exit 1;")) + && entrypoint.get(2).contains(String.join(" ", "fi;", "touch /tmp/floci-hdfs-ready;", "wait -n; rm -f /tmp/floci-hdfs-ready; kill $(jobs -rp) 2>/dev/null; exit 1'")))); + // A cluster without Hive runs no metastore service, and its primary node does not talk to Floci. + verify(spec, never()).withEnv(eq("FLOCI_HIVE_METASTORE"), anyString()); + verify(spec, never()).withJavaTrustStore(); + assertNull(started.hiveMetastore()); // One left stopped by a restart goes first. InOrder order = inOrder(lifecycle); order.verify(lifecycle).removeIfExistsStrict(hdfsName); @@ -186,7 +202,7 @@ class EmrClusterStorageTest { ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", ""); SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, - "host", NOT_STOPPED); + "host", null, NOT_STOPPED); assertEquals("127.0.0.1", started.hdfsAddress()); // Steps share the host's network with it, so they join no other. @@ -202,7 +218,7 @@ class EmrClusterStorageTest { when(lifecycle.probeContainer("c-1")).thenReturn(ContainerLiveness.RUNNING); ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", ""); - storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", NOT_STOPPED); + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", null, NOT_STOPPED); // The host's other interfaces would otherwise serve its files, without permissions, to anyone reaching them. verify(spec).withEnv("FLOCI_HDFS_BIND", "127.0.0.1"); @@ -218,7 +234,7 @@ class EmrClusterStorageTest { when(lifecycle.probeContainer("c-2")).thenReturn(ContainerLiveness.RUNNING); ContainerExecStubs.completeEveryExec(docker, "c-2", 0L, "", ""); - SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, null, + SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, null, null, NOT_STOPPED); // Docker joins a container placed in another's namespace to no other network, so its steps reach it there. @@ -229,6 +245,357 @@ class EmrClusterStorageTest { verify(lifecycle, never()).ensureNetwork(anyString(), any()); } + @Test + void aClusterWithHivesPrimaryNodeRunsItsMetastoreServiceToo() { + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-6", Map.of())); + when(lifecycle.probeContainer("c-6")).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.resolveContainerNetworkIp("c-6", hdfsName)).thenReturn("172.18.0.7"); + ContainerExecStubs.completeEveryExec(docker, "c-6", 0L, "", ""); + // A session for the cluster's instance profile's role, as its steps' S3 would have. + Optional session = Optional.of(new SessionCreds("ASIAMETASTORE", "secret", "token")); + when(roleCredentials.forRole("arn:aws:iam::123456789012:role/EMR_EC2_DefaultRole", "123456789012", + hdfsName)).thenReturn(session); + // Floci on the host, reached at the host's address. + when(awsEnv.flociEndpoint(false)).thenReturn("http://host.docker.internal:4566"); + when(awsEnv.sdkBaselineEnv("us-east-1", Optional.empty(), "http://host.docker.internal:4566", session, + "123456789012")).thenReturn(List.of("AWS_ACCESS_KEY_ID=ASIAMETASTORE")); + + SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, + "floci-network", + new ClusterStorage.HiveMetastore("arn:aws:iam::123456789012:role/EMR_EC2_DefaultRole", Map.of()), + NOT_STOPPED); + + assertEquals("thrift://ip-10-0-0-1.ec2.internal:9083", started.hiveMetastore()); + verify(spec).withEnv(List.of("AWS_ACCESS_KEY_ID=ASIAMETASTORE")); + verify(spec).withHostDockerInternalOnLinux(); + verify(spec).withJavaTrustStore(); + // Floci's resolver would answer with an address on Floci's network, which the cluster's does not reach. + verify(spec, never()).withEmbeddedDns(); + verify(lifecycle, never()).ensureConnected(anyString(), anyString(), anyString()); + // Floci's S3 through S3A, as for the cluster's steps. + verify(spec).withEnv(eq("FLOCI_HIVE_METASTORE"), argThat(settings -> settings.startsWith( + "--hiveconf fs.s3a.endpoint=http://host.docker.internal:4566" + + " --hiveconf fs.s3a.endpoint.region=us-east-1 ") + && settings.contains(" --hiveconf fs.s3.impl=org.apache.hadoop.fs.s3a.S3AFileSystem "))); + // Hive's exec jar where a Hive session would upload it, so two at once do not race to. + verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains( + "hdfs dfs -mkdir -p /user/hive/warehouse /tmp/hadoop/.hiveJars || exit 1; " + + "jar=$(ls /usr/lib/hive/lib/hive-exec-[0-9]*.jar | head -1); hdfs dfs -put -f \"$jar\" " + + "/tmp/hadoop/.hiveJars/$(basename \"$jar\" .jar)" + + "-$(sha256sum \"$jar\" | cut -d\" \" -f1).jar"))); + // With the image's Hadoop configuration, as Hive steps run; in a folder Derby can write its log in; its + // database on the primary node's own volume, its warehouse in the HDFS, ready only once it listens, and the + // node gone if it exits while starting. + verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains( + "cd /tmp; LOGS_DIR=/tmp/floci-hive-logs HADOOP_CONF_DIR=/etc/hadoop/conf" + + " hive --service metastore -p 9083" + + " --hiveconf fs.defaultFS=hdfs://$FLOCI_HDFS_HOST:8020 $FLOCI_HIVE_METASTORE" + + " --hiveconf \"javax.jdo.option.ConnectionURL=jdbc:derby:;" + + "databaseName=/mnt/var/lib/hive/metastore_db;create=true\"") + && entrypoint.get(2).contains( + "hive.metastore.warehouse.dir=hdfs://$FLOCI_HDFS_HOST:8020/user/hive/warehouse" + + " \"${site[@]}\" &") + && entrypoint.get(2).contains("until (exec 3<>/dev/tcp/127.0.0.1/9083) 2>/dev/null; do " + + "[ \"$(jobs -rp | wc -l)\" = 3 ] || exit 1; sleep 0.2; done; " + + "fi; touch /tmp/floci-hdfs-ready"))); + + // The session goes with the container. + storage.remove("j-1"); + verify(roleCredentials).unregister("123456789012", "ASIAMETASTORE"); + } + + @Test + void aMetastoresSessionGoesWithItsContainerOnAResetOrAShutdownAndWhenItCannotStart() { + ClusterStorage.HiveMetastore metastore = METASTORE; + when(roleCredentials.forRole("arn:aws:iam::123456789012:role/r", "123456789012", hdfsName)) + .thenReturn(Optional.of(new SessionCreds("ASIAONE", "s", "t")), Optional.of(new SessionCreds("ASIATWO", + "s", "t"))); + when(awsEnv.flociEndpoint(false)).thenReturn("http://host.docker.internal:4566"); + when(awsEnv.sdkBaselineEnv(anyString(), any(), anyString(), any(), anyString())).thenReturn(List.of()); + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-8", Map.of())) + .thenThrow(new IllegalStateException("Could not start the container")); + when(lifecycle.probeContainer("c-8")).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.resolveContainerNetworkIp("c-8", hdfsName)).thenReturn("172.18.0.10"); + ContainerExecStubs.completeEveryExec(docker, "c-8", 0L, "", ""); + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", metastore, NOT_STOPPED); + + storage.stopManagedContainers(); + verify(roleCredentials).unregister("123456789012", "ASIAONE"); + assertThrows(IllegalStateException.class, () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, + "floci-network", metastore, NOT_STOPPED)); + + verify(roleCredentials).unregister("123456789012", "ASIATWO"); + } + + @Test + void aMetastoreStartedAgainAfterItsContainerStoppedReleasesTheSessionOfTheOneBefore() { + ClusterStorage.HiveMetastore metastore = METASTORE; + when(roleCredentials.forRole("arn:aws:iam::123456789012:role/r", "123456789012", hdfsName)) + .thenReturn(Optional.of(new SessionCreds("ASIAONE", "s", "t")), + Optional.of(new SessionCreds("ASIATWO", "s", "t"))); + when(awsEnv.flociEndpoint(false)).thenReturn("http://host.docker.internal:4566"); + when(awsEnv.sdkBaselineEnv(anyString(), any(), anyString(), any(), anyString())).thenReturn(List.of()); + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-8", Map.of()), + new ContainerLifecycleManager.ContainerInfo("c-9", Map.of())); + when(lifecycle.probeContainer("c-8")).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.probeContainer("c-9")).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.resolveContainerNetworkIp("c-8", hdfsName)).thenReturn("172.18.0.10"); + when(lifecycle.resolveContainerNetworkIp("c-9", hdfsName)).thenReturn("172.18.0.11"); + ContainerExecStubs.completeEveryExec(docker, "c-8", 0L, "", ""); + ContainerExecStubs.completeEveryExec(docker, "c-9", 0L, "", ""); + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", metastore, NOT_STOPPED); + + // Its metastore exited, which ended the container; the cluster's next step starts it again. + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", metastore, NOT_STOPPED); + + verify(roleCredentials).unregister("123456789012", "ASIAONE"); + verify(roleCredentials, never()).unregister("123456789012", "ASIATWO"); + } + + @Test + void aMetastoresSessionStaysWhileDockerKeepsItsContainer() { + ClusterStorage.HiveMetastore metastore = METASTORE; + when(roleCredentials.forRole("arn:aws:iam::123456789012:role/r", "123456789012", hdfsName)) + .thenReturn(Optional.of(new SessionCreds("ASIAONE", "s", "t"))); + when(awsEnv.flociEndpoint(false)).thenReturn("http://host.docker.internal:4566"); + when(awsEnv.sdkBaselineEnv(anyString(), any(), anyString(), any(), anyString())).thenReturn(List.of()); + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-8", Map.of())); + when(lifecycle.probeContainer("c-8")).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.resolveContainerNetworkIp("c-8", hdfsName)).thenReturn("172.18.0.10"); + ContainerExecStubs.completeEveryExec(docker, "c-8", 0L, "", ""); + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", metastore, NOT_STOPPED); + doThrow(new IllegalStateException("Failed to remove container " + hdfsName)).doNothing() + .when(lifecycle).removeIfExistsStrict(hdfsName); + + storage.stopManagedContainers(); + // Its metastore may still reach S3 with it. + verify(roleCredentials, never()).unregister(anyString(), anyString()); + storage.stopManagedContainers(); + + verify(roleCredentials).unregister("123456789012", "ASIAONE"); + } + + @Test + void inANamespaceTheStepsShareTheMetastoreServiceDoesNotRunAsItWouldServeEveryInterface() { + when(containerBuilder.resolveDockerNetwork(Optional.of("host"))).thenReturn(Optional.of("host")); + 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); + ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", ""); + + SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", + METASTORE, NOT_STOPPED); + + // Hive steps keep a metastore of their own. + assertNull(started.hiveMetastore()); + verify(spec, never()).withEnv(eq("FLOCI_HIVE_METASTORE"), anyString()); + verify(roleCredentials, never()).forRole(anyString(), anyString(), anyString()); + } + + @Test + void withFlociInAContainerItsContainerJoinsTheClustersNetworkForTheMetastoreToReachItsS3() { + when(currentContainer.resolveContainerId()).thenReturn(Optional.of("floci-container")); + when(awsEnv.flociEndpoint(false)).thenReturn("http://172.20.0.2:4566"); + when(awsEnv.sdkBaselineEnv(anyString(), any(), anyString(), any(), anyString())).thenReturn(List.of()); + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-6", Map.of())); + when(lifecycle.probeContainer("c-6")).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.resolveContainerNetworkIp("c-6", hdfsName)).thenReturn("172.18.0.7"); + ContainerExecStubs.completeEveryExec(docker, "c-6", 0L, "", ""); + + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", + METASTORE, NOT_STOPPED); + + // Docker keeps the cluster's network apart from Floci's, where Floci's address is. + InOrder start = inOrder(lifecycle); + start.verify(lifecycle).ensureNetwork(eq(hdfsName), any()); + start.verify(lifecycle).ensureConnected("floci-container", hdfsName, "floci"); + start.verify(lifecycle).createAndStart(any()); + verify(awsEnv).sdkBaselineEnv(anyString(), any(), eq("http://floci:4566"), any(), anyString()); + verify(spec).withEnv(eq("FLOCI_HIVE_METASTORE"), argThat(settings -> settings.startsWith( + "--hiveconf fs.s3a.endpoint=http://floci:4566 "))); + + // It leaves the network with the container, so the network can go. + when(lifecycle.removeNetwork(hdfsName)).thenReturn(true); + storage.remove("j-1"); + InOrder removal = inOrder(lifecycle); + removal.verify(lifecycle).removeIfExistsStrict(hdfsName); + removal.verify(lifecycle).disconnectFromNetwork("floci-container", hdfsName); + removal.verify(lifecycle).removeNetwork(hdfsName); + } + + @Test + void aFlociContainerThatCannotJoinTheClustersNetworkLeavesTheMetastoreFlocisOwnAddress() { + when(currentContainer.resolveContainerId()).thenReturn(Optional.of("floci-container")); + doThrow(new DockerException("No such container: floci-container", 404)) + .when(lifecycle).ensureConnected("floci-container", hdfsName, "floci"); + when(awsEnv.flociEndpoint(false)).thenReturn("http://192.168.1.5:4566"); + when(awsEnv.sdkBaselineEnv(anyString(), any(), anyString(), any(), anyString())).thenReturn(List.of()); + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-6", Map.of())); + when(lifecycle.probeContainer("c-6")).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.resolveContainerNetworkIp("c-6", hdfsName)).thenReturn("172.18.0.7"); + ContainerExecStubs.completeEveryExec(docker, "c-6", 0L, "", ""); + + SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, + "floci-network", METASTORE, NOT_STOPPED); + + // The HDFS still starts, as do its steps' tables there. + assertEquals("172.18.0.7", started.hdfsAddress()); + verify(spec).withEnv(eq("FLOCI_HIVE_METASTORE"), argThat(settings -> settings.startsWith( + "--hiveconf fs.s3a.endpoint=http://192.168.1.5:4566 "))); + } + + @Test + void aMetastoreThisFlociStartedIsUsedAsItIsHavingFlocisContainerJoinItsNetworkAgain() { + when(currentContainer.resolveContainerId()).thenReturn(Optional.of("floci-container")); + when(awsEnv.flociEndpoint(false)).thenReturn("http://172.20.0.2:4566"); + when(awsEnv.sdkBaselineEnv(anyString(), any(), anyString(), any(), anyString())).thenReturn(List.of()); + // Started by this process, then found running by the cluster's next step. + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING, ContainerLiveness.RUNNING); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-6", Map.of())); + when(lifecycle.probeContainer("c-6")).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.resolveContainerNetworkIp(anyString(), eq(hdfsName))).thenReturn("172.18.0.7"); + runningOn(hdfsName, hdfsName); + ContainerExecStubs.completeEveryExec(docker, "c-6", 0L, "", ""); + ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", ""); + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", METASTORE, NOT_STOPPED); + + SparkJobRunner.Storage found = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, + "floci-network", METASTORE, NOT_STOPPED); + + assertEquals("thrift://ip-10-0-0-1.ec2.internal:9083", found.hiveMetastore()); + verify(lifecycle, times(1)).createAndStart(any()); + // In case Floci's container has left the network since. + verify(lifecycle, times(2)).ensureConnected("floci-container", hdfsName, "floci"); + } + + @Test + void aMetastoreAnEarlierFlociLeftRunningStartsAgainWithASessionOfThisOnes() { + // Its session went with the process that started it. + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING); + runningOn(hdfsName, hdfsName); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-9", Map.of())); + when(lifecycle.probeContainer("c-9")).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.resolveContainerNetworkIp("c-9", hdfsName)).thenReturn("172.18.0.9"); + ContainerExecStubs.completeEveryExec(docker, "c-9", 0L, "", ""); + Optional session = Optional.of(new SessionCreds("ASIANEW", "s", "t")); + when(roleCredentials.forRole("arn:aws:iam::123456789012:role/r", "123456789012", hdfsName)).thenReturn(session); + when(awsEnv.flociEndpoint(false)).thenReturn("http://host.docker.internal:4566"); + when(awsEnv.sdkBaselineEnv("us-east-1", Optional.empty(), "http://host.docker.internal:4566", session, + "123456789012")).thenReturn(List.of("AWS_ACCESS_KEY_ID=ASIANEW")); + + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", METASTORE, NOT_STOPPED); + + InOrder order = inOrder(lifecycle); + order.verify(lifecycle).removeIfExistsStrict(hdfsName); + order.verify(lifecycle).createAndStart(any()); + verify(spec).withEnv(List.of("AWS_ACCESS_KEY_ID=ASIANEW")); + // On the data its volume keeps. + verify(lifecycle, never()).removeVolume(anyString()); + } + + @Test + void aMetastoreStartedWhileFlocisContainerCouldNotJoinItsNetworkStartsAgainOnceItCan() { + when(currentContainer.resolveContainerId()).thenReturn(Optional.of("floci-container")); + doThrow(new DockerException("The daemon is busy", 500)).doNothing() + .when(lifecycle).ensureConnected("floci-container", hdfsName, "floci"); + when(awsEnv.flociEndpoint(false)).thenReturn("http://172.20.0.2:4566"); + when(awsEnv.sdkBaselineEnv(anyString(), any(), anyString(), any(), anyString())).thenReturn(List.of()); + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING, ContainerLiveness.RUNNING); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-6", Map.of()), + new ContainerLifecycleManager.ContainerInfo("c-7", Map.of())); + when(lifecycle.probeContainer("c-6")).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.probeContainer("c-7")).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.resolveContainerNetworkIp(anyString(), eq(hdfsName))).thenReturn("172.18.0.7"); + runningOn(hdfsName, hdfsName); + ContainerExecStubs.completeEveryExec(docker, "c-6", 0L, "", ""); + ContainerExecStubs.completeEveryExec(docker, "c-7", 0L, "", ""); + // Given Floci's address on Floci's network, which the cluster's does not reach. + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", METASTORE, NOT_STOPPED); + + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", METASTORE, NOT_STOPPED); + + // A join cannot change the address it was given, so it starts again with Floci's on its network. + verify(lifecycle, times(2)).createAndStart(any()); + // It had no session to give back: the role has none here. + verify(roleCredentials, never()).unregister(any(), any()); + verify(spec).withEnv(eq("FLOCI_HIVE_METASTORE"), argThat(settings -> settings.startsWith( + "--hiveconf fs.s3a.endpoint=http://floci:4566 "))); + } + + @Test + void aMetastoreThatFailsToStartHasFlocisContainerLeaveItsNetwork() { + when(currentContainer.resolveContainerId()).thenReturn(Optional.of("floci-container")); + when(awsEnv.flociEndpoint(false)).thenReturn("http://172.20.0.2:4566"); + when(awsEnv.sdkBaselineEnv(anyString(), any(), anyString(), any(), anyString())).thenReturn(List.of()); + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING); + when(lifecycle.createAndStart(any())).thenThrow(new IllegalStateException("Could not start the container")); + + assertThrows(IllegalStateException.class, () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, + IMAGE, "floci-network", METASTORE, NOT_STOPPED)); + + InOrder order = inOrder(lifecycle); + order.verify(lifecycle).ensureConnected("floci-container", hdfsName, "floci"); + order.verify(lifecycle).createAndStart(any()); + order.verify(lifecycle).disconnectFromNetwork("floci-container", hdfsName); + } + + @Test + void anHdfsWhoseNetworkDockerKeepsFlocisContainerOnStaysKnownForTheNextTeardown() { + when(currentContainer.resolveContainerId()).thenReturn(Optional.of("floci-container")); + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.resolveContainerNetworkIp(hdfsName, hdfsName)).thenReturn("172.18.0.9"); + runningOn(hdfsName, hdfsName); + ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", ""); + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, NOT_STOPPED); + when(lifecycle.disconnectFromNetwork("floci-container", hdfsName)).thenReturn(false, true); + + storage.stopManagedContainers(); + storage.stopManagedContainers(); + storage.stopManagedContainers(); + + // Kept on it the first time, so still known; off it the second; not asked again the third. + verify(lifecycle, times(2)).disconnectFromNetwork("floci-container", hdfsName); + // Nor is a storage whose network Docker keeps it on gone. + when(lifecycle.disconnectFromNetwork("floci-container", hdfsName)).thenReturn(false); + when(lifecycle.removeVolume(anyString())).thenReturn(true); + when(lifecycle.removeNetwork(hdfsName)).thenReturn(true); + assertFalse(storage.remove("j-1")); + } + + @Test + void aMetastoreGetsTheClustersCoreSiteAndHiveSiteAfterItsOwnSettings() { + when(awsEnv.flociEndpoint(false)).thenReturn("http://host.docker.internal:4566"); + when(awsEnv.sdkBaselineEnv(anyString(), any(), anyString(), any(), anyString())).thenReturn(List.of()); + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-6", Map.of())); + when(lifecycle.probeContainer("c-6")).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.resolveContainerNetworkIp("c-6", hdfsName)).thenReturn("172.18.0.7"); + ContainerExecStubs.completeEveryExec(docker, "c-6", 0L, "", ""); + Map settings = new LinkedHashMap<>(); + settings.put("fs.s3a.endpoint", "http://s3.example:9000"); + settings.put("hive.metastore.warehouse.dir", "s3://bucket/warehouse dir"); + + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", + new ClusterStorage.HiveMetastore("arn:aws:iam::123456789012:role/r", settings), NOT_STOPPED); + + // One to a line, so a value with a space stays one argument. + verify(spec).withEnv("FLOCI_HIVE_METASTORE_SITE", String.join("\n", "--hiveconf", + "fs.s3a.endpoint=http://s3.example:9000", "--hiveconf", + "hive.metastore.warehouse.dir=s3://bucket/warehouse dir")); + // Last, so each replaces the service's own, its S3 and warehouse among them. + verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains( + "[ -z \"$FLOCI_HIVE_METASTORE_SITE\" ] || mapfile -t site <<< \"$FLOCI_HIVE_METASTORE_SITE\"; cd /tmp;") + && entrypoint.get(2).contains( + "hive.metastore.warehouse.dir=hdfs://$FLOCI_HDFS_HOST:8020/user/hive/warehouse" + + " \"${site[@]}\" &"))); + } + @Test void aClustersHdfsStartsFromTheImageIdItsPullResolvedWhichAnotherPullCannotMove() { String id = "sha256:" + "a".repeat(64); @@ -241,7 +608,7 @@ class EmrClusterStorageTest { when(lifecycle.resolveContainerNetworkIp("c-1", hdfsName)).thenReturn("172.18.0.5"); ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", ""); - storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED); + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, NOT_STOPPED); verify(containerBuilder).newContainer(id); verify(containerBuilder, never()).newContainer(IMAGE); @@ -258,7 +625,7 @@ class EmrClusterStorageTest { when(lifecycle.probeContainer("c-1")).thenReturn(ContainerLiveness.RUNNING); ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", ""); - assertEquals("127.0.0.1", storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", + assertEquals("127.0.0.1", storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", null, NOT_STOPPED).hdfsAddress()); verify(lifecycle).removeIfExistsStrict(hdfsName); @@ -300,11 +667,11 @@ class EmrClusterStorageTest { return null; }).when(lifecycle).ensureVolume(eq(hdfsName), any()); Future starting = steps.submit( - () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", NOT_STOPPED)); + () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", null, NOT_STOPPED)); assertTrue(firstLooked.await(10, TimeUnit.SECONDS)); Future waiting = steps.submit(() -> { second.set(Thread.currentThread()); - return storage.hdfs("j-2", "123456789012", "us-east-1", HOST, IMAGE, "host", NOT_STOPPED); + return storage.hdfs("j-2", "123456789012", "us-east-1", HOST, IMAGE, "host", null, NOT_STOPPED); }); assertEquals("127.0.0.1", starting.get(10, TimeUnit.SECONDS).hdfsAddress()); @@ -334,7 +701,7 @@ class EmrClusterStorageTest { when(lifecycle.probeContainer("c-1")).thenReturn(ContainerLiveness.RUNNING); ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", ""); - storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", NOT_STOPPED); + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", null, NOT_STOPPED); verify(lifecycle).createAndStart(any()); } @@ -346,7 +713,8 @@ class EmrClusterStorageTest { .when(lifecycle).removeIfExistsStrict(hdfsName); IllegalStateException failure = assertThrows(IllegalStateException.class, - () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED)); + () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, + "floci-network", null, NOT_STOPPED)); // Not a name clash on the create that follows. assertEquals("Failed to remove stale container " + hdfsName, failure.getMessage()); @@ -362,7 +730,8 @@ class EmrClusterStorageTest { ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", ""); IllegalStateException failure = assertThrows(IllegalStateException.class, - () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED)); + () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, + "floci-network", null, NOT_STOPPED)); assertEquals("The HDFS of EMR cluster j-1 has no address on Docker network " + hdfsName, failure.getMessage()); @@ -376,7 +745,7 @@ class EmrClusterStorageTest { ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", ""); assertEquals("172.18.0.6", storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, - "floci-network", NOT_STOPPED).hdfsAddress()); + "floci-network", null, NOT_STOPPED).hdfsAddress()); verify(lifecycle, never()).createAndStart(any()); verify(lifecycle, never()).removeIfExists(anyString()); @@ -388,7 +757,8 @@ class EmrClusterStorageTest { when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.UNKNOWN); IllegalStateException failure = assertThrows(IllegalStateException.class, - () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED)); + () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, + "floci-network", null, NOT_STOPPED)); assertEquals("Could not tell whether the HDFS of EMR cluster j-1 runs", failure.getMessage()); verify(lifecycle, never()).removeIfExists(anyString()); @@ -407,7 +777,7 @@ class EmrClusterStorageTest { ContainerExecStubs.completeEveryExec(docker, "c-7", 0L, "", ""); assertEquals("172.18.0.8", storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, - "floci-network", NOT_STOPPED).hdfsAddress()); + "floci-network", null, NOT_STOPPED).hdfsAddress()); InOrder order = inOrder(lifecycle); order.verify(lifecycle).removeIfExistsStrict(hdfsName); @@ -423,7 +793,8 @@ class EmrClusterStorageTest { List> looks = ContainerExecStubs.completeEveryExec(docker, "c-3", 1L, "", ""); IllegalStateException failure = assertThrows(IllegalStateException.class, - () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED)); + () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, + "floci-network", null, NOT_STOPPED)); assertEquals("The HDFS of EMR cluster j-1 stopped before it was ready", failure.getMessage()); assertEquals(List.of(), looks); @@ -431,7 +802,8 @@ class EmrClusterStorageTest { @Test void aClustersHdfsThatIsNotReadyInTimeFailsToStart() { - EmrClusterStorage impatient = new EmrClusterStorage(lifecycle, containerBuilder, config, Duration.ZERO, + EmrClusterStorage impatient = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv, + roleCredentials, currentContainer, config, Duration.ZERO, System::nanoTime); when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING); when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-4", Map.of())); @@ -439,7 +811,8 @@ class EmrClusterStorageTest { ContainerExecStubs.completeEveryExec(docker, "c-4", 1L, "", ""); IllegalStateException failure = assertThrows(IllegalStateException.class, - () -> impatient.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED)); + () -> impatient.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, + "floci-network", null, NOT_STOPPED)); assertEquals("The HDFS of EMR cluster j-1 did not start within 0 seconds", failure.getMessage()); } @@ -448,7 +821,8 @@ class EmrClusterStorageTest { void aStepWaitingWhileAnotherStartsItsClustersHdfsHasOnlyWhatIsLeftOfTheStartTimeout() throws Exception { AtomicLong clock = new AtomicLong(); long timeout = Duration.ofMinutes(2).toNanos(); - EmrClusterStorage timed = new EmrClusterStorage(lifecycle, containerBuilder, config, Duration.ofMinutes(2), + EmrClusterStorage timed = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv, + roleCredentials, currentContainer, config, Duration.ofMinutes(2), clock::get); // The first step starts it; the second, which waited for it, finds it running. when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING, ContainerLiveness.RUNNING); @@ -470,11 +844,12 @@ class EmrClusterStorageTest { ExecutorService steps = Executors.newFixedThreadPool(2); try { Future first = steps.submit( - () -> timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED)); + () -> timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, + "floci-network", null, NOT_STOPPED)); assertTrue(firstLooks.await(10, TimeUnit.SECONDS)); Future waiting = steps.submit(() -> { second.set(Thread.currentThread()); - return timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED); + return timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, NOT_STOPPED); }); assertThrows(ExecutionException.class, () -> first.get(10, TimeUnit.SECONDS)); @@ -492,7 +867,8 @@ class EmrClusterStorageTest { @Test void aStepWaitingForItsClustersHdfsThroughATeardownStopsAsItsDriverWouldAndStartsItNoMore() { AtomicLong clock = new AtomicLong(); - EmrClusterStorage timed = new EmrClusterStorage(lifecycle, containerBuilder, config, Duration.ofMinutes(2), + EmrClusterStorage timed = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv, + roleCredentials, currentContainer, config, Duration.ofMinutes(2), clock::get); when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING); when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-5", Map.of())); @@ -505,7 +881,7 @@ class EmrClusterStorageTest { }); assertThrows(ClusterStorage.Stopped.class, - () -> timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED)); + () -> timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, NOT_STOPPED)); verify(lifecycle, times(1)).createAndStart(any()); // As it starts, one left from before goes, and the teardown removes it; the step does again, in case it @@ -519,7 +895,7 @@ class EmrClusterStorageTest { when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING); assertThrows(ClusterStorage.Stopped.class, - () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", () -> true)); + () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> true)); verify(lifecycle, never()).createAndStart(any()); verify(lifecycle, never()).removeIfExists(anyString()); @@ -530,7 +906,8 @@ class EmrClusterStorageTest { @Test void theFirstPullOfItsImageIsNoPartOfTheHdfsStartTimeout() { AtomicLong clock = new AtomicLong(); - EmrClusterStorage timed = new EmrClusterStorage(lifecycle, containerBuilder, config, Duration.ofMinutes(2), + EmrClusterStorage timed = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv, + roleCredentials, currentContainer, config, Duration.ofMinutes(2), clock::get); // The Hive image is not there yet, and its pull takes five minutes. when(lifecycle.resolveImageForLaunch(IMAGE, ImagePullBehavior.PREFER_CACHED, null)).thenAnswer(pull -> { @@ -544,7 +921,7 @@ class EmrClusterStorageTest { // Not ready the first time it is looked at, then ready. ContainerExecStubs.completeEveryExec(docker, "c-4", List.of(1L, 0L), "", ""); - assertEquals("172.18.0.11", timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", + assertEquals("172.18.0.11", timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, NOT_STOPPED).hdfsAddress()); } @@ -561,7 +938,7 @@ class EmrClusterStorageTest { when(running.exec()).thenReturn(List.of(other)); IllegalStateException failure = assertThrows(IllegalStateException.class, - () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", NOT_STOPPED)); + () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", null, NOT_STOPPED)); // Its daemons, on the ports j-2's hold, would never bind, and j-2's would answer for them. assertEquals("The HDFS of EMR cluster j-1 cannot start while that of EMR cluster j-2 runs in the network" @@ -575,7 +952,8 @@ class EmrClusterStorageTest { void aStepCancelledWhileItsClustersHdfsStartsStopsAndLeavesItToTheClustersOtherSteps() { AtomicBoolean cancelled = new AtomicBoolean(); AtomicLong clock = new AtomicLong(); - EmrClusterStorage timed = new EmrClusterStorage(lifecycle, containerBuilder, config, Duration.ofMinutes(2), + EmrClusterStorage timed = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv, + roleCredentials, currentContainer, config, Duration.ofMinutes(2), clock::get); when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING); when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-8", Map.of())); @@ -588,7 +966,8 @@ class EmrClusterStorageTest { }); assertThrows(ClusterStorage.Stopped.class, - () -> timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", cancelled::get)); + () -> timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, + "floci-network", null, cancelled::get)); // Only one left from before went, as it started; the one it started is the next step's. verify(lifecycle, times(1)).removeIfExistsStrict(hdfsName); @@ -607,7 +986,7 @@ class EmrClusterStorageTest { ContainerExecStubs.completeEveryExec(docker, "c-9", 0L, "", ""); assertEquals("172.18.0.10", storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, - "floci-network", NOT_STOPPED).hdfsAddress()); + "floci-network", null, NOT_STOPPED).hdfsAddress()); verify(lifecycle).createAndStart(any()); } @@ -619,7 +998,8 @@ class EmrClusterStorageTest { when(docker.execCreateCmd(hdfsName)).thenThrow(new DockerException("The daemon is busy", 500)); assertThrows(DockerException.class, - () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED)); + () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, + "floci-network", null, NOT_STOPPED)); verify(lifecycle, never()).createAndStart(any()); verify(lifecycle, never()).removeIfExists(anyString()); @@ -675,7 +1055,7 @@ class EmrClusterStorageTest { when(lifecycle.resolveContainerNetworkIp(hdfsName, hdfsName)).thenReturn("172.18.0.9"); runningOn(hdfsName, hdfsName); ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", ""); - storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED); + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, NOT_STOPPED); assertFalse(storage.remove("j-1")); // The next reset or shutdown removes it. @@ -688,7 +1068,7 @@ class EmrClusterStorageTest { void withNoNetworkItsStepsRunWithoutAnHdfs() { when(containerBuilder.resolveDockerNetwork(Optional.of("none"))).thenReturn(Optional.of("none")); - SparkJobRunner.Storage storageOnly = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "none", + SparkJobRunner.Storage storageOnly = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "none", null, NOT_STOPPED); // Docker joins a container placed there to no network, the HDFS's included. @@ -709,7 +1089,7 @@ class EmrClusterStorageTest { when(lifecycle.probeContainer("c-1")).thenReturn(ContainerLiveness.RUNNING); ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", ""); - storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "container:b", NOT_STOPPED); + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "container:b", null, NOT_STOPPED); verify(lifecycle).createAndStart(any()); verify(spec).withDockerNetwork(Optional.of("container:b")); @@ -726,7 +1106,7 @@ class EmrClusterStorageTest { containerIdOf("3333", "3333"); ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", ""); - assertEquals("127.0.0.1", storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "container:floci", + assertEquals("127.0.0.1", storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "container:floci", null, NOT_STOPPED).hdfsAddress()); verify(lifecycle, never()).createAndStart(any()); @@ -748,7 +1128,7 @@ class EmrClusterStorageTest { when(lifecycle.probeContainer("c-1")).thenReturn(ContainerLiveness.RUNNING); ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", ""); - storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "container:b", NOT_STOPPED); + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "container:b", null, NOT_STOPPED); verify(lifecycle).createAndStart(any()); } @@ -759,7 +1139,7 @@ class EmrClusterStorageTest { when(lifecycle.resolveContainerNetworkIp(hdfsName, hdfsName)).thenReturn("172.18.0.9"); runningOn(hdfsName, hdfsName); ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", ""); - storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED); + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, NOT_STOPPED); storage.stopManagedContainers(); storage.stopManagedContainers(); @@ -775,7 +1155,7 @@ class EmrClusterStorageTest { when(lifecycle.resolveContainerNetworkIp(hdfsName, hdfsName)).thenReturn("172.18.0.9"); runningOn(hdfsName, hdfsName); ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", ""); - storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", NOT_STOPPED); + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, NOT_STOPPED); doThrow(new IllegalStateException("Failed to remove container " + hdfsName)).doNothing() .when(lifecycle).removeIfExistsStrict(hdfsName); @@ -850,6 +1230,30 @@ class EmrClusterStorageTest { verify(lifecycle, times(2)).removeIfExistsStrict(ended); } + @Test + void theSweepHasFlocisContainerLeaveTheNetworksItRemoves() { + when(currentContainer.resolveContainerId()).thenReturn(Optional.of("floci-container")); + ListContainersCmd list = mock(ListContainersCmd.class, RETURNS_SELF); + when(docker.listContainersCmd()).thenReturn(list); + when(list.exec()).thenReturn(List.of()); + ListNetworksCmd networks = mock(ListNetworksCmd.class, RETURNS_SELF); + when(docker.listNetworksCmd()).thenReturn(networks); + Network keptNetwork = hdfsNetwork("emr-j-up-hdfs", "j-up"); + Network goneNetwork = hdfsNetwork("emr-j-ended-hdfs", "j-ended"); + when(networks.exec()).thenReturn(List.of(keptNetwork, goneNetwork)); + ListVolumesCmd volumes = mock(ListVolumesCmd.class, RETURNS_SELF); + when(docker.listVolumesCmd()).thenReturn(volumes); + when(volumes.exec()).thenReturn(mock(ListVolumesResponse.class)); + + storage.removeAllBut(Set.of("j-up")); + + // An earlier Floci's container, this one after a restart, joined it, and Docker removes no network in use. + InOrder order = inOrder(lifecycle); + order.verify(lifecycle).disconnectFromNetwork("floci-container", "emr-j-ended-hdfs"); + order.verify(lifecycle).removeNetwork("emr-j-ended-hdfs"); + verify(lifecycle, never()).disconnectFromNetwork("floci-container", "emr-j-up-hdfs"); + } + // The container name runs with networkMode as its network mode, as Docker inspects it. private void runningOn(String name, String networkMode) { InspectContainerCmd inspect = mock(InspectContainerCmd.class); diff --git a/src/test/java/io/floci/aws/services/emr/EmrHiveStepsDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrHiveStepsDockerIntegrationTest.java index bc027d166e..b940a8e785 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrHiveStepsDockerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrHiveStepsDockerIntegrationTest.java @@ -77,7 +77,7 @@ class EmrHiveStepsDockerIntegrationTest { } @Test - void hiveStepsKeepTheirTablesInTheClustersMetastoreAndHdfsForTheStepsAfterThem() { + void hiveAndSparkStepsShareTheClustersMetastoreServiceAndHdfs() { startCluster(HIVE_AND_SPARK, "[]", null); put("queries/load.q", """ create external table kv (k string, v int) @@ -107,8 +107,39 @@ class EmrHiveStepsDockerIntegrationTest { String pinned = addStep("command-runner.jar", "hadoop", "fs", "-cat", "hdfs:///floci/pinned/*"); assertEquals("COMPLETED", state(pinned)); assertEquals("a\nb\nc\n", stepLog(pinned, "stdout.gz")); - // The metastore is the cluster's own, a database in its /mnt. - assertEquals("COMPLETED", state(addStep("command-runner.jar", "test", "-d", "/mnt/var/lib/hive/metastore_db"))); + // A Spark step uses the cluster's metastore too: it reads Hive's table, and makes one a Hive step reads. + put("jobs/catalog.py", """ + import sys + from pyspark.sql import SparkSession + spark = SparkSession.builder.enableHiveSupport().getOrCreate() + rows = sorted(f"{row.k}{row.v}" for row in spark.sql("select k, v from scaled").collect()) + spark.createDataFrame([(" ".join(rows),)], ["value"]).coalesce(1).write.text(sys.argv[1]) + spark.sql("create table from_spark stored as textfile as select upper(k) as k from scaled") + """); + assertEquals("COMPLETED", state(addStep("command-runner.jar", "spark-submit", s3Uri("jobs/catalog.py"), + s3Uri("out/spark/")))); + assertEquals("a10 b20 c30\n", objects("out/spark/")); + String fromSpark = addStep("command-runner.jar", "hive-script", "--run-hive-script", "--args", + "-e", "select k from from_spark order by k;"); + assertEquals("COMPLETED", state(fromSpark)); + assertTrue(stepLog(fromSpark, "stdout.gz").contains("A\nB\nC\n")); + } + + @Test + void hiveStepsRunningAtOnceShareTheClustersMetastoreService() { + startCluster(HIVE_AND_SPARK, "[]", null, 2); + + // The first holds its session past the second's, which an embedded Derby database would refuse. + String slow = addStep("command-runner.jar", "hive-script", "--run-hive-script", "--args", + "-e", "create table slow (k string); !sleep 20; insert into slow values ('s');"); + String quick = addStep("command-runner.jar", "hive-script", "--run-hive-script", "--args", + "-e", "create table quick as select 'q' as k;"); + assertEquals("COMPLETED", state(quick)); + assertEquals("COMPLETED", state(slow)); + String both = addStep("command-runner.jar", "hive-script", "--run-hive-script", "--args", + "-e", "select k from slow union all select k from quick order by k;"); + assertEquals("COMPLETED", state(both)); + assertTrue(stepLog(both, "stdout.gz").contains("q\ns\n")); } @Test @@ -162,8 +193,14 @@ class EmrHiveStepsDockerIntegrationTest { /** A cluster with {@code applications}, {@code configurations} and a bootstrap action's script, if not null. */ private void startCluster(String applications, String configurations, String bootstrapScript) { + startCluster(applications, configurations, bootstrapScript, 1); + } + + /** As {@link #startCluster(String, String, String)}, running up to {@code stepConcurrency} steps at once. */ + private void startCluster(String applications, String configurations, String bootstrapScript, + int stepConcurrency) { ObjectNode request = JSON.createObjectNode().put("Name", "hive-steps").put("ReleaseLabel", "emr-7.5.0") - .put("LogUri", s3Uri("logs/")); + .put("LogUri", s3Uri("logs/")).put("StepConcurrencyLevel", stepConcurrency); try { request.set("Applications", JSON.readTree(applications)); request.set("Configurations", JSON.readTree(configurations)); diff --git a/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java b/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java index 195c645284..d2a75382ee 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java @@ -333,12 +333,13 @@ class EmrServiceContainerStepsTest { assertEquals(3, service.listInstanceGroups(cluster.getId()).get(0).getRunningInstanceCount()); fixture.runStepThread(); + // A cluster without Hive runs no metastore service. List started = Arrays.asList(cluster.getId(), "ip-10-0-0-1.ec2.internal", - "public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", null); + "public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", null, "false", null); assertEquals(List.of(started, started), fixture.clusterStorage.hdfs); - assertEquals(new SparkJobRunner.Storage(cluster.getId() + "-home", cluster.getId() + "-mnt", - "ip-10-0-0-1.ec2.internal", EmrServiceFixture.RecordingStorage.HDFS_ADDRESS, - EmrServiceFixture.RecordingStorage.HDFS_NETWORK), runner.jobs.get(0).storage()); + assertEquals(new SparkJobRunner.Storage(cluster.getId() + "-home", cluster.getId() + "-mnt") + .withHdfs("ip-10-0-0-1.ec2.internal", EmrServiceFixture.RecordingStorage.HDFS_ADDRESS, + EmrServiceFixture.RecordingStorage.HDFS_NETWORK), runner.jobs.get(0).storage()); } @Test @@ -824,7 +825,10 @@ class EmrServiceContainerStepsTest { // Its cluster's Spark settings are not Hive's. assertEquals(Map.of(), job.sparkDefaults()); assertEquals(Map.of("HADOOP_HEAPSIZE", "2048"), job.environment()); - assertEquals(hdfsStorage(cluster), job.storage()); + // A cluster with Hive's primary node runs its metastore service, which its steps use, with its hive-site. + assertEquals("true", fixture.clusterStorage.hdfs.get(0).get(4)); + assertEquals(Map.of("hive.exec.reducers.max", "8"), fixture.clusterStorage.metastores.get(0).settings()); + assertEquals(hdfsStorage(cluster).withHiveMetastore("thrift://ip-10-0-0-1.ec2.internal:9083"), job.storage()); assertEquals("s3://logs/emr/" + cluster.getId() + "/steps/" + stepId + "/", job.logFolder()); assertEquals(List.of(cluster.getId()), fixture.clusterStorage.created); assertEquals("COMPLETED", service.describeStep(cluster.getId(), stepId).getState()); @@ -1227,9 +1231,9 @@ class EmrServiceContainerStepsTest { // A spark-submit step through command-runner.jar, written for a cluster with YARN. // A cluster's storage as a step gets it, its HDFS on the primary node of a cluster with no instance groups. private static SparkJobRunner.Storage hdfsStorage(EmrCluster cluster) { - return new SparkJobRunner.Storage(cluster.getId() + "-home", cluster.getId() + "-mnt", - "ip-10-0-0-1.ec2.internal", EmrServiceFixture.RecordingStorage.HDFS_ADDRESS, - EmrServiceFixture.RecordingStorage.HDFS_NETWORK); + return new SparkJobRunner.Storage(cluster.getId() + "-home", cluster.getId() + "-mnt") + .withHdfs("ip-10-0-0-1.ec2.internal", EmrServiceFixture.RecordingStorage.HDFS_ADDRESS, + EmrServiceFixture.RecordingStorage.HDFS_NETWORK); } // The AWS CLI's Hive step: command-runner.jar running hive-script with the step's arguments after its --args. diff --git a/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java b/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java index b9888340d9..ccd1f1164d 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java @@ -63,6 +63,8 @@ final class EmrServiceFixture { final List created = new ArrayList<>(); // Each HDFS started: its cluster, primary node's host name, image and Docker network. final List> hdfs = new ArrayList<>(); + // Each HDFS's metastore service asked for. + final List metastores = new ArrayList<>(); RuntimeException hdfsFailure; // Runs as each HDFS starts, with what tells it the step is past starting. Consumer whileStartingHdfs = stopped -> { }; @@ -84,13 +86,19 @@ final class EmrServiceFixture { @Override public SparkJobRunner.Storage hdfs(String clusterId, String accountId, String region, String host, - String image, String dockerNetwork, BooleanSupplier stopped) { - hdfs.add(Arrays.asList(clusterId, host, image, dockerNetwork)); + String image, String dockerNetwork, HiveMetastore hiveMetastore, + BooleanSupplier stopped) { + hdfs.add(Arrays.asList(clusterId, host, image, dockerNetwork, String.valueOf(hiveMetastore != null), + hiveMetastore != null ? hiveMetastore.role() : null)); + if (hiveMetastore != null) { + metastores.add(hiveMetastore); + } whileStartingHdfs.accept(stopped); if (hdfsFailure != null) { throw hdfsFailure; } - return volumes(clusterId).withHdfs(host, HDFS_ADDRESS, HDFS_NETWORK); + SparkJobRunner.Storage storage = volumes(clusterId).withHdfs(host, HDFS_ADDRESS, HDFS_NETWORK); + return hiveMetastore != null ? storage.withHiveMetastore("thrift://" + host + ":9083") : storage; } @Override diff --git a/src/test/java/io/floci/aws/services/emr/EmrSparkStepsTest.java b/src/test/java/io/floci/aws/services/emr/EmrSparkStepsTest.java index 550479cec3..34b4697ab6 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrSparkStepsTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrSparkStepsTest.java @@ -297,6 +297,27 @@ class EmrSparkStepsTest { assertEquals(Map.of(), EmrSparkSteps.coreSite(null, objectMapper)); } + @Test + void aClustersHiveMetastoreServiceGetsItsCoreSiteThenItsHiveSiteWhichWins() { + String configurations = """ + [{"Classification": "core-site", "Properties": {"fs.s3a.connection.maximum": "50", + "hive.exec.scratchdir": "/tmp/core"}}, + {"Classification": "hive-site", "Properties": {"hive.exec.scratchdir": "/tmp/hive", + "hive.metastore.warehouse.dir": "s3://bucket/warehouse/"}}, + {"Classification": "spark-hive-site", "Properties": {"hive.metastore.warehouse.dir": "s3://other/"}}, + {"Classification": "tez-site", "Properties": {"tez.am.resource.memory.mb": "2048"}}] + """; + + Map settings = EmrSparkSteps.hiveMetastoreSettings(configurations, objectMapper); + + // Not spark-hive-site, Spark's own, nor tez-site, which the service does not read. + assertEquals(Map.of("fs.s3a.connection.maximum", "50", "hive.exec.scratchdir", "/tmp/hive", + "hive.metastore.warehouse.dir", "s3://bucket/warehouse/"), settings); + assertEquals(List.of("fs.s3a.connection.maximum", "hive.exec.scratchdir", "hive.metastore.warehouse.dir"), + List.copyOf(settings.keySet())); + assertEquals(Map.of(), EmrSparkSteps.hiveMetastoreSettings(null, objectMapper)); + } + @Test void theClustersSparkLog4j2PropertiesComeFromItsConfigurations() { String configurations = """ diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java index cd3ef3e954..ebb24837ba 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java @@ -82,8 +82,8 @@ class EmrServerlessSparkRunnerTest { private static final String ENDPOINT = "http://floci:4566"; // A cluster's storage, its HDFS running on its primary node. private static final SparkJobRunner.Storage STORAGE = new SparkJobRunner.Storage( - "floci-aws-emr-j-2AXXXXXXGAPLF-home", "floci-aws-emr-j-2AXXXXXXGAPLF-mnt", "ip-10-0-0-1.ec2.internal", - "172.18.0.5", "floci-aws-emr-j-2AXXXXXXGAPLF-hdfs"); + "floci-aws-emr-j-2AXXXXXXGAPLF-home", "floci-aws-emr-j-2AXXXXXXGAPLF-mnt") + .withHdfs("ip-10-0-0-1.ec2.internal", "172.18.0.5", "floci-aws-emr-j-2AXXXXXXGAPLF-hdfs"); private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); private final ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); @@ -249,11 +249,29 @@ class EmrServerlessSparkRunnerTest { } @Test - void anEmrHiveStepsHiveReachesItsClustersHdfsAndKeepsItsMetastoreInItsMnt() { + void anEmrHiveStepsHiveReachesItsClustersHdfsAndMetastoreServiceOnItsPrimaryNode() { List arguments = EmrServerlessSparkRunner.hiveArguments( hiveStep(List.of("--hiveconf", "hive.exec.reducers.max=8", "-f", "s3://bucket/queries/report.q")), ENDPOINT); + int tez = arguments.indexOf("tez.am.client.am.port-range=40000-40100"); + assertEquals(List.of( + "--hiveconf", "fs.defaultFS=hdfs://ip-10-0-0-1.ec2.internal:8020", + "--hiveconf", "hive.metastore.client.factory.class=" + + "org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClientFactory", + "--hiveconf", "hive.metastore.uris=thrift://ip-10-0-0-1.ec2.internal:9083", + "--hiveconf", "hive.exec.reducers.max=8", "-f", "s3://bucket/queries/report.q"), + arguments.subList(tez + 1, arguments.size())); + } + + @Test + void anEmrHiveStepWhereNoMetastoreServiceRunsKeepsItsMetastoreInItsClustersMnt() { + // As in a network namespace the steps share, where the service would listen on every interface. + SparkJobRunner.Job step = hiveStep(List.of("-f", "s3://bucket/queries/report.q")); + List arguments = EmrServerlessSparkRunner.hiveArguments(step.onStorage( + new SparkJobRunner.Storage("j-1-home", "j-1-mnt").withHdfs("ip-10-0-0-1.ec2.internal", "127.0.0.1", + null)), ENDPOINT); + int tez = arguments.indexOf("tez.am.client.am.port-range=40000-40100"); assertEquals(List.of( "--hiveconf", "fs.defaultFS=hdfs://ip-10-0-0-1.ec2.internal:8020", @@ -263,8 +281,11 @@ class EmrServerlessSparkRunnerTest { + "jdbc:derby:;databaseName=/mnt/var/lib/hive/metastore_db;create=true", "--hiveconf", "hive.metastore.schema.verification=false", "--hiveconf", "datanucleus.schema.autoCreateAll=true", - "--hiveconf", "hive.exec.reducers.max=8", "-f", "s3://bucket/queries/report.q"), + "-f", "s3://bucket/queries/report.q"), arguments.subList(tez + 1, arguments.size())); + // Nor does its Spark steps' Hive client get one. + assertFalse(EmrServerlessSparkRunner.sparkSubmitArguments(stepJob(Map.of()), ENDPOINT).stream() + .anyMatch(argument -> argument.startsWith("spark.hadoop.hive.metastore.uris="))); } @Test @@ -592,6 +613,23 @@ class EmrServerlessSparkRunnerTest { "s3://bucket/jobs/report.py"), arguments.subList(20, arguments.size())); } + @Test + void aSparkStepOnAClusterWithHiveUsesItsMetastoreServiceUnlessItsSparkHiveSiteNamesAnother() { + String glue = "spark.hadoop.hive.metastore.client.factory.class=" + + "com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory"; + SparkJobRunner.Job job = stepJob(Map.of("spark.hadoop.hive.metastore.client.factory.class", + "com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory")) + .onStorage(STORAGE.withHiveMetastore("thrift://ip-10-0-0-1.ec2.internal:9083")); + + List arguments = EmrServerlessSparkRunner.sparkSubmitArguments(job, ENDPOINT); + + int metastore = arguments.indexOf("spark.hadoop.hive.metastore.uris=thrift://ip-10-0-0-1.ec2.internal:9083"); + assertTrue(metastore > 0, arguments.toString()); + assertEquals("--conf", arguments.get(metastore - 1)); + // Floci's, before the cluster's spark-defaults and spark-hive-site, which win. + assertTrue(arguments.indexOf(glue) > metastore, arguments.toString()); + } + @Test void aCommandOnAClusterGivesItsHadoopCommandTheClustersHdfsToo() { ContainerBuilder builder = mock(ContainerBuilder.class); @@ -1438,8 +1476,9 @@ class EmrServerlessSparkRunnerTest { return new SparkJobRunner.Job("emr", "s-1", "123456789012", "eu-west-1", "emr-7.5.0", HIVE, null, null, "floci-network", "arn:aws:iam::123456789012:role/emr-ec2", Map.of(), application, List.of("hive-script", "--run-hive-script", "--args"), Duration.ZERO, null, null, Map.of(), List.of(), - new SparkJobRunner.Storage("j-1-home", "j-1-mnt", "ip-10-0-0-1.ec2.internal", "172.18.0.5", - "j-1-hdfs"), Map.of(), Map.of(), Map.of(), Map.of(), Map.of()); + new SparkJobRunner.Storage("j-1-home", "j-1-mnt").withHdfs("ip-10-0-0-1.ec2.internal", "172.18.0.5", + "j-1-hdfs").withHiveMetastore("thrift://ip-10-0-0-1.ec2.internal:9083"), + Map.of(), Map.of(), Map.of(), Map.of(), Map.of()); } private static SparkJobRunner.Job customImageJob(String customImage) {