feat(emr): have the JVMs in EMR containers trust Floci's CA (#6926)

With TLS on, every container Floci launches gets the CA bundle and the
SSL_CERT_FILE family of variables, but the JVM reads none of them. So
in the docker runner mode a Spark job's own SDK clients that ignore
AWS_ENDPOINT_URL, the AWS SDK for Java 1.x's or an older 2.x's,
failed with "PKIX path building failed" against Floci's HTTPS, even
with FLOCI_DNS_SPOOF_AWS_ENDPOINTS sending AWS's endpoint names to
Floci. A job could only reach Floci over its HTTP endpoint.

Floci now also writes the bundle's certificates as a PKCS12 trust
store at boot, floci-ca-bundle.p12 beside the bundle. A launcher whose
workload is Java can copy it into a container before the container
starts (ContainerLifecycleManager.copyJavaTrustStore) and point the
container's JVMs at it through JAVA_TOOL_OPTIONS, with a shell line
that does so only when the file is there. The store has no password
and the line gives only its path, so a trust store a job or an image
names itself replaces Floci's, with that store's own type and
password. EMR Serverless job runs and EMR steps copy it into the
driver's container ahead of spark-submit or the step's command, and
the bootstrap actions' container gets it for its actions, then drops
it before the image is kept. Other services' containers are unchanged.

JAVA_TOOL_OPTIONS rather than spark.driver.extraJavaOptions, since
setting that key would replace what the image's spark-defaults.conf
gives it, and a job's own value would drop Floci's. Each JVM prints
"Picked up JAVA_TOOL_OPTIONS: ..." on its standard error, as the docs
now say.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-29 07:50:46 -05:00
1 parent c4ae11c414
commit c9bc1e7cb8
13 files changed
+472 -47

No files matched your search

+1 -1
View File
@@ -107,7 +107,7 @@ Names are added by the custom domain operations: API Gateway `CreateDomainName`,
### Containers Floci Launches
Every container Floci launches, from Lambda functions and ECS or Batch tasks to the Docker backends behind RDS, ElastiCache, MWAA and Flink, and the Kubernetes Lambda pods, receives `/etc/floci-ca-bundle.pem`: the public root CAs the Floci JVM trusts, followed by the Floci CA (or your certificate file when you provide one). `SSL_CERT_FILE`, `CURL_CA_BUNDLE`, `REQUESTS_CA_BUNDLE`, `NODE_EXTRA_CA_CERTS` and `AWS_CA_BUNDLE` point at it, so curl, Python, Node.js, Go, the AWS CLI and the AWS SDKs that read `AWS_CA_BUNDLE` reach both Floci and public HTTPS sites with no setup in the workload. A variable you set on the function or task definition wins over the injected one. The JVM ignores all of these variables, so a Java workload still needs its own trust store, as shown under SDK Configuration Examples. The bundle is written to `{persistent-path}/tls/floci-ca-bundle.pem` at startup; when it is missing, or when an image has no `/etc` to copy it into, the container starts without the variables and Floci logs a warning. Floci trusts the same bundle when it fetches a JWT issuer's keys for an HTTP API authorizer or an AppSync OIDC provider, so an issuer it serves itself, a Cognito user pool for one, verifies over HTTPS.
Every container Floci launches, from Lambda functions and ECS or Batch tasks to the Docker backends behind RDS, ElastiCache, MWAA and Flink, and the Kubernetes Lambda pods, receives `/etc/floci-ca-bundle.pem`: the public root CAs the Floci JVM trusts, followed by the Floci CA (or your certificate file when you provide one). `SSL_CERT_FILE`, `CURL_CA_BUNDLE`, `REQUESTS_CA_BUNDLE`, `NODE_EXTRA_CA_CERTS` and `AWS_CA_BUNDLE` point at it, so curl, Python, Node.js, Go, the AWS CLI and the AWS SDKs that read `AWS_CA_BUNDLE` reach both Floci and public HTTPS sites with no setup in the workload. A variable you set on the function or task definition wins over the injected one. The JVM ignores all of these variables, so a Java workload still needs its own trust store, as shown under SDK Configuration Examples. Floci writes one beside the bundle, `{persistent-path}/tls/floci-ca-bundle.p12` (PKCS12, no password), with the same certificates; EMR steps and bootstrap actions and EMR Serverless job runs in the `docker` runner mode get it at `/etc/floci-ca-bundle.p12`, and every JVM in them uses it through `JAVA_TOOL_OPTIONS`, which gives only its path (`-Djavax.net.ssl.trustStore`), so a trust store a job names itself replaces it, with that store's own type and password. The bundle is written to `{persistent-path}/tls/floci-ca-bundle.pem` at startup; when it is missing, or when an image has no `/etc` to copy it into, the container starts without the variables and Floci logs a warning. Floci trusts the same bundle when it fetches a JWT issuer's keys for an HTTP API authorizer or an AppSync OIDC provider, so an issuer it serves itself, a Cognito user pool for one, verifies over HTTPS.
## User-Provided Certificates
+9 -1
View File
@@ -136,6 +136,14 @@ publishes for customizing EMR Serverless images (`public.ecr.aws/emr-serverless/
* **Credentials**: the container gets a session for the run's execution role when IAM knows the role,
otherwise the account's placeholder credentials, and `AWS_ENDPOINT_URL` pointing at Floci, so the
job's own SDK clients reach Floci too.
* **HTTPS**: with [TLS](../configuration/tls.md) on, the container also gets Floci's CA bundle as a
Java trust store, `/etc/floci-ca-bundle.p12`, which every JVM in it uses through
`JAVA_TOOL_OPTIONS`, each saying so on its standard error (`Picked up JAVA_TOOL_OPTIONS: ...`); a
trust store the job names itself, with `-Djavax.net.ssl.trustStore`, replaces it. So
the job trusts Floci over HTTPS, and with
[`FLOCI_DNS_SPOOF_AWS_ENDPOINTS`](../configuration/environment-variables.md#transparent-endpoints)
on as well, which leads AWS's own endpoint names to Floci, SDK clients that ignore `AWS_ENDPOINT_URL`,
the AWS SDK for Java 1.x's for one, reach Floci unchanged.
* **Output**: the driver's output goes to Floci's log, prefixed `emr-serverless:<jobRunId>`. With an S3
log destination, the run's `s3MonitoringConfiguration` or else the application's, its standard output
and error also go to Floci's S3 once the run ends, gzipped, as `stdout.gz` and `stderr.gz` under
@@ -156,7 +164,7 @@ publishes for customizing EMR Serverless images (`public.ecr.aws/emr-serverless/
## Limitations and Differences from AWS
* **Jobs do not execute by default**: in the `immediate` runner mode `StartJobRun` records a job run and moves it through its states, but nothing runs. In the `docker` mode a Spark run executes in local mode in one container, so worker counts and sizes, initial and maximum capacity are not applied; a Hive run is `FAILED` without running, in Floci's own wording, as is a driver's failure. Of the monitoring configuration, the S3 log destination gets the driver's `stdout.gz` and `stderr.gz` once a run ends (no event logs, rotated files or uploads while it runs), and CloudWatch Logs the driver's output while it runs (there are no executor logs, local mode having no executors, and `encryptionKeyArn` is ignored), and Floci's CA is not in the job's Java truststore, so a job reaches Floci over its HTTP endpoint only.
* **Jobs do not execute by default**: in the `immediate` runner mode `StartJobRun` records a job run and moves it through its states, but nothing runs. In the `docker` mode a Spark run executes in local mode in one container, so worker counts and sizes, initial and maximum capacity are not applied; a Hive run is `FAILED` without running, in Floci's own wording, as is a driver's failure. Of the monitoring configuration, the S3 log destination gets the driver's `stdout.gz` and `stderr.gz` once a run ends (no event logs, rotated files or uploads while it runs), and CloudWatch Logs the driver's output while it runs (there are no executor logs, local mode having no executors, and `encryptionKeyArn` is ignored).
* **Unsourced errors**: AWS documents neither the error for a run submitted to an application whose auto-start is off nor the one for a run on a terminated application; Floci answers both with `ValidationException`. The same holds for a `BATCH` timeout outside 1 to 10080 minutes on `emr-7.11.0` or later (`ValidationException`) and for `GetJobRun` naming an attempt a run never made (`ResourceNotFoundException`), both in Floci's own wording. A run needs a `jobDriver`, as every `JobRun` carries one, and `jobDriver` is a union, so a run without a driver, or with one that sets both `sparkSubmit` and `hive` or neither, is refused with `ValidationException` too, in Floci's own wording.
* **StopApplication with running jobs**: AWS requires running jobs to finish or be cancelled before an application stops. Floci does not enforce it; with the default duration of `0` no `BATCH` run is ever running.
* **Not emulated**: the "EMR Serverless Job Run Retry" event, as Floci sends no EMR Serverless events, queuing (`QUEUED`), `totalResourceUtilization` and `billedResourceUtilization`, and `shutdownGracePeriodInSeconds` (accepted and ignored: a cancelled run's driver is stopped at once).
+4
View File
@@ -131,6 +131,10 @@ but for its bootstrap actions.
its own. A `spark-submit` they start runs in local mode on Floci's S3 with the cluster's
`spark-defaults`, which Floci puts in a Spark configuration of its own, ahead of the image's EMR
Serverless master; its own `--master yarn` or `--deploy-mode cluster` fails, as there is no YARN.
* **HTTPS**: with [TLS](../configuration/tls.md) on, each step's container, and the bootstrap actions'
one, also gets Floci's CA bundle as a Java trust store, which every JVM in it uses, as an
[EMR Serverless job run](emr-serverless.md#running-spark-job-runs)'s do, so Java code reaches Floci
over HTTPS too, and through AWS's own endpoint names with `FLOCI_DNS_SPOOF_AWS_ENDPOINTS`.
* **Bootstrap actions**: a cluster with `BootstrapActions` is `BOOTSTRAPPING` until they have run, one
after the other, in one container of the release's image, whatever the second half of
`cluster-startup-delay-seconds`. Each action's script is read from Floci's S3 (an `s3n://` or `s3a://`
@@ -9,8 +9,10 @@ import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -36,7 +38,9 @@ import java.util.concurrent.atomic.AtomicBoolean;
* is what makes it safe to point the <em>replacing</em> variables ({@code SSL_CERT_FILE},
* {@code CURL_CA_BUNDLE}, {@code REQUESTS_CA_BUNDLE}) at it: the workload still reaches public
* HTTPS endpoints. {@code NODE_EXTRA_CA_CERTS} appends to Node's roots and {@code AWS_CA_BUNDLE}
* only applies to AWS SDK and CLI traffic, so both are harmless with the same file.
* only applies to AWS SDK and CLI traffic, so both are harmless with the same file. The JVM reads none
* of them, so the same certificates also go in a PKCS12 trust store, which a launcher whose workload is
* Java copies in beside the bundle and points its JVMs at.
*
* <p>Written by {@link TlsConfigSource} at boot; copied into containers by the Docker lifecycle
* manager and mounted from a ConfigMap by the Kubernetes Lambda launcher. Plain class because the
@@ -53,6 +57,25 @@ public final class ContainerCaBundle {
static final List<String> ENV_KEYS = List.of(
"SSL_CERT_FILE", "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "NODE_EXTRA_CA_CERTS", "AWS_CA_BUNDLE");
public static final String JAVA_TRUST_STORE_FILE_NAME = "floci-ca-bundle.p12";
public static final String JAVA_TRUST_STORE_PATH = CONTAINER_DIR + "/" + JAVA_TRUST_STORE_FILE_NAME;
/**
* The JVM option that makes a JVM trust what the trust store at {@link #JAVA_TRUST_STORE_PATH} holds: its
* path alone, as the store needs no password and the JVM reads it whatever store type it is told. A store a
* job or an image names then replaces Floci's whole, and its own type and password, or none, apply to it.
*/
public static final String JAVA_TRUST_OPTIONS = "-Djavax.net.ssl.trustStore=" + JAVA_TRUST_STORE_PATH;
/**
* A shell line after which every JVM the shell starts trusts the bundle, through {@code JAVA_TOOL_OPTIONS},
* when the trust store is in the container, and only then, so a container without it keeps the image's
* trust. Options already in {@code JAVA_TOOL_OPTIONS} come after Floci's, so a trust store of their own
* wins.
*/
public static final String JAVA_TRUST_SHELL_LINE = "if [ -r " + JAVA_TRUST_STORE_PATH + " ]; then"
+ " export JAVA_TOOL_OPTIONS=\"" + JAVA_TRUST_OPTIONS + "${JAVA_TOOL_OPTIONS:+ $JAVA_TOOL_OPTIONS}\"; fi";
/** A missing bundle is a boot-time condition, so it is worth one WARN per process, not one per container. */
private static final AtomicBoolean MISSING_BUNDLE_WARNED = new AtomicBoolean();
@@ -87,21 +110,26 @@ public final class ContainerCaBundle {
pem.append(toPem(anchor));
}
Files.createDirectories(tlsDir);
Path target = tlsDir.resolve(FILE_NAME);
Path temp = tlsDir.resolve(FILE_NAME + "." + UUID.randomUUID() + ".tmp");
try {
Files.writeString(temp, pem.toString());
Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
} catch (AtomicMoveNotSupportedException e) {
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING);
} finally {
Files.deleteIfExists(temp);
}
Path target = replace(tlsDir.resolve(FILE_NAME), pem.toString().getBytes(StandardCharsets.UTF_8));
LOG.debugv("TLS: container CA bundle {0} holds {1} public roots and {2} Floci anchor(s)",
target, roots.size(), anchors.size());
return target;
}
/**
* Writes the certificates of {@code bundle}, the file {@link #write} returned, to a PKCS12 trust store
* beside it, {@code floci-ca-bundle.p12}, which a JVM given {@link #JAVA_TRUST_OPTIONS} trusts, swapped in
* as the bundle is. It has no password, so its certificates are neither encrypted nor under a MAC, and a
* JVM reads them with no password or any.
*
* @throws CertificateException when the bundle holds no certificate
*/
public static Path writeJavaTrustStore(Path bundle) throws IOException, GeneralSecurityException {
ByteArrayOutputStream content = new ByteArrayOutputStream();
trustStore(bundle).store(content, null);
return replace(bundle.resolveSibling(JAVA_TRUST_STORE_FILE_NAME), content.toByteArray());
}
/**
* The bundle on the Floci host, or empty when TLS is off or the boot did not manage to write
* it. Looks in the directory the bootstrap used, next to the CA.
@@ -124,6 +152,18 @@ public final class ContainerCaBundle {
return Optional.of(bundle);
}
/**
* The trust store {@link #writeJavaTrustStore} wrote on the Floci host, or empty when TLS is off or the
* boot did not manage to write it.
*/
public static Optional<Path> javaTrustStoreHostPath(EmulatorConfig config) {
if (!config.tls().enabled()) {
return Optional.empty();
}
Path trustStore = FlociCertificateAuthorityProducer.tlsDir(config).resolve(JAVA_TRUST_STORE_FILE_NAME);
return Files.isReadable(trustStore) ? Optional.of(trustStore) : Optional.empty();
}
/**
* The certificate blocks of a PEM text, re-encoded one after the other; a private key or any
* other PEM object in the text is dropped. What Floci hands out from a user-provided certificate
@@ -189,6 +229,13 @@ public final class ContainerCaBundle {
/** The trust managers of {@link #sslContext(Path)}, over exactly the certificates in {@code bundle}. */
static TrustManager[] trustManagers(Path bundle) throws IOException, GeneralSecurityException {
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(trustStore(bundle));
return factory.getTrustManagers();
}
/** A PKCS12 key store of exactly the certificates in {@code bundle}, each a trusted entry. */
private static KeyStore trustStore(Path bundle) throws IOException, GeneralSecurityException {
List<X509Certificate> certificates = parseCertificates(Files.readString(bundle));
if (certificates.isEmpty()) {
throw new CertificateException(bundle + " holds no certificate");
@@ -198,9 +245,21 @@ public final class ContainerCaBundle {
for (int i = 0; i < certificates.size(); i++) {
trustStore.setCertificateEntry("anchor-" + i, certificates.get(i));
}
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(trustStore);
return factory.getTrustManagers();
return trustStore;
}
/** Puts {@code content} at {@code target} through a temporary file swapped in, as {@link #write} says. */
private static Path replace(Path target, byte[] content) throws IOException {
Path temp = target.resolveSibling(target.getFileName() + "." + UUID.randomUUID() + ".tmp");
try {
Files.write(temp, content);
Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
} catch (AtomicMoveNotSupportedException e) {
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING);
} finally {
Files.deleteIfExists(temp);
}
return target;
}
/** Every trust anchor the running JVM accepts by default. */
@@ -417,15 +417,23 @@ public class TlsConfigSource implements ConfigSource {
}
/**
* Containers Floci launches get this bundle copied in (Docker) or mounted (Kubernetes). A
* failure here must not stop Floci: log it, and containers simply will not trust Floci HTTPS
* until a boot manages to write it.
* Containers Floci launches get this bundle copied in (Docker) or mounted (Kubernetes), and
* those whose workload is Java its trust store too. A failure here must not stop Floci: log it,
* and containers simply will not trust Floci HTTPS until a boot manages to write it.
*/
private static void writeContainerCaBundle(Path tlsDir, Path trustAnchor) {
Path bundle;
try {
ContainerCaBundle.write(tlsDir, trustAnchor);
bundle = ContainerCaBundle.write(tlsDir, trustAnchor);
} catch (Exception e) {
LOG.warnv(e, "TLS: could not write the container CA bundle under {0}: {1}", tlsDir, e.getMessage());
return;
}
try {
ContainerCaBundle.writeJavaTrustStore(bundle);
} catch (Exception e) {
LOG.warnv(e, "TLS: could not write the containers' Java trust store under {0}: {1}", tlsDir,
e.getMessage());
}
}
@@ -34,6 +34,7 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.Closeable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
@@ -367,10 +368,7 @@ public class ContainerLifecycleManager {
*/
private boolean copyCaBundle(String containerId, Path bundle) {
try {
byte[] content = Files.readAllBytes(bundle);
RetryingTarCopier.copyBytes(dockerClient, containerId, ContainerCaBundle.CONTAINER_DIR,
ContainerCaBundle.FILE_NAME, content, 0644,
RetryingTarCopier.DEFAULT_MAX_ATTEMPTS, archiveRetryBackoffMillis);
copyIntoContainerDir(containerId, bundle, ContainerCaBundle.FILE_NAME);
LOG.debugv("Copied the CA bundle into container {0} at {1}", containerId, ContainerCaBundle.CONTAINER_PATH);
return true;
} catch (Exception e) {
@@ -381,6 +379,35 @@ public class ContainerLifecycleManager {
}
}
/**
* Copies the CA bundle's Java trust store into {@code containerId}, before it starts, at
* {@link ContainerCaBundle#JAVA_TRUST_STORE_PATH}, for a container whose JVMs are then pointed at
* it, as {@link ContainerCaBundle#JAVA_TRUST_SHELL_LINE} does. Returns whether it is there: false
* when TLS is off, the boot wrote no trust store, or the copy failed, which is logged; the JVMs then
* keep the image's trust store.
*/
public boolean copyJavaTrustStore(String containerId) {
Optional<Path> trustStore = ContainerCaBundle.javaTrustStoreHostPath(config);
if (trustStore.isEmpty()) {
return false;
}
try {
copyIntoContainerDir(containerId, trustStore.get(), ContainerCaBundle.JAVA_TRUST_STORE_FILE_NAME);
return true;
} catch (Exception e) {
LOG.warnv("Could not copy the Java trust store into container {0}, whose JVMs keep the image's trust"
+ " store and will not trust Floci HTTPS: {1}", containerId, e.getMessage());
return false;
}
}
// Copies a file of the CA bundle's to the container's ContainerCaBundle.CONTAINER_DIR as name, readable by
// any user, so a non-root USER can read it.
private void copyIntoContainerDir(String containerId, Path file, String name) throws IOException {
RetryingTarCopier.copyBytes(dockerClient, containerId, ContainerCaBundle.CONTAINER_DIR, name,
Files.readAllBytes(file), 0644, RetryingTarCopier.DEFAULT_MAX_ATTEMPTS, archiveRetryBackoffMillis);
}
/**
* Confirms a name-conflicting container is the one THIS create() call produced, not a stale or
* differently-owned container, and not one from a genuinely concurrent create() sharing the same
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.emr;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.Image;
import io.github.hectorvent.floci.config.ContainerCaBundle;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
@@ -47,7 +48,8 @@ import java.util.zip.GZIPOutputStream;
* runs its command as it is, and what it leaves in that home is the {@code hadoop} user's. Each action's
* script is read from Floci's S3 as the cluster's account and runs through {@code docker exec}, with the
* credentials of the cluster's EC2 instance profile in its environment alone, so that they never become
* part of the image.
* part of the image. With TLS on, the JVMs an action starts trust Floci's CA, through the Java trust store
* copied in once the container is up, which goes before the image is kept.
*/
@ApplicationScoped
public class EmrBootstrapRunner implements BootstrapRunner, ContainerTeardown {
@@ -71,8 +73,10 @@ public class EmrBootstrapRunner implements BootstrapRunner, ContainerTeardown {
" esac",
"done",
"exec env \"$@\"");
// What each action runs as root: $1 is its script, and the rest that script's arguments.
// What each action runs as root: $1 is its script, and the rest that script's arguments. The JVMs it starts
// trust Floci's CA once the container has its trust store.
private static final String ACTION_COMMAND = String.join("\n",
ContainerCaBundle.JAVA_TRUST_SHELL_LINE,
"mkdir -p /tmp/floci-bin",
"cat > /tmp/floci-bin/sudo <<'SUDO'",
SUDO,
@@ -87,9 +91,10 @@ public class EmrBootstrapRunner implements BootstrapRunner, ContainerTeardown {
"code=$?",
"chown -R hadoop:hadoop /home/hadoop",
"exit $code");
// Run once every action has: what only the actions needed goes before the image is kept.
private static final String CLEANUP_COMMAND = "rm -f /tmp/floci-bin/sudo /tmp/floci-bootstrap-action-*;"
+ " rmdir /tmp/floci-bin";
// Run once every action has: what only the actions needed goes before the image is kept, the trust store
// included, which each step's container gets afresh.
private static final String CLEANUP_COMMAND = "rm -f /tmp/floci-bin/sudo /tmp/floci-bootstrap-action-* "
+ ContainerCaBundle.JAVA_TRUST_STORE_PATH + "; rmdir /tmp/floci-bin";
// The bootstraps inside run(); a stop for one not here comes after its container has gone, and is dropped.
private final ContainerLaunches launches = new ContainerLaunches();
@@ -136,7 +141,9 @@ public class EmrBootstrapRunner implements BootstrapRunner, ContainerTeardown {
.build();
String containerId = lifecycleManager.createAndStart(spec).containerId();
launch.started(containerId);
// A stop, a reset or a shutdown while the image was pulled is read now the container is up.
// In before the first action, for the actions' JVMs to find it.
lifecycleManager.copyJavaTrustStore(containerId);
// A stop, a reset or a shutdown while the image was pulled or the trust store copied is read now.
if (launch.stopRequested() || cancelled.getAsBoolean()) {
return Outcome.halted();
}
@@ -5,6 +5,7 @@ import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import io.github.hectorvent.floci.config.ContainerCaBundle;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.common.RequestScopes;
@@ -45,9 +46,10 @@ import java.util.zip.GZIPOutputStream;
* supplies at run time, which the public image lacks, so the runner starts {@code spark-submit} itself,
* in local mode: the container holds the driver and its executors. The container reaches Floci as the
* other containers Floci launches do, with the run's execution role as its credentials, and S3A, which
* takes {@code s3://} on every release, is pointed at Floci's S3. The driver's output goes to Floci's log and,
* while it runs, to the run's CloudWatch log streams, when it has some; once it ends, its standard output
* and error go, gzipped, to the run's log folder in Floci's S3, when it has one.
* takes {@code s3://} on every release, is pointed at Floci's S3. With TLS on, every JVM in the container
* trusts Floci's CA, through the Java trust store copied in before it starts. The driver's output goes to
* Floci's log and, while it runs, to the run's CloudWatch log streams, when it has some; once it ends, its
* standard output and error go, gzipped, to the run's log folder in Floci's S3, when it has one.
*/
@ApplicationScoped
public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardown {
@@ -55,11 +57,17 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
private static final Logger LOG = Logger.getLogger(EmrServerlessSparkRunner.class);
private static final String SPARK_SUBMIT = "/usr/lib/spark/bin/spark-submit";
private static final String SPARK_DEFAULTS_VARIABLE = "FLOCI_SPARK_DEFAULTS";
// spark-submit runs after this, its JVMs trusting Floci's CA once its trust store is in the container.
private static final String SPARK_SUBMIT_WRAPPER = String.join("\n",
ContainerCaBundle.JAVA_TRUST_SHELL_LINE,
"exec \"$@\"");
// A command runs after this sets up a Spark configuration of its own, so a spark-submit it starts runs
// locally on Floci's S3: the image's spark-defaults.conf names EMR Serverless's resource manager as its
// master, which a system property cannot override, so its master and that manager's lines give way to
// local mode, Floci's settings and the job's spark-defaults, passed in SPARK_DEFAULTS_VARIABLE.
// local mode, Floci's settings and the job's spark-defaults, passed in SPARK_DEFAULTS_VARIABLE. Its JVMs
// trust Floci's CA as spark-submit's do.
private static final String COMMAND_WRAPPER = String.join("\n",
ContainerCaBundle.JAVA_TRUST_SHELL_LINE,
"conf=/tmp/floci-spark-conf",
"mkdir -p \"$conf\"",
"cp -r /usr/lib/spark/conf/. \"$conf\" 2>/dev/null",
@@ -141,10 +149,12 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
image(job.imageTemplate(), job.releaseLabel()))
.withName(ContainerStorageHelper.dockerName(config, job.service() + "-" + job.runId()))
.withEnv(awsEnv.sdkBaselineEnv(job.region(), Optional.empty(), credentials, job.accountId()));
// bash -c's script gets "floci" as its $0, and spark-submit or the command as its arguments, "$@".
if (job.command() == null) {
container.withEntrypoint(List.of(SPARK_SUBMIT)).withCmd(sparkSubmitArguments(job, endpoint));
List<String> submit = new ArrayList<>(List.of(SPARK_SUBMIT));
submit.addAll(sparkSubmitArguments(job, endpoint));
container.withEntrypoint(List.of("/bin/bash", "-c", SPARK_SUBMIT_WRAPPER, "floci")).withCmd(submit);
} else {
// bash -c's script gets "floci" as its $0, and the command as its arguments, "$@".
container.withEntrypoint(List.of("/bin/bash", "-c", COMMAND_WRAPPER, "floci"))
.withCmd(job.command())
.withEnv(SPARK_DEFAULTS_VARIABLE, sparkDefaultsFile(job, endpoint));
@@ -156,12 +166,16 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
.withLogRotation()
.withLabels(labels)
.build();
String containerId = lifecycleManager.createAndStart(spec).containerId();
String containerId = lifecycleManager.create(spec);
launch.started(containerId);
// A stop, a reset or a shutdown while the image was pulled is read now the driver has a container.
// In before the driver starts, for its JVMs to find it.
lifecycleManager.copyJavaTrustStore(containerId);
// A stop, a reset or a shutdown while the image was pulled or the trust store copied is read now,
// before the driver starts.
if (launch.stopRequested() || progress.cancelled()) {
return Outcome.halted();
}
lifecycleManager.startCreated(containerId, spec);
logHandle = attachLog(containerId, job);
progress.started();
Outcome outcome = awaitEnd(containerId, job, launch, progress);
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.config;
import io.github.hectorvent.floci.core.common.Pem;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import io.github.hectorvent.floci.services.lambda.launcher.BootstrapProcess;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -12,6 +13,8 @@ import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.GeneralSecurityException;
@@ -21,8 +24,12 @@ import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -260,6 +267,137 @@ class ContainerCaBundleTest {
assertEquals(ContainerCaBundle.env(), ContainerCaBundle.appendEnv(List.of()));
}
@Test
void theJavaTrustStoreHoldsEveryCertificateOfTheBundleAsATrustedEntry() throws Exception {
Path tlsDir = tempDir.resolve("tls");
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);
Path bundle = ContainerCaBundle.write(tlsDir, ca.certificatePath());
Path trustStore = ContainerCaBundle.writeJavaTrustStore(bundle);
assertEquals(tlsDir.resolve("floci-ca-bundle.p12"), trustStore);
// Loaded as a JVM given only its path loads it: the default store type, and no password.
assertEquals("-Djavax.net.ssl.trustStore=/etc/floci-ca-bundle.p12", ContainerCaBundle.JAVA_TRUST_OPTIONS);
KeyStore loaded = KeyStore.getInstance(KeyStore.getDefaultType());
try (InputStream in = Files.newInputStream(trustStore)) {
loaded.load(in, null);
}
List<X509Certificate> held = new ArrayList<>();
for (String alias : Collections.list(loaded.aliases())) {
assertTrue(loaded.isCertificateEntry(alias), alias + " is a trusted certificate");
held.add((X509Certificate) loaded.getCertificate(alias));
}
assertEquals(Set.copyOf(parseAll(Files.readAllBytes(bundle))), Set.copyOf(held));
assertTrue(held.contains(ca.certificate()), "Floci's anchor");
try (Stream<Path> files = Files.list(tlsDir)) {
assertTrue(files.noneMatch(file -> file.getFileName().toString().endsWith(".tmp")),
"no temp file left behind");
}
}
@Test
void javaTrustStoreHostPathIsEmptyUntilTheBootWritesIt() throws Exception {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.tls().enabled()).thenReturn(true);
when(config.storage().persistentPath()).thenReturn(tempDir.toString());
Path tlsDir = tempDir.resolve("tls");
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);
Path bundle = ContainerCaBundle.write(tlsDir, ca.certificatePath());
assertEquals(Optional.empty(), ContainerCaBundle.javaTrustStoreHostPath(config));
Path trustStore = ContainerCaBundle.writeJavaTrustStore(bundle);
assertEquals(Optional.of(trustStore), ContainerCaBundle.javaTrustStoreHostPath(config));
when(config.tls().enabled()).thenReturn(false);
assertEquals(Optional.empty(), ContainerCaBundle.javaTrustStoreHostPath(config));
}
@Test
void theShellLinePointsTheJvmsAtTheTrustStoreOnlyWhenItIsThere() throws Exception {
Path trustStore = Files.writeString(tempDir.resolve("floci-ca-bundle.p12"), "trust store");
String line = ContainerCaBundle.JAVA_TRUST_SHELL_LINE
.replace(ContainerCaBundle.JAVA_TRUST_STORE_PATH, trustStore.toString());
String options = ContainerCaBundle.JAVA_TRUST_OPTIONS
.replace(ContainerCaBundle.JAVA_TRUST_STORE_PATH, trustStore.toString());
assertEquals(options, javaToolOptionsAfter(line, null));
// Options already there come after Floci's, so a trust store of their own wins.
assertEquals(options + " -Djavax.net.ssl.trustStore=/own.p12",
javaToolOptionsAfter(line, "-Djavax.net.ssl.trustStore=/own.p12"));
Files.delete(trustStore);
assertEquals("unset", javaToolOptionsAfter(line, null));
assertEquals("-Xss2m", javaToolOptionsAfter(line, "-Xss2m"));
}
@Test
void aJvmTrustsTheStoreByItsPathAloneAndAStoreAJobNamesReplacesItWhole() throws Exception {
Path tlsDir = tempDir.resolve("tls");
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);
Path bundle = ContainerCaBundle.write(tlsDir, ca.certificatePath());
String line = ContainerCaBundle.JAVA_TRUST_SHELL_LINE.replace(ContainerCaBundle.JAVA_TRUST_STORE_PATH,
ContainerCaBundle.writeJavaTrustStore(bundle).toString());
int bundled = Set.copyOf(parseAll(Files.readAllBytes(bundle))).size();
// A job's own store, under a password of its own, which it names by its path alone.
Path own = tempDir.resolve("own.jks");
KeyStore ownStore = KeyStore.getInstance("JKS");
ownStore.load(null, null);
ownStore.setCertificateEntry("own", ca.certificate());
try (OutputStream out = Files.newOutputStream(own)) {
ownStore.store(out, "s3cret".toCharArray());
}
assertEquals(bundled, anchorsTrustedAfter(line, null));
assertEquals(1, anchorsTrustedAfter(line, "-Djavax.net.ssl.trustStore=" + own));
// A password or a type a job gives for the JDK's own store still reads Floci's.
assertEquals(bundled, anchorsTrustedAfter(line, "-Djavax.net.ssl.trustStorePassword=changeit"));
assertEquals(bundled, anchorsTrustedAfter(line, "-Djavax.net.ssl.trustStoreType=JKS"));
}
/** Run in a JVM of its own: prints how many anchors that JVM trusts by default, as its options say. */
public static final class TrustedAnchors {
public static void main(String[] args) throws GeneralSecurityException {
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init((KeyStore) null);
int anchors = 0;
for (TrustManager manager : factory.getTrustManagers()) {
if (manager instanceof X509TrustManager x509) {
anchors += x509.getAcceptedIssuers().length;
}
}
System.out.println("trusted anchors " + anchors);
}
}
// JAVA_TOOL_OPTIONS as a shell that ran line leaves it, starting from existing, or from none when null.
private static String javaToolOptionsAfter(String line, String existing) throws Exception {
return runAfter(line, existing, "printf %s \"${JAVA_TOOL_OPTIONS-unset}\"");
}
// How many anchors a JVM a shell starts after line trusts, JAVA_TOOL_OPTIONS starting as javaToolOptionsAfter's.
private static int anchorsTrustedAfter(String line, String existing) throws Exception {
String java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
String classes = Path.of(TrustedAnchors.class.getProtectionDomain().getCodeSource().getLocation().toURI())
.toString();
String output = runAfter(line, existing, "exec \"$@\"", java, "-cp", classes, TrustedAnchors.class.getName());
Matcher anchors = Pattern.compile("trusted anchors (\\d+)").matcher(output);
assertTrue(anchors.find(), output);
return Integer.parseInt(anchors.group(1));
}
// What script, run by a shell after line with arguments as "$@", prints, JAVA_TOOL_OPTIONS starting from
// existing, or from none when null.
private static String runAfter(String line, String existing, String script, String... arguments) throws Exception {
List<String> command = new ArrayList<>(List.of("bash", "-c", line + "\n" + script, "floci"));
command.addAll(List.of(arguments));
ProcessBuilder shell = new ProcessBuilder(command);
shell.environment().remove("JAVA_TOOL_OPTIONS");
if (existing != null) {
shell.environment().put("JAVA_TOOL_OPTIONS", existing);
}
BootstrapProcess.Result ended = BootstrapProcess.run(shell);
assertEquals(0, ended.exit(), ended.output());
return ended.output();
}
private static List<X509Certificate> parseAll(byte[] pem) throws Exception {
List<X509Certificate> certificates = new ArrayList<>();
for (Certificate certificate : CertificateFactory.getInstance("X.509").generateCertificates(new ByteArrayInputStream(pem))) {
@@ -47,6 +47,21 @@ class TlsConfigSourceContainerCaBundleTest {
assertTrue(pem.endsWith(caPem), "the local CA is the last entry");
assertTrue(pem.indexOf("-----BEGIN CERTIFICATE-----") < pem.lastIndexOf("-----BEGIN CERTIFICATE-----"),
"public roots precede the CA");
assertTrue(Files.isRegularFile(tempDir.resolve("tls/floci-ca-bundle.p12")), "Java trust store written at boot");
}
@Test
void aJavaTrustStoreThatCannotBeWrittenLeavesTheBundleAndTheBoot() throws Exception {
// A directory where the trust store goes, with something in it, so it cannot be replaced.
Files.writeString(Files.createDirectories(tempDir.resolve("tls/floci-ca-bundle.p12")).resolve("x"), "x");
System.setProperty("floci.tls.enabled", "true");
System.setProperty("floci.tls.self-signed", "true");
System.setProperty("floci.storage.persistent-path", tempDir.toString());
new TlsConfigSource();
assertTrue(Files.isRegularFile(tempDir.resolve("tls/floci-ca-bundle.pem")), "bundle written at boot");
assertTrue(Files.isDirectory(tempDir.resolve("tls/floci-ca-bundle.p12")), "the boot left the obstacle alone");
}
@Test
@@ -36,6 +36,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
@@ -270,20 +271,70 @@ class ContainerLifecycleManagerCaBundleTest {
verify(dockerClient, times(1)).copyArchiveToContainerCmd(anyString());
}
@Test
void theJavaTrustStoreIsCopiedBesideTheBundleWhenALauncherAsks() throws Exception {
when(tlsConfig.enabled()).thenReturn(true);
byte[] trustStore = {0x30, (byte) 0x82, 0x01, 0x02};
Files.write(Files.createDirectories(tempDir.resolve("tls")).resolve("floci-ca-bundle.p12"), trustStore);
CopyArchiveToContainerCmd copyCmd = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
when(dockerClient.copyArchiveToContainerCmd("container-id")).thenReturn(copyCmd);
List<InputStream> streams = new ArrayList<>();
when(copyCmd.withTarInputStream(any(InputStream.class))).thenAnswer(invocation -> {
streams.add(invocation.getArgument(0));
return copyCmd;
});
when(copyCmd.exec()).thenAnswer(invocation -> {
assertSingleFileArchive(streams.getLast(), "floci-ca-bundle.p12", trustStore);
return null;
});
assertTrue(manager().copyJavaTrustStore("container-id"));
verify(copyCmd).withRemotePath("/etc");
verify(copyCmd).exec();
}
@Test
void noJavaTrustStoreIsCopiedWithTlsOffOrWithoutOneFromTheBoot() throws Exception {
when(tlsConfig.enabled()).thenReturn(true);
writeBundle();
assertFalse(manager().copyJavaTrustStore("container-id"), "the boot wrote no trust store");
Files.write(tempDir.resolve("tls").resolve("floci-ca-bundle.p12"), new byte[] {1});
when(tlsConfig.enabled()).thenReturn(false);
assertFalse(manager().copyJavaTrustStore("container-id"), "TLS is off");
verify(dockerClient, never()).copyArchiveToContainerCmd(anyString());
}
@Test
void aJavaTrustStoreThatCannotBeCopiedIsReportedMissing() throws Exception {
when(tlsConfig.enabled()).thenReturn(true);
Files.write(Files.createDirectories(tempDir.resolve("tls")).resolve("floci-ca-bundle.p12"), new byte[] {1});
CopyArchiveToContainerCmd copyCmd = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
when(dockerClient.copyArchiveToContainerCmd("container-id")).thenReturn(copyCmd);
when(copyCmd.exec()).thenThrow(new NotFoundException("Could not find the file /etc in container"));
assertFalse(manager().copyJavaTrustStore("container-id"));
}
private Path writeBundle() throws Exception {
Path tlsDir = Files.createDirectories(tempDir.resolve("tls"));
return Files.writeString(tlsDir.resolve("floci-ca-bundle.pem"), BUNDLE_PEM);
}
private static void assertBundleArchive(InputStream stream) throws IOException {
assertSingleFileArchive(stream, "floci-ca-bundle.pem", BUNDLE_PEM.getBytes(StandardCharsets.UTF_8));
}
private static void assertSingleFileArchive(InputStream stream, String name, byte[] content) throws IOException {
byte[] archive = stream.readAllBytes();
try (TarArchiveInputStream in = new TarArchiveInputStream(new ByteArrayInputStream(archive))) {
TarArchiveEntry entry = in.getNextEntry();
assertNotNull(entry, "every attempt must begin with a complete tar header");
assertEquals("floci-ca-bundle.pem", entry.getName());
assertEquals(name, entry.getName());
assertEquals(0644, entry.getMode() & 0777, "world-readable, so a non-root USER can read it");
assertArrayEquals(BUNDLE_PEM.getBytes(StandardCharsets.UTF_8), in.readAllBytes());
assertNull(in.getNextEntry(), "the archive holds only the bundle");
assertArrayEquals(content, in.readAllBytes());
assertNull(in.getNextEntry(), "the archive holds only " + name);
}
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.emr;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.ExecCreateCmd;
import com.github.dockerjava.api.model.Image;
import io.github.hectorvent.floci.config.ContainerCaBundle;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
@@ -23,6 +24,7 @@ import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -142,6 +144,26 @@ class EmrBootstrapRunnerTest {
verify(lifecycle).stopAndRemove(CONTAINER, null, 0);
}
@Test
void theActionsJvmsTrustFlocisCaWhoseTrustStoreIsNotKeptInTheImage() {
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, CONTAINER, 0, "", "");
List<Integer> execsBeforeTheCopy = new ArrayList<>();
when(lifecycle.copyJavaTrustStore(CONTAINER)).thenAnswer(copy -> {
execsBeforeTheCopy.add(commands.size());
return true;
});
runner.run(bootstrap(null, action("s3://bucket/bootstrap/install.sh")), () -> false);
// In once the container is up, before the first action runs, which points its JVMs at it.
assertEquals(List.of(0), execsBeforeTheCopy);
assertTrue(commands.get(0).get(2).startsWith(ContainerCaBundle.JAVA_TRUST_SHELL_LINE + "\n"));
// Each step's container gets its own, so the image goes without it.
assertEquals(2, commands.size());
assertTrue(commands.get(1).get(2).contains("rm -f ") && commands.get(1).get(2).contains(
" " + ContainerCaBundle.JAVA_TRUST_STORE_PATH + ";"), commands.get(1).get(2));
}
@Test
void aFailingActionEndsTheBootstrapThereAndNothingIsKept() {
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, CONTAINER, List.of(0L, 3L), "", "");
@@ -202,6 +224,24 @@ class EmrBootstrapRunnerTest {
verify(lifecycle, never()).commit(any(), any(), any(), any(), any());
}
@Test
void aClusterThatEndsWhileTheTrustStoreIsCopiedRunsNoAction() {
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, CONTAINER, 0, "", "");
AtomicBoolean ended = new AtomicBoolean();
when(lifecycle.copyJavaTrustStore(CONTAINER)).thenAnswer(copy -> {
ended.set(true);
return true;
});
BootstrapRunner.Outcome outcome = runner.run(bootstrap(null, action("s3://bucket/bootstrap/install.sh")),
ended::get);
assertEquals(BootstrapRunner.Outcome.halted(), outcome);
assertTrue(commands.isEmpty());
verify(lifecycle, never()).commit(any(), any(), any(), any(), any());
verify(lifecycle).stopAndRemove(CONTAINER, null, 0);
}
@Test
void imagesOfClustersThatAreGoneAreRemovedAndTheOthersKept() {
String goneId = "sha256:" + "3".repeat(64);
@@ -6,6 +6,7 @@ import com.github.dockerjava.api.exception.InternalServerErrorException;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import io.github.hectorvent.floci.config.ContainerCaBundle;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
@@ -135,7 +136,12 @@ class EmrServerlessSparkRunnerTest {
runner(builder).run(job(Duration.ZERO), progress);
verify(builder).newContainer("public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest");
verify(spec).withEntrypoint(List.of("/usr/lib/spark/bin/spark-submit"));
// bash -c runs Floci's wrapper with "floci" as its $0 and spark-submit and its arguments as "$@".
verify(spec).withEntrypoint(List.of("/bin/bash", "-c",
ContainerCaBundle.JAVA_TRUST_SHELL_LINE + "\nexec \"$@\"", "floci"));
verify(spec).withCmd(argThat((List<String> cmd) -> "/usr/lib/spark/bin/spark-submit".equals(cmd.getFirst())
&& List.of("--master", "local[*]").equals(cmd.subList(1, 3))
&& "s3://bucket/jobs/app.jar".equals(cmd.getLast())));
verify(spec).withName(ContainerStorageHelper.dockerName(config, "emr-serverless-00f0000000000001"));
verify(spec).withDockerNetwork(Optional.of("floci-network"));
verify(spec).withLabels(argThat(labels ->
@@ -154,13 +160,23 @@ class EmrServerlessSparkRunnerTest {
// bash -c runs Floci's wrapper with "floci" as its $0 and the command as "$@".
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.size() == 4
&& entrypoint.subList(0, 2).equals(List.of("/bin/bash", "-c"))
&& entrypoint.get(2).startsWith(ContainerCaBundle.JAVA_TRUST_SHELL_LINE + "\n")
&& entrypoint.get(2).contains("export SPARK_CONF_DIR=") && entrypoint.get(2).endsWith("exec \"$@\"")
&& "floci".equals(entrypoint.get(3))));
verify(spec).withCmd(command);
verify(spec).withEnv(eq("FLOCI_SPARK_DEFAULTS"),
argThat(file -> file.startsWith("spark.master local[*]\n")
&& file.endsWith("\nspark.executor.cores 4")));
verify(spec, never()).withEntrypoint(List.of("/usr/lib/spark/bin/spark-submit"));
}
@Test
void theJavaTrustStoreGoesIntoTheDriversContainerBeforeItStarts() {
runner().run(job(Duration.ZERO), progress);
InOrder order = inOrder(lifecycle);
order.verify(lifecycle).create(any());
order.verify(lifecycle).copyJavaTrustStore("driver");
order.verify(lifecycle).startCreated(eq("driver"), any());
}
@Test
@@ -210,7 +226,7 @@ class EmrServerlessSparkRunnerTest {
assertNull(outcome.exitCode());
assertNotNull(outcome.failure());
verify(lifecycle, never()).createAndStart(any());
verify(lifecycle, never()).create(any());
}
@Test
@@ -243,15 +259,16 @@ class EmrServerlessSparkRunnerTest {
@Test
void aResetWhileTheImageIsPulledStopsTheRunOnceItsContainerIsUp() {
EmrServerlessSparkRunner runner = runner();
when(lifecycle.createAndStart(any())).thenAnswer(pulling -> {
when(lifecycle.create(any())).thenAnswer(pulling -> {
runner.stopManagedContainers();
return new ContainerLifecycleManager.ContainerInfo("driver", Map.of());
return "driver";
});
SparkJobRunner.Outcome outcome = runner.run(job(Duration.ZERO), progress);
assertTrue(outcome.stopped());
verify(progress, never()).started();
verify(lifecycle, never()).startCreated(anyString(), any());
verify(lifecycle).stopAndRemove("driver", null, 0);
}
@@ -265,6 +282,43 @@ class EmrServerlessSparkRunnerTest {
assertTrue(outcome.stopped());
verify(progress, never()).started();
verify(lifecycle, never()).startCreated(anyString(), any());
verify(lifecycle).stopAndRemove("driver", null, 0);
}
@Test
void aRunStoppedWhileTheTrustStoreIsCopiedNeverStartsItsDriver() {
EmrServerlessSparkRunner runner = runner();
SparkJobRunner.Job job = job(Duration.ZERO);
// The copy can wait on Docker, and a stop only marks the run.
when(lifecycle.copyJavaTrustStore("driver")).thenAnswer(copy -> {
runner.stop(job.runId());
return true;
});
SparkJobRunner.Outcome outcome = runner.run(job, progress);
assertTrue(outcome.stopped());
verify(progress, never()).started();
verify(lifecycle, never()).startCreated(anyString(), any());
verify(lifecycle).stopAndRemove("driver", null, 0);
}
@Test
void aRunCancelledWhileTheTrustStoreIsCopiedNeverStartsItsDriver() {
EmrServerlessSparkRunner runner = runner();
AtomicBoolean cancelled = new AtomicBoolean();
when(progress.cancelled()).thenAnswer(look -> cancelled.get());
when(lifecycle.copyJavaTrustStore("driver")).thenAnswer(copy -> {
cancelled.set(true);
return true;
});
SparkJobRunner.Outcome outcome = runner.run(job(Duration.ZERO), progress);
assertTrue(outcome.stopped());
verify(progress, never()).started();
verify(lifecycle, never()).startCreated(anyString(), any());
verify(lifecycle).stopAndRemove("driver", null, 0);
}
@@ -480,7 +534,7 @@ class EmrServerlessSparkRunnerTest {
private EmrServerlessSparkRunner runner(ContainerBuilder builder) {
when(lifecycle.getDockerClient()).thenReturn(docker);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("driver", Map.of()));
when(lifecycle.create(any())).thenReturn("driver");
when(docker.inspectContainerCmd("driver").exec().getState().getRunning()).thenReturn(false);
when(docker.inspectContainerCmd("driver").exec().getState().getExitCodeLong()).thenReturn(0L);
return new EmrServerlessSparkRunner(builder, lifecycle, logStreamer,