feat(emr): keep a cluster's application history and open its persistent UIs for real in the docker runner mode (#8817)

With runner-mode docker, GetPersistentAppUIPresignedURL now opens the
persistent application UI's interface for real, SHS the Spark History
Server, YTS the YARN timeline server and TEZ the Tez UI, on a host of
its own as an on-cluster UI does: while the cluster runs, its primary
node's; once it has ended, as "You can access application history and
relevant log files for active and terminated clusters", its kept
history's, for the 30 days for which "The logs are available ... after
the application ends".

The primary node of a cluster that runs either history interface mounts
a volume of its own, which holds the timeline server's store (its
entities kept 30 days rather than Hadoop's 7), and into which, as the
cluster's storage goes, or as a reset or a shutdown removes a node
still running, its Spark applications' event logs are copied out of its
HDFS; the cluster's other storage goes as before, though a copy that
fails keeps it, the event logs in it, for a later try or a restart to
remove. The URL is not
PresignedURLReady while the cluster is ending or its storage is going.
Then a container of the image the cluster ran serves it, on a network
of its own that no step's container is on, started by the first link,
the URL not PresignedURLReady until it answers, and stopped once no
link to it is valid, a later link starting it again; with no
ResourceManager there, the Tez UI's asks for one go to the timeline
server. A kept history goes once its 30 days have passed, whether or
not a link asked for it. A restart keeps the histories of the clusters
that ended within 30 days, a reset or a shutdown removes the
containers, and a reset every history. Elsewhere, the link still opens
Floci's own page.

EmrAppUiNightlyIntegrationTest runs it for real: a persistent UI opens
the cluster's Spark History Server while it runs, and, once it has
ended and its storage has gone, its kept history: the Spark
application, the Hive query's Tez DAG and the Tez UI's page.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-18 01:29:25 -04:00
1 parent 8418c7e674
commit 5fa518cf10
11 files changed
+1128 -43

No files matched your search

@@ -9,6 +9,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
@@ -183,9 +184,48 @@ public interface ClusterStorage {
return Optional.empty();
}
/**
* Keeps what a cluster's history interfaces show once it has ended, before its storage goes: the Spark
* applications' event logs, copied out of its HDFS into the volume of its primary node that already holds the
* YARN timeline server's store, which outlives the cluster's other storage until {@link #removeHistoriesBut} lets
* it go: true once they are kept, or where there is nothing it can keep, the node not running or keeping no
* history; false where the copy failed, so the caller keeps the storage, which holds them, and tries again.
*/
default boolean keepHistory(String clusterId) {
return true;
}
/** Whether a cluster's history is kept. */
default boolean historyKept(String clusterId) {
return false;
}
/**
* Where Floci reaches {@code port} of the container that serves a cluster's kept history: its Spark History
* Server, YARN timeline server and Tez UI, as {@code yarn} had its primary node run them, their links naming
* {@code primaryHost}, as the node's did. Started, as {@code accountId} in {@code region}, in the image
* {@code image} gives, {@code released} told once the container is made, where it is not running; empty until it
* answers.
*/
default Optional<ContainerLifecycleManager.EndpointInfo> historyInterface(String clusterId, String accountId,
String region, Supplier<String> image,
Consumer<String> released,
String primaryHost, Yarn yarn,
int port) {
return Optional.empty();
}
/** Stops the container serving a cluster's kept history, which a later link starts again. */
default void stopHistory(String clusterId) {
}
/** Removes the kept history of every cluster but those in {@code kept}, and the container serving it. */
default void removeHistoriesBut(Set<String> kept) {
}
/**
* Removes {@code clusterId}'s HDFS and the volumes of its storage once it no longer needs them: true when the
* volumes are gone, false when Docker refused, so the caller can try again.
* volumes are gone, false when Docker refused, so the caller can try again. Its kept history stays.
*/
boolean remove(String clusterId);
@@ -17,10 +17,11 @@ import java.util.List;
/**
* The page a presigned URL of {@code GetPersistentAppUIPresignedURL} or {@code GetOnClusterAppUIPresignedURL} opens
* ({@link EmrAppUiService}). EMR opens the cluster's Spark History Server, Tez UI, YARN timeline server or on-cluster
* UI; Floci serves none of them, so the page shows the cluster as DescribeCluster gives it and which interface was
* asked for. A link that is not one of this process's, or whose hour has passed, opens a refusal instead, and so does
* one whose cluster has gone. Like the rest of Floci the page takes no AWS credentials: the link is all it asks for.
* ({@link EmrAppUiService}) for an interface Floci does not run here: EMR opens the cluster's Spark History Server,
* Tez UI, YARN timeline server or on-cluster UI, and the page shows the cluster as DescribeCluster gives it and which
* interface was asked for. A link that is not one of this process's, or whose hour has passed, opens a refusal
* instead, and so does one whose cluster has gone. Like the rest of Floci the page takes no AWS credentials: the link
* is all it asks for.
*/
@Path(EmrAppUiService.PATH)
public class EmrAppUiController {
@@ -28,8 +29,8 @@ public class EmrAppUiController {
// No source gives AWS's wording for these; they are Floci's.
static final String INVALID = "This application UI link is not valid, or its hour has passed. Call"
+ " GetPersistentAppUIPresignedURL or GetOnClusterAppUIPresignedURL for a new one.";
static final String NO_UI = "Floci serves no Spark History Server, Tez UI, YARN timeline server or on-cluster"
+ " application UI, so this page stands in for the interface EMR opens.";
static final String NO_UI = "Floci does not run this interface here, so this page stands in for the interface EMR"
+ " opens; in the docker runner mode, a cluster whose primary node runs it opens it for real.";
private final EmrAppUiService appUis;
@@ -13,8 +13,10 @@ import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrPersistentAppUi;
import io.floci.aws.services.emrserverless.EmrServerlessSparkRunner;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.net.URI;
import java.net.URLEncoder;
@@ -32,6 +34,9 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -42,9 +47,9 @@ import java.util.regex.Pattern;
* application master through it, its MapReduce JobHistory server, the NodeManager of a primary node that works, the
* Spark History Server of a cluster with Spark, or the YARN timeline server and the Tez UI of one with Hadoop and Tez,
* opens for real through {@link EmrAppUiProxy}, on a host of its own under {@link #UI_HOST}, as AWS's are under
* "emrappui-prod.us-east-1.amazonaws.com" (Management Guide, "View Amazon EMR application history"). Floci keeps a
* persistent application UI's record, but serves no persistent UI: a link to one, and to any on-cluster UI elsewhere,
* opens a page of Floci's own about the cluster
* "emrappui-prod.us-east-1.amazonaws.com" (Management Guide, "View Amazon EMR application history"). A persistent
* application UI opens the same interfaces while its cluster runs, and, for the 30 days after it ends, its kept
* history's, served by a container of its own. Any other link opens a page of Floci's own about the cluster
* ({@link EmrAppUiController}). Either link is valid for {@link #VALIDITY}: the page's is signed with a key of this
* process, and a proxied interface's host holds a secret this process gave it.
*/
@@ -62,7 +67,7 @@ public class EmrAppUiService {
// "For each AWS account, the default limit for active application UIs is 200."
static final int MAX_PERSISTENT_APP_UIS = 200;
// "The logs are available for 30 days after the application ends."
static final Duration LOGS_KEPT = Duration.ofDays(30);
static final Duration LOGS_KEPT = EmrService.HISTORY_KEPT;
// No source gives AWS's status values; Floci reports this one for every persistent application UI.
static final String ACTIVE = "ACTIVE";
/** The label under Floci's host name an on-cluster UI's own host is in. */
@@ -84,6 +89,12 @@ public class EmrAppUiService {
private static final Duration ENDPOINT_RECHECK = Duration.ofSeconds(10);
static final String NOT_READY = "The cluster's primary node is not running yet: it starts once a step runs, or a"
+ " link to one of its interfaces is asked for. Try again in a moment.";
static final String HISTORY_NOT_READY = "The cluster's kept history is starting. Try again in a moment.";
static final String HISTORY_GONE = "The history of cluster %s is no longer kept: it is kept for 30 days after the"
+ " cluster ends.";
// How long after its last link has expired the container serving a cluster's kept history is checked.
private static final Duration REAP_MARGIN = Duration.ofMinutes(1);
private static final Logger LOG = Logger.getLogger(EmrAppUiService.class);
private static final Pattern APPLICATION_ID = Pattern.compile("application_(\\d+_\\d+)");
private final AccountAwareStorageBackend<EmrPersistentAppUi> store;
@@ -95,6 +106,8 @@ public class EmrAppUiService {
// The links to proxied interfaces this process has given, by their secret, until they expire.
private final Map<String, Grant> grants = new ConcurrentHashMap<>();
private final SecureRandom random = new SecureRandom();
// Checks, as links to kept histories expire, whether the containers serving them may stop; made on first use.
private ScheduledExecutorService reaper;
@Inject
public EmrAppUiService(StorageFactory storageFactory, EmrService clusters, RegionResolver regionResolver,
@@ -201,10 +214,13 @@ public class EmrAppUiService {
}
/**
* A presigned URL to one of the persistent UI's types, by default its first, for the application asked for. It is
* ready at once, as Floci's page has nothing to prepare.
* A presigned URL to one of the persistent UI's types, by default its first, for the application asked for. In the
* docker runner mode the interface opens for real: on a cluster still running or waiting, its primary node's, as
* its on-cluster UI does; on one that has ended, for the 30 days its history is kept, the history's, served by a
* container of its own, which starts where it is not running, the URL not ready until it answers. Elsewhere it
* opens Floci's own page, ready at once, as that has nothing to prepare.
*/
public synchronized String persistentUrl(String appUiId, String type, String applicationId) {
public synchronized Presigned persistentUrl(String appUiId, String type, String applicationId) {
List<String> violations = new ArrayList<>();
EmrService.checkEnum(violations, "persistentAppUIType", type, PERSISTENT_TYPES);
if (!violations.isEmpty()) {
@@ -214,7 +230,37 @@ public class EmrAppUiService {
if (type != null && !appUi.getTypes().contains(type)) {
throw EmrService.invalid("Persistent application UI " + appUiId + " has no " + type + " interface.");
}
return url(appUi.getClusterId(), type != null ? type : appUi.getTypes().get(0), applicationId);
String asked = type != null ? type : appUi.getTypes().get(0);
// The on-cluster interface each persistent one is, which a link lands on as its own does.
String interfaceType = switch (asked) {
case "TEZ" -> TEZ_UI;
case "YTS" -> YARN_TIMELINE_SERVICE;
default -> SPARK_HISTORY_SERVER;
};
EmrCluster cluster = clusters.findDescribedCluster(appUi.getClusterId()).orElse(null);
if (cluster != null && (EmrClusterLifecycle.RUNNING.equals(cluster.getState())
|| EmrClusterLifecycle.WAITING.equals(cluster.getState()))) {
Optional<EmrService.WebInterfaces> served = clusters.webInterfaces(cluster);
Integer port = served.map(interfaces -> portOf(interfaceType, interfaces)).orElse(null);
if (port != null) {
return link(cluster, served.get(), port, landing(interfaceType, applicationId), false);
}
} else if (cluster != null) {
boolean kept = clusters.historyKept(cluster);
if (kept || clusters.historyComing(cluster)) {
EmrService.WebInterfaces history = clusters.historyInterfaces(cluster);
Integer port = portOf(interfaceType, history);
if (port != null && kept) {
return link(cluster, history, port, landing(interfaceType, applicationId), true);
}
if (port != null) {
// Not ready until its storage has gone: its primary node may still hold the timeline server's
// store, and its event logs are copied as the storage goes.
return new Presigned(url(appUi.getClusterId(), asked, applicationId), false);
}
}
}
return new Presigned(url(appUi.getClusterId(), asked, applicationId), true);
}
/** A presigned URL, and whether what it opens is ready: none for a dry run. */
@@ -251,18 +297,73 @@ public class EmrAppUiService {
if (port == null) {
return new Presigned(url(clusterId, asked, applicationId), true);
}
return link(cluster, served.get(), port, landing(asked, applicationId), false);
}
/**
* A link to the cluster's interface on {@code port}, landing on {@code landing}: its primary node's, ready once
* the node is, which starts where it is not running; or, for {@code history}, its kept history's, ready once the
* container serving it answers, which starts where it is not running, and stops once no link to it is valid.
*/
private Presigned link(EmrCluster cluster, EmrService.WebInterfaces interfaces, int port, String landing,
boolean history) {
Instant now = clock.instant();
grants.values().removeIf(grant -> !now.isBefore(grant.expires()));
String secret = secret();
grants.put(secret, new Grant(regionResolver.getAccountId(), regionResolver.getRegion(), clusterId,
served.get().primaryHost(), served.get().ports(), now.plus(VALIDITY), new ConcurrentHashMap<>()));
boolean ready = clusters.webInterface(clusterId, port).isPresent();
if (!ready) {
clusters.startPrimaryNode(clusterId);
Grant grant = new Grant(regionResolver.getAccountId(), regionResolver.getRegion(), cluster.getId(),
interfaces.primaryHost(), interfaces.ports(), now.plus(VALIDITY), new ConcurrentHashMap<>(), history);
grants.put(secret, grant);
boolean ready;
if (history) {
ready = clusters.historyInterface(cluster, port).isPresent();
reapLater(grant);
} else {
ready = clusters.webInterface(cluster.getId(), port).isPresent();
if (!ready) {
clusters.startPrimaryNode(cluster.getId());
}
}
URI base = URI.create(baseUrl);
return new Presigned(base.getScheme() + "://" + secret + "-" + port + "." + UI_HOST + "."
+ base.getRawAuthority() + landing(asked, applicationId), ready);
+ base.getRawAuthority() + landing, ready);
}
// Checks, once the link has expired, whether the container serving the cluster's kept history may stop.
private synchronized void reapLater(Grant grant) {
if (reaper == null) {
reaper = Executors.newSingleThreadScheduledExecutor(
Thread.ofPlatform().daemon().name("emr-app-ui-history").factory());
}
long delay = Duration.between(clock.instant(), grant.expires()).plus(REAP_MARGIN).toMillis();
reaper.schedule(() -> reapHistory(grant.accountId(), grant.region(), grant.clusterId()), delay,
TimeUnit.MILLISECONDS);
}
/**
* Stops the container serving a cluster's kept history once no link to it is valid, and removes the kept
* histories that have passed their 30 days; under the service's lock, as a new link is given, so one given while
* this looks does not lose the container it opens.
*/
synchronized void reapHistory(String accountId, String region, String clusterId) {
Instant now = clock.instant();
boolean linked = grants.values().stream().anyMatch(grant -> grant.history()
&& grant.clusterId().equals(clusterId) && grant.accountId().equals(accountId)
&& now.isBefore(grant.expires()));
try {
if (!linked) {
RequestScopes.runAs(accountId, region, () -> clusters.stopHistory(clusterId));
}
clusters.removeExpiredHistories();
} catch (RuntimeException e) {
LOG.warnv(e, "Could not stop the history of EMR cluster {0}: {1}", clusterId, e.getMessage());
}
}
@PreDestroy
synchronized void close() {
if (reaper != null) {
reaper.shutdownNow();
}
}
// The interface's port on the primary node, where Floci serves it: an application master's UI through the
@@ -314,7 +415,7 @@ public class EmrAppUiService {
* interfaces' ports; when it expires; and where Floci reaches each port, once found.
*/
private record Grant(String accountId, String region, String clusterId, String primaryHost, Set<Integer> ports,
Instant expires, Map<Integer, Found> endpoints) {
Instant expires, Map<Integer, Found> endpoints, boolean history) {
}
// Where Floci found a port of the cluster's own primary node's container, and when, which is asked again once
@@ -360,22 +461,28 @@ public class EmrAppUiService {
if (!grant.ports().contains(port)) {
return UiRoute.refused(404, NO_SUCH_INTERFACE);
}
// The interface is there only while its cluster runs or waits: once it ends, its node's ports are no longer
// its own.
// A live interface is there only while its cluster runs or waits, and its kept history only once it has ended,
// for its 30 days: outside them, the port found for it is no longer the cluster's own.
EmrCluster cluster = RequestScopes.callAs(grant.accountId(), grant.region(),
() -> clusters.findDescribedCluster(grant.clusterId()).orElse(null));
if (cluster == null || !EmrClusterLifecycle.RUNNING.equals(cluster.getState())
&& !EmrClusterLifecycle.WAITING.equals(cluster.getState())) {
Instant now = clock.instant();
boolean up = cluster != null && (EmrClusterLifecycle.RUNNING.equals(cluster.getState())
|| EmrClusterLifecycle.WAITING.equals(cluster.getState()));
if (!grant.history() && !up) {
return UiRoute.refused(404, String.format(CLUSTER_ENDED, grant.clusterId()));
}
Instant now = clock.instant();
if (grant.history() && (cluster == null || up || cluster.getEndDateTime() == null
|| !now.isBefore(cluster.getEndDateTime().plus(EmrService.HISTORY_KEPT)))) {
return UiRoute.refused(404, String.format(HISTORY_GONE, grant.clusterId()));
}
Found found = grant.endpoints().get(port);
if (found == null || !now.isBefore(found.at().plus(ENDPOINT_RECHECK))) {
ContainerLifecycleManager.EndpointInfo endpoint = RequestScopes.callAs(grant.accountId(), grant.region(),
() -> clusters.webInterface(grant.clusterId(), port)).orElse(null);
() -> grant.history() ? clusters.historyInterface(cluster, port)
: clusters.webInterface(grant.clusterId(), port)).orElse(null);
if (endpoint == null) {
grant.endpoints().remove(port);
return UiRoute.refused(503, NOT_READY);
return UiRoute.refused(503, grant.history() ? HISTORY_NOT_READY : NOT_READY);
}
found = new Found(endpoint, now);
grant.endpoints().put(port, found);
@@ -3,6 +3,7 @@ package io.floci.aws.services.emr;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.command.InspectVolumeResponse;
import com.github.dockerjava.api.command.ListVolumesResponse;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.ContainerNetwork;
import com.github.dockerjava.api.model.HostConfig;
@@ -50,6 +51,7 @@ import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.LongSupplier;
import java.util.function.Supplier;
@@ -159,6 +161,20 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
private static final String TEZ_UI_CONFIG = "/etc/tez-ui/conf/configs.js";
// The Tez UI's files, which an image with Tez has, one with Hive or Floci's Pig.
private static final String TEZ_UI_FILES = "/usr/lib/tez/tez-ui";
// A cluster's kept history: a volume of its primary node's, mounted here, which holds the YARN timeline server's
// store and, once the cluster has ended, its Spark applications' event logs, and which a container of its own
// serves after the cluster's other storage has gone; set where the node runs either.
static final String HISTORY_PATH = "/var/lib/floci-history";
private static final String HISTORY_COMPONENT = "emr-history";
private static final String HISTORY_VARIABLE = "FLOCI_HISTORY";
private static final String HISTORY_READY = "/tmp/floci-history-ready";
private static final String HISTORY_CONF = "/tmp/floci-history-conf";
private static final String HISTORY_EVENT_LOGS = HISTORY_PATH + "/spark-events";
private static final String HISTORY_TIMELINE = HISTORY_PATH + "/timeline";
// How long the timeline server keeps an entity, 7 days by default: "The logs are available for 30 days after the
// application ends".
private static final long TIMELINE_TTL_MS = 30L * 24 * 60 * 60 * 1000;
private static final int HISTORY_COPY_SECONDS = 120;
// Set on a primary node that runs a Spark History Server, as on a cluster with Spark; its version on its web port
// says it has started.
private static final String SPARK_HISTORY_VARIABLE = "FLOCI_SPARK_HISTORY";
@@ -233,11 +249,18 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
+ " \"<property><name>dfs.datanode.ipc.address</name>"
+ "<value>$FLOCI_HDFS_BIND:9867</value></property>\""
+ " '</configuration>' > " + HDFS_CONF + "/hdfs-site.xml",
"timeline_store=/mnt/yarn/timeline",
"if [ -n \"$" + HISTORY_VARIABLE + "\" ]; then",
" mkdir -p " + HISTORY_EVENT_LOGS + " " + HISTORY_TIMELINE + " && chown -R hadoop:hadoop " + HISTORY_PATH
+ " || exit",
" timeline_store=" + HISTORY_TIMELINE,
"fi",
"timeline=; [ -z \"$" + TIMELINE_VARIABLE + "\" ] || timeline=\"" + String.join("", List.of(
property("yarn.timeline-service.enabled", "true"),
property("yarn.timeline-service.hostname", "$FLOCI_HDFS_HOST"),
property("yarn.timeline-service.bind-host", "$FLOCI_HDFS_BIND"),
property("yarn.timeline-service.leveldb-timeline-store.path", "/mnt/yarn/timeline"),
property("yarn.timeline-service.leveldb-timeline-store.path", "$timeline_store"),
property("yarn.timeline-service.ttl-ms", String.valueOf(TIMELINE_TTL_MS)),
property("yarn.timeline-service.http-cross-origin.enabled", "true"),
property("yarn.resourcemanager.webapp.cross-origin.enabled", "true"),
// The ResourceManager publishes its applications there: Hadoop 3.4 reads the first, which
@@ -438,6 +461,77 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
+ "while [ \"$(jobs -rp | wc -l)\" = $n ]; do sleep 1; done; rm -f " + HDFS_READY
+ "; kill $(jobs -rp) 2>/dev/null; exit 1'");
// What serves a cluster's kept history once it has ended, started as root: the Spark History Server, reading the
// event logs kept beside the timeline server's store, the YARN timeline server, on that store, and the Tez UI, as
// the primary node ran them (SPARK_HISTORY_VARIABLE, TIMELINE_VARIABLE and TEZ_UI_VARIABLE), on their ports, with
// a configuration of their own, as the cluster's HDFS has gone; the Tez UI's naming the timeline server and the
// ResourceManager by the primary node's name, FLOCI_HDFS_HOST, as on the node, whose links Floci makes the
// browser's; with no ResourceManager there, the Tez UI's asks for it go to the timeline server, which answers them
// that it has nothing, rather than to the node that has gone. HISTORY_READY says it is ready once each answers; a
// daemon that exits ends the container, which the next link starts again.
private static final String HISTORY_SCRIPT = String.join("\n",
"mkdir -p " + HISTORY_CONF + " || exit",
"printf '%s\\n' '<configuration>' '" + property("fs.defaultFS", "file:///") + "' '</configuration>'"
+ " > " + HISTORY_CONF + "/core-site.xml || exit",
"printf '%s\\n' '<configuration>' '" + String.join("", List.of(
property("yarn.timeline-service.enabled", "true"),
property("yarn.timeline-service.hostname", "localhost"),
property("yarn.timeline-service.bind-host", "0.0.0.0"),
property("yarn.timeline-service.leveldb-timeline-store.path", HISTORY_TIMELINE),
property("yarn.timeline-service.ttl-ms", String.valueOf(TIMELINE_TTL_MS)),
property("yarn.timeline-service.http-cross-origin.enabled", "true")))
+ "' '</configuration>' > " + HISTORY_CONF + "/yarn-site.xml || exit",
"printf '%s\\n' 'log4j.rootLogger=WARN,console' 'log4j.appender.console=org.apache.log4j.ConsoleAppender'"
+ " 'log4j.appender.console.layout=org.apache.log4j.PatternLayout'"
+ " 'log4j.appender.console.layout.ConversionPattern=%d %p %c: %m%n'"
+ " > " + HISTORY_CONF + "/log4j.properties || exit",
"if [ -n \"$" + TEZ_UI_VARIABLE + "\" ]; then",
" mkdir -p " + TEZ_UI_CONFIG.substring(0, TEZ_UI_CONFIG.lastIndexOf('/')) + " && printf '%s\\n' 'ENV = {'"
+ " ' hosts: {' \" timeline: 'http://$FLOCI_HDFS_HOST:" + TIMELINE_WEB_PORT + "',\""
+ " \" rm: 'http://$FLOCI_HDFS_HOST:" + TIMELINE_WEB_PORT + "',\" ' },' '};'"
+ " > " + TEZ_UI_CONFIG + " || exit",
"fi",
HADOOP_FOLDER_SETUP,
"exec setpriv --reuid=hadoop --regid=hadoop --clear-groups bash -c '"
+ "n=0; "
+ "if [ -n \"$" + SPARK_HISTORY_VARIABLE + "\" ]; then "
+ "SPARK_HISTORY_OPTS=\"-Dspark.history.fs.logDirectory=file://" + HISTORY_EVENT_LOGS
+ " -Dspark.history.ui.port=" + EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT + "\""
+ " /usr/lib/spark/bin/spark-class org.apache.spark.deploy.history.HistoryServer & n=$((n + 1)); "
+ "fi; "
+ "if [ -n \"$" + TIMELINE_VARIABLE + "\" ]; then "
+ "HADOOP_CONF_DIR=" + HISTORY_CONF + " JDK_JAVA_OPTIONS=\"" + yarnOpens()
+ "\" yarn timelineserver & n=$((n + 1)); fi; "
+ "tez_ui=; [ -z \"$" + TEZ_UI_VARIABLE + "\" ] || [ ! -d " + TEZ_UI_FILES + " ] || tez_ui=1; "
+ "if [ -n \"$tez_ui\" ]; then "
+ "python3 -m http.server " + TEZ_UI_PORT + " --bind 0.0.0.0 --directory /usr/lib/tez"
+ " > /dev/null 2>&1 & n=$((n + 1)); fi; "
+ "if [ -n \"$" + SPARK_HISTORY_VARIABLE + "\" ]; then "
+ untilReady("curl -sf -m 5 http://127.0.0.1:" + EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT
+ "/api/v1/version > /dev/null")
+ "fi; "
+ "if [ -n \"$" + TIMELINE_VARIABLE + "\" ]; then "
+ untilReady("curl -sf -m 5 http://127.0.0.1:" + TIMELINE_WEB_PORT + "/ws/v1/timeline > /dev/null")
+ "fi; "
+ "if [ -n \"$tez_ui\" ]; then "
+ untilReady("curl -sf -m 5 http://127.0.0.1:" + TEZ_UI_PORT + TEZ_UI_PATH + " > /dev/null")
+ "fi; "
+ "touch " + HISTORY_READY + "; "
+ "while [ \"$(jobs -rp | wc -l)\" = $n ]; do sleep 1; done; rm -f " + HISTORY_READY
+ "; kill $(jobs -rp) 2>/dev/null; exit 1'");
// Copies the Spark applications' event logs, where there are any, out of the cluster's HDFS into its kept history,
// as the image's user, the node's daemons' (see keepHistory).
private static final String KEEP_EVENT_LOGS = String.join("\n",
HADOOP_FOLDER_SETUP,
"[ -d " + HISTORY_EVENT_LOGS + " ] || exit 0",
"hdfs dfs -test -d " + EmrServerlessSparkRunner.SPARK_EVENT_LOGS + " || exit 0",
"[ -n \"$(hdfs dfs -ls -C " + EmrServerlessSparkRunner.SPARK_EVENT_LOGS + ")\" ] || exit 0",
"exec hdfs dfs -get -f '" + EmrServerlessSparkRunner.SPARK_EVENT_LOGS + "/*' " + HISTORY_EVENT_LOGS + "/");
// The clusters whose history container is being started, and the history containers this process has started or
// found, by name, which a reset or a shutdown removes.
private final Set<String> historyStarts = ConcurrentHashMap.newKeySet();
private final Set<String> historyContainers = ConcurrentHashMap.newKeySet();
// One start at a time in a namespace the steps share, whatever the cluster, as it holds one HDFS.
private final Object sharedNamespaceStarts = new Object();
// One start at a time for each cluster's HDFS; a step coming while it starts waits, then finds it running.
@@ -1398,6 +1492,12 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
if (yarn.tezUi()) {
spec.withLoopbackPortBinding(TEZ_UI_PORT, 0);
}
if (yarn.sparkHistory() || yarn.timelineServer()) {
// Its history, in a volume of its own, which outlives the cluster's other storage (see keepHistory).
String history = historyName(clusterId);
lifecycleManager.ensureVolume(history, labels(clusterId, accountId, region, HISTORY_COMPONENT));
spec.withNamedVolume(history, HISTORY_PATH).withEnv(HISTORY_VARIABLE, "1");
}
}
if (yarn != null) {
spec.withEnv(YARN_MEMORY_VARIABLE, String.valueOf(yarn.memoryMb()))
@@ -1567,6 +1667,210 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
}
}
@Override
public boolean keepHistory(String clusterId) {
try {
if (!historyKept(clusterId)) {
return true;
}
if (lifecycleManager.probeContainer(hdfsName(clusterId)) != ContainerLiveness.RUNNING) {
// Its HDFS, which holds them, is read only through its NameNode.
LOG.warnv("The Spark event logs of EMR cluster {0} since its primary node last stopped are not kept, as"
+ " the node is not running", clusterId);
return true;
}
return copyEventLogs(hdfsName(clusterId));
} catch (RuntimeException e) {
// Docker did not answer, so its storage stays for a later try.
LOG.warnv(e, "Could not keep the Spark event logs of EMR cluster {0}: {1}", clusterId, e.getMessage());
return false;
}
}
// Copies a running primary node's Spark event logs into its kept history, where it has one (KEEP_EVENT_LOGS): as
// its cluster's storage goes, and before a teardown or a sweep at start removes the node, which neither can put
// off; whether they were kept.
private boolean copyEventLogs(String name) {
try {
ContainerExec.Result copied = ContainerExec.run(lifecycleManager.getDockerClient(), name,
new String[]{"setpriv", "--reuid=hadoop", "--regid=hadoop", "--clear-groups", "bash", "-c",
KEEP_EVENT_LOGS}, HISTORY_COPY_SECONDS);
if (copied.exitCode() != 0) {
LOG.warnv("Could not keep the Spark event logs of {0}: {1}", name, copied.stderr());
return false;
}
return true;
} catch (RuntimeException e) {
LOG.warnv(e, "Could not keep the Spark event logs of {0}: {1}", name, e.getMessage());
return false;
}
}
// Whether the cluster's kept history's volume is there; a failure to tell is thrown, rather than taken for none.
@Override
public boolean historyKept(String clusterId) {
try {
lifecycleManager.getDockerClient().inspectVolumeCmd(historyName(clusterId)).exec();
return true;
} catch (NotFoundException e) {
return false;
}
}
/**
* Where Floci reaches a port of the container serving a cluster's kept history, once it is ready: on the host's
* loopback interface, where it is published, or, Floci in a container, on the history's own network, which Floci's
* container joins, so no step's container reaches it. One not running is started on a thread of its own, as its
* image may need making first.
*/
@Override
public Optional<ContainerLifecycleManager.EndpointInfo> historyInterface(String clusterId, String accountId,
String region, Supplier<String> image,
Consumer<String> released,
String primaryHost, Yarn yarn,
int port) {
String name = historyUiName(clusterId);
try {
ContainerLiveness liveness = lifecycleManager.probeContainer(name);
if (liveness == ContainerLiveness.RUNNING) {
if (ContainerExec.run(lifecycleManager.getDockerClient(), name,
new String[]{"test", "-f", HISTORY_READY}, 10).exitCode() != 0) {
return Optional.empty();
}
String network = historyName(clusterId);
if (currentContainer.resolveContainerId().isPresent() && !attachFloci(network)) {
return Optional.empty();
}
return Optional.of(lifecycleManager.resolveEndpoint(name, port, network));
}
if (liveness == ContainerLiveness.NOT_RUNNING && historyStarts.add(clusterId)) {
long teardown = teardowns.get();
decommissions.execute(() -> {
try {
startHistory(clusterId, accountId, region, image, released, primaryHost, yarn, teardown);
} catch (RuntimeException e) {
LOG.warnv(e, "Could not start the history of EMR cluster {0}: {1}", clusterId,
e.getMessage());
} finally {
historyStarts.remove(clusterId);
}
});
}
} catch (RuntimeException e) {
LOG.debugv(e, "The history of EMR cluster {0} is not reachable: {1}", clusterId, e.getMessage());
}
return Optional.empty();
}
// The container serving a cluster's kept history, on a network of its own, its ports published as the primary
// node's were, made from the image the cluster ran; none once a teardown has run since it was asked for, or the
// history has gone, whose volume the container would make again, empty.
private void startHistory(String clusterId, String accountId, String region, Supplier<String> image,
Consumer<String> released, String primaryHost, Yarn yarn, long teardown) {
String imageId = image.get();
try {
if (teardowns.get() != teardown || !historyKept(clusterId)) {
return;
}
String name = historyUiName(clusterId);
String network = historyName(clusterId);
lifecycleManager.removeIfExistsStrict(name);
lifecycleManager.ensureNetwork(network, labels(clusterId, accountId, region, HISTORY_COMPONENT));
// Known before it starts, so a teardown while it starts removes it.
historyContainers.add(name);
ContainerBuilder.Builder spec = containerBuilder.newContainer(imageId)
.withName(name)
.withUser("root")
.withEntrypoint(List.of("/bin/bash", "-c", HISTORY_SCRIPT))
.withEnv("FLOCI_HDFS_HOST", primaryHost)
.withEnv("HADOOP_LOG_DIR", "/tmp/floci-history-logs")
.withNamedVolume(historyName(clusterId), HISTORY_PATH)
.withDockerNetwork(Optional.of(network))
.withLogRotation()
.withLabels(labels(clusterId, accountId, region, HISTORY_COMPONENT));
if (yarn.sparkHistory()) {
spec.withEnv(SPARK_HISTORY_VARIABLE, "1")
.withLoopbackPortBinding(EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT, 0);
}
if (yarn.timelineServer()) {
spec.withEnv(TIMELINE_VARIABLE, "1").withLoopbackPortBinding(TIMELINE_WEB_PORT, 0);
}
if (yarn.tezUi()) {
spec.withEnv(TEZ_UI_VARIABLE, "1").withLoopbackPortBinding(TEZ_UI_PORT, 0);
}
if (yarn.hadoopFolder() != null) {
spec.withEnv(HADOOP_FOLDER_VARIABLE, yarn.hadoopFolder());
}
lifecycleManager.createAndStart(spec.build());
if (teardowns.get() != teardown) {
// A teardown ran while it started, and may have missed it.
lifecycleManager.removeIfExistsStrict(name);
historyContainers.remove(name);
return;
}
LOG.infov("Started the history of EMR cluster {0}", clusterId);
} finally {
released.accept(imageId);
}
}
@Override
public void stopHistory(String clusterId) {
try {
lifecycleManager.removeIfExistsStrict(historyUiName(clusterId));
historyContainers.remove(historyUiName(clusterId));
} catch (RuntimeException e) {
LOG.warnv(e, "Could not stop the history of EMR cluster {0}: {1}", clusterId, e.getMessage());
}
}
/** Removes the kept histories of the clusters not in {@code kept}, their containers first, as each holds one. */
@Override
public void removeHistoriesBut(Set<String> kept) {
removeHistoryContainers(kept);
try {
ListVolumesResponse response = lifecycleManager.getDockerClient().listVolumesCmd()
.withFilter("label", historyLabels()).exec();
List<InspectVolumeResponse> volumes = response != null && response.getVolumes() != null
? response.getVolumes() : List.of();
for (InspectVolumeResponse volume : volumes) {
Map<String, String> labels = volume.getLabels() != null ? volume.getLabels() : Map.of();
if (!kept.contains(labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL))) {
lifecycleManager.removeVolume(volume.getName());
// Its network, named as it is, with Floci's container off it first.
detachFloci(volume.getName());
lifecycleManager.removeNetwork(volume.getName());
}
}
} catch (RuntimeException e) {
LOG.warnv(e, "Could not remove the kept histories of EMR clusters: {0}", e.getMessage());
}
}
// Removes the containers serving the kept histories of the clusters not in kept; those of the clusters kept, which
// an earlier process may have left, are known from now, so a reset or a shutdown removes them.
private void removeHistoryContainers(Set<String> kept) {
try {
for (Container container : lifecycleManager.getDockerClient().listContainersCmd().withShowAll(true)
.withLabelFilter(historyLabels()).exec()) {
Map<String, String> labels = container.getLabels() != null ? container.getLabels() : Map.of();
String clusterId = labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL);
if (!kept.contains(clusterId)) {
lifecycleManager.removeIfExistsStrict(container.getId());
} else {
historyContainers.add(historyUiName(clusterId));
}
}
} catch (RuntimeException e) {
LOG.warnv(e, "Could not remove the containers of EMR clusters' kept histories: {0}", e.getMessage());
}
}
private List<String> historyLabels() {
return List.of(ContainerStorageHelper.COMPONENT_LABEL + "=" + HISTORY_COMPONENT,
ContainerStorageHelper.OWNER_LABEL + "=" + ContainerStorageHelper.ownerIdentity(config));
}
// Whether the container became ready by the deadline, false when it stopped first, or the step did, or a teardown
// has run since it asked; a failure to become ready in time is thrown.
private boolean awaitReady(String clusterId, String containerId, long deadline, long teardown,
@@ -1634,6 +1938,15 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
return ContainerStorageHelper.dockerName(config, SERVICE + "-" + clusterId + "-hdfs");
}
// A cluster's kept history's volume, and the container serving it.
private String historyName(String clusterId) {
return ContainerStorageHelper.dockerName(config, SERVICE + "-" + clusterId + "-history");
}
private String historyUiName(String clusterId) {
return ContainerStorageHelper.dockerName(config, SERVICE + "-" + clusterId + "-history-ui");
}
private Map<String, String> labels(String clusterId, String accountId, String region, String component) {
Map<String, String> labels = new LinkedHashMap<>(ContainerStorageHelper.resourceIdentityLabels(SERVICE,
clusterId, accountId, region));
@@ -1696,8 +2009,21 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
removeNode(name, false);
}
for (String name : List.copyOf(running)) {
// What its history interfaces show goes into its kept history first, as nothing reads its HDFS after.
if (lifecycleManager.probeContainer(name) == ContainerLiveness.RUNNING) {
copyEventLogs(name);
}
removeKnown(name);
}
// The containers serving kept histories, which a later link starts again; the histories stay.
for (String name : List.copyOf(historyContainers)) {
try {
lifecycleManager.removeIfExistsStrict(name);
historyContainers.remove(name);
} catch (RuntimeException e) {
LOG.warnv(e, "Could not remove the history container {0}: {1}", name, e.getMessage());
}
}
}
// Removes an HDFS container, forgetting it only once Docker says it is gone and Floci's container has left its
@@ -1754,6 +2080,9 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
// Known first, so one Docker refuses to remove stays for the next reset or shutdown to remove.
String name = clusterId != null ? hdfsName(clusterId) : container.getId();
running.add(name);
if ("running".equals(container.getState())) {
copyEventLogs(name);
}
removeKnown(name);
} else {
// A cluster still up keeps the HDFS an earlier process left, which a reset or a shutdown removes.
@@ -898,8 +898,8 @@ public class EmrHandler {
private Response handleGetPersistentAppUiPresignedUrl(JsonNode request) {
bool(request, "AuthProxyCall");
string(request, "ExecutionRoleArn");
return presignedUrl(new EmrAppUiService.Presigned(appUis.persistentUrl(string(request, "PersistentAppUIId"),
string(request, "PersistentAppUIType"), string(request, "ApplicationId")), true));
return presignedUrl(appUis.persistentUrl(string(request, "PersistentAppUIId"),
string(request, "PersistentAppUIType"), string(request, "ApplicationId")));
}
private Response handleGetOnClusterAppUiPresignedUrl(JsonNode request) {
@@ -115,6 +115,13 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
private static final int SESSION_PASSWORD_BYTES = 24;
// No source gives how long GetClusterSessionCredentials' credentials last; Floci's expire in an hour.
private static final Duration SESSION_CREDENTIALS_VALIDITY = Duration.ofHours(1);
/**
* How long a cluster's history is kept after it ends: "The logs are available for 30 days after the application
* ends".
*/
static final Duration HISTORY_KEPT = Duration.ofDays(30);
// How long after its 30 days a cluster's kept history is looked at again, to remove it.
private static final Duration HISTORY_SWEEP_MARGIN = Duration.ofMinutes(1);
// How long the command that starts a cluster's primary node for its application UIs may run: it runs nothing.
private static final Duration PRIMARY_NODE_START = Duration.ofMinutes(5);
// AWS's answer to a change on a terminated cluster, for AddJobFlowSteps and ModifyInstanceFleet; Floci
@@ -403,11 +410,13 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
clustersUp.add(cluster.getId());
}
}
Set<String> histories = historiesKept();
if (bootstrapRunner != null && config.services().emr().reconcileContainersOnStartup()) {
bootstrapRunner.removeImages(imagesInUse);
}
if (clusterStorage != null && config.services().emr().reconcileContainersOnStartup()) {
clusterStorage.removeAllBut(clustersUp);
clusterStorage.removeHistoriesBut(histories);
}
wakeAtStart.forEach(Runnable::run);
}
@@ -466,6 +475,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
}
if (clusterStorage != null) {
clusterStorage.removeAllBut(Set.of());
clusterStorage.removeHistoriesBut(Set.of());
}
}
@@ -1041,6 +1051,91 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
});
}
/**
* Whether a cluster that has ended still has its kept history, which its history interfaces show for
* {@link #HISTORY_KEPT} after its end, once its storage has gone: until then its primary node may still hold the
* timeline server's store, and its event logs are not yet copied.
*/
public boolean historyKept(EmrCluster cluster) {
return clusterStorage != null && releaseImages != null && EmrClusterLifecycle.isTerminated(cluster.getState())
&& !cluster.isStorageCreated() && cluster.getEndDateTime() != null
&& now().isBefore(cluster.getEndDateTime().plus(HISTORY_KEPT))
&& clusterStorage.historyKept(cluster.getId());
}
/**
* Whether a cluster that is ending, or has ended with its storage not yet gone, will have its kept history once
* the storage has gone, as {@link #historyKept} has it then.
*/
public boolean historyComing(EmrCluster cluster) {
return clusterStorage != null && releaseImages != null && cluster.isStorageCreated()
&& (EmrClusterLifecycle.TERMINATING.equals(cluster.getState())
|| EmrClusterLifecycle.isTerminated(cluster.getState()))
&& (cluster.getEndDateTime() == null || now().isBefore(cluster.getEndDateTime().plus(HISTORY_KEPT)))
&& clusterStorage.historyKept(cluster.getId());
}
/**
* The history interfaces of a cluster that has ended, as its primary node ran them: its Spark History Server on a
* cluster with Spark, its YARN timeline server on one with Hadoop, and its Tez UI on one with Tez.
*/
public WebInterfaces historyInterfaces(EmrCluster cluster) {
ClusterStorage.Yarn yarn = yarnOf(cluster);
Set<Integer> ports = new LinkedHashSet<>();
if (yarn.sparkHistory()) {
ports.add(EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT);
}
if (yarn.timelineServer()) {
ports.add(EmrClusterStorage.TIMELINE_WEB_PORT);
}
if (yarn.tezUi()) {
ports.add(EmrClusterStorage.TEZ_UI_PORT);
}
return new WebInterfaces(masterPrivateDnsName(cluster), Set.copyOf(ports));
}
/**
* Where Floci reaches one of the history interfaces of a cluster that has ended, its kept history served by a
* container started in the image its steps ran in when it is not running; empty until it answers.
*/
public Optional<ContainerLifecycleManager.EndpointInfo> historyInterface(EmrCluster cluster, int port) {
Supplier<String> image = releaseImage(cluster);
if (clusterStorage == null || image == null) {
return Optional.empty();
}
return clusterStorage.historyInterface(cluster.getId(), regionResolver.getAccountId(), regionOf(cluster),
image, releaseImages::released, masterPrivateDnsName(cluster), yarnOf(cluster), port);
}
/** Stops the container serving a cluster's kept history, which a later link starts again. */
public void stopHistory(String clusterId) {
if (clusterStorage != null) {
clusterStorage.stopHistory(clusterId);
}
}
/** Removes the kept histories of the clusters that are gone, or ended more than {@link #HISTORY_KEPT} ago. */
public void removeExpiredHistories() {
if (clusterStorage != null) {
clusterStorage.removeHistoriesBut(historiesKept());
}
}
// The clusters, of every account, whose history is kept: those up, and those that ended within HISTORY_KEPT.
private Set<String> historiesKept() {
Instant cutoff = now().minus(HISTORY_KEPT);
Set<String> kept = new HashSet<>();
for (AccountAwareStorageBackend.AccountEntry<EmrCluster> entry
: clusterStore.scanAllAccountEntries(k -> true)) {
EmrCluster cluster = entry.value();
if (!EmrClusterLifecycle.isTerminated(cluster.getState())
|| cluster.getEndDateTime() == null || cluster.getEndDateTime().isAfter(cutoff)) {
kept.add(cluster.getId());
}
}
return kept;
}
/** Stops a command {@link #runOnCluster} runs, which then ends as stopped. */
public void stopOnCluster(String runId) {
if (sparkRunner != null) {
@@ -2398,8 +2493,13 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
}
String clusterId = cluster.getId();
String region = regionOf(cluster);
// Its kept history goes once its 30 days have passed, whether or not a link ever asked for it.
Instant ended = cluster.getEndDateTime() != null ? cluster.getEndDateTime() : now();
wakeups.at(ended.plus(HISTORY_KEPT).plus(HISTORY_SWEEP_MARGIN), this::removeExpiredHistories);
stepExecutor.execute(() -> {
boolean gone = clusterStorage.remove(clusterId);
// What its history interfaces show goes into its kept history first, which outlives the rest; a copy that
// failed keeps the storage that holds it, which the cluster's next release, or a restart, tries again.
boolean gone = clusterStorage.keepHistory(clusterId) && clusterStorage.remove(clusterId);
RequestScopes.runAs(accountId, region, () -> run(() -> storageRemoved(clusterId, key, gone)));
});
}