From 5fa518cf10e55ddd04d8a16ed4d936945c284fa6 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:29:25 -0400 Subject: [PATCH] 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. --- docs/services/emr.md | 28 +- .../aws/services/emr/ClusterStorage.java | 42 ++- .../aws/services/emr/EmrAppUiController.java | 13 +- .../aws/services/emr/EmrAppUiService.java | 151 ++++++-- .../aws/services/emr/EmrClusterStorage.java | 331 +++++++++++++++++- .../io/floci/aws/services/emr/EmrHandler.java | 4 +- .../io/floci/aws/services/emr/EmrService.java | 102 +++++- .../emr/EmrAppUiNightlyIntegrationTest.java | 53 ++- .../services/emr/EmrClusterStorageTest.java | 197 ++++++++++- .../services/emr/EmrPersistentAppUiTest.java | 204 +++++++++++ .../aws/services/emr/EmrServiceFixture.java | 46 +++ 11 files changed, 1128 insertions(+), 43 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/emr/EmrPersistentAppUiTest.java diff --git a/docs/services/emr.md b/docs/services/emr.md index 4f5ce28194..85fd8c6d46 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -45,7 +45,7 @@ Floci emulates the Amazon EMR (Elastic MapReduce) management API. Clusters (job | `ListNotebookExecutions` | Lists notebook executions, newest first, by editor, status, time and cluster | | `CreatePersistentAppUI` | Makes a cluster's persistent application UIs; see [Application UIs](#application-uis) | | `DescribePersistentAppUI` | Returns a persistent application UI's types and status | -| `GetPersistentAppUIPresignedURL` | Returns a presigned URL to a persistent application UI, a page of Floci's | +| `GetPersistentAppUIPresignedURL` | Returns a presigned URL to a persistent application UI, which opens for real in the `docker` mode; see [Application UIs](#application-uis) | | `GetOnClusterAppUIPresignedURL` | Returns a presigned URL to a running cluster's on-cluster UI, which opens for real in the `docker` mode; see [Application UIs](#application-uis) | | `GetClusterSessionCredentials` | Returns temporary basic credentials for a runtime role enabled cluster; see [Application UIs](#application-uis) | | `AddInstanceGroups` | Adds instance groups to a running cluster | @@ -373,12 +373,11 @@ not Jupyter: ## Application UIs -Floci keeps a cluster's persistent application UIs, but serves none of them: a presigned URL to one opens a page Floci -serves at `/_aws/emr/app-ui` on its own address -(`base-url`, or `hostname`), with the cluster as `DescribeCluster` gives it and the interface asked for, and so does -one to an on-cluster UI in the `immediate` mode. The link is signed with a key Floci makes as it starts and lasts an -hour, as no source gives AWS's; one changed, past its hour or given before Floci restarted opens a `403` page, and one -whose cluster has gone a `404`. +In the `immediate` mode, and for an interface the cluster does not run, a presigned URL opens a page Floci serves at +`/_aws/emr/app-ui` on its own address (`base-url`, or `hostname`), with the cluster as `DescribeCluster` gives it and +the interface asked for. The link is signed with a key Floci makes as it starts and lasts an hour, as no source gives +AWS's; one changed, past its hour or given before Floci restarted opens a `403` page, and one whose cluster has gone a +`404`. In the `docker` mode, an on-cluster UI that runs on the cluster's primary node opens for real: the `ResourceManager` ("YARN ResourceManager | http://master-public-dns-name:8088/"), an `ApplicationMaster` through the ResourceManager's @@ -424,7 +423,20 @@ arrives, and an interface that sends nothing for a minute has the request given any source gives. A tag without its `Key`, "the minimum required information for a valid tag", is refused, as it is for sessions, Studios and notebook executions. * **GetPersistentAppUIPresignedURL** gives a URL to one of the UI's types, its first by default; a type it has not is - refused, and the URL is `PresignedURLReady` at once. **GetOnClusterAppUIPresignedURL** gives one to an on-cluster UI, + refused. In the `docker` mode it opens the 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". Floci keeps it in a volume of the primary node's of its own, which holds the timeline server's + store (its entities kept 30 days rather than Hadoop's default 7) and, copied out of the cluster's HDFS as the cluster's + storage goes, its Spark applications' event logs, and as a reset or a shutdown removes a node still running; 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. The 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, and a reset removes every + one. Elsewhere the URL opens Floci's page, ready at once. **GetOnClusterAppUIPresignedURL** gives one to an on-cluster UI, the `ResourceManager` by default, while the cluster is `RUNNING` or `WAITING`, and none for a `DryRun`. With an `ApplicationId`, the ResourceManager's link lands on the application's page, an application master's on its UI through the web proxy, the JobHistory server's on the job of that id (`job_` in place of `application_`), the Spark diff --git a/src/main/java/io/floci/aws/services/emr/ClusterStorage.java b/src/main/java/io/floci/aws/services/emr/ClusterStorage.java index 63dc1a1ee3..4e3dd737ac 100644 --- a/src/main/java/io/floci/aws/services/emr/ClusterStorage.java +++ b/src/main/java/io/floci/aws/services/emr/ClusterStorage.java @@ -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 historyInterface(String clusterId, String accountId, + String region, Supplier image, + Consumer 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 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); diff --git a/src/main/java/io/floci/aws/services/emr/EmrAppUiController.java b/src/main/java/io/floci/aws/services/emr/EmrAppUiController.java index 3fece16159..03208e2f51 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrAppUiController.java +++ b/src/main/java/io/floci/aws/services/emr/EmrAppUiController.java @@ -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; diff --git a/src/main/java/io/floci/aws/services/emr/EmrAppUiService.java b/src/main/java/io/floci/aws/services/emr/EmrAppUiService.java index d5acf5a54c..48ec8b2838 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrAppUiService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrAppUiService.java @@ -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 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 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 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 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 ports, - Instant expires, Map endpoints) { + Instant expires, Map 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); diff --git a/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java b/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java index 459e245a5d..653d725aec 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java +++ b/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java @@ -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 { + " \"dfs.datanode.ipc.address" + "$FLOCI_HDFS_BIND:9867\"" + " '' > " + 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' '' '" + property("fs.defaultFS", "file:///") + "' ''" + + " > " + HISTORY_CONF + "/core-site.xml || exit", + "printf '%s\\n' '' '" + 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"))) + + "' '' > " + 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 historyStarts = ConcurrentHashMap.newKeySet(); + private final Set 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 historyInterface(String clusterId, String accountId, + String region, Supplier image, + Consumer 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 image, + Consumer 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 kept) { + removeHistoryContainers(kept); + try { + ListVolumesResponse response = lifecycleManager.getDockerClient().listVolumesCmd() + .withFilter("label", historyLabels()).exec(); + List volumes = response != null && response.getVolumes() != null + ? response.getVolumes() : List.of(); + for (InspectVolumeResponse volume : volumes) { + Map 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 kept) { + try { + for (Container container : lifecycleManager.getDockerClient().listContainersCmd().withShowAll(true) + .withLabelFilter(historyLabels()).exec()) { + Map 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 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 labels(String clusterId, String accountId, String region, String component) { Map 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. diff --git a/src/main/java/io/floci/aws/services/emr/EmrHandler.java b/src/main/java/io/floci/aws/services/emr/EmrHandler.java index 38c90bd721..8309347edc 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrHandler.java +++ b/src/main/java/io/floci/aws/services/emr/EmrHandler.java @@ -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) { diff --git a/src/main/java/io/floci/aws/services/emr/EmrService.java b/src/main/java/io/floci/aws/services/emr/EmrService.java index bb7cdeb1f4..371f65aff8 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrService.java @@ -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 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 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 historyInterface(EmrCluster cluster, int port) { + Supplier 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 historiesKept() { + Instant cutoff = now().minus(HISTORY_KEPT); + Set kept = new HashSet<>(); + for (AccountAwareStorageBackend.AccountEntry 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))); }); } diff --git a/src/test/java/io/floci/aws/services/emr/EmrAppUiNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrAppUiNightlyIntegrationTest.java index 4fa046454b..188e4991c7 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrAppUiNightlyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrAppUiNightlyIntegrationTest.java @@ -20,6 +20,7 @@ import org.junit.jupiter.api.extension.RegisterExtension; import java.net.URI; import java.time.Duration; import java.util.Map; +import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.LockSupport; import java.util.function.BooleanSupplier; @@ -40,7 +41,9 @@ import static org.junit.jupiter.api.Assertions.fail; * opens it, as the JobHistory server's link does; after a Spark step, whose event logs are in the cluster's HDFS, the * ResourceManager's answer links to the application on the Spark History Server's own host, which lists and opens it, * as the Spark History Server's link does; after a Hive step, its Tez DAG is in the YARN timeline server, and the Tez - * UI's page names the timeline server and the ResourceManager on their own hosts, which answer its page's requests. + * UI's page names the timeline server and the ResourceManager on their own hosts, which answer its page's requests. A + * persistent application UI opens the Spark History Server while the cluster runs, and, once it has ended and its + * storage has gone, its kept history: the Spark application, the DAG and the Tez UI's page. * *

A nightly check: the cluster's image, its HDFS and YARN, and a MapReduce job and a Spark one take minutes and * gigabytes. @@ -75,6 +78,9 @@ class EmrAppUiNightlyIntegrationTest { @Inject EmrService emrService; + @Inject + EmrClusterStorage clusterStorage; + @BeforeAll static void configure() { RestAssuredJsonUtils.configureAwsContentTypes(); @@ -206,6 +212,51 @@ class EmrAppUiNightlyIntegrationTest { assertEquals(200, crossOrigin.statusCode(), crossOrigin.asString()); String allowed = crossOrigin.getHeader("Access-Control-Allow-Origin"); assertTrue(tezOrigin.equals(allowed) || "*".equals(allowed), String.valueOf(allowed)); + + // A persistent application UI: the cluster's own while it runs. + String appUi = emr("CreatePersistentAppUI", "{\"TargetResourceArn\":\"arn:aws:elasticmapreduce:us-east-1:" + + "000000000000:cluster/" + clusterId + "\"}").then().statusCode(200).extract().jsonPath() + .getString("PersistentAppUIId"); + JsonPath live = persistentLink(appUi, "SHS"); + assertTrue(live.getBoolean("PresignedURLReady"), live.prettify()); + assertEquals(200, open(live.getString("PresignedURL")).statusCode()); + // Once the cluster has ended and its storage has gone, its kept history, served by a container of its own. + cleanup.register(() -> clusterStorage.removeHistoriesBut(Set.of())); + terminateClusterAndAwaitCleanup(clusterId, emrService); + String keptHistory = readyPersistentLink(appUi, "SHS"); + await(() -> open(keptHistory.replaceFirst("/$", "") + "/api/v1/applications").asString().contains(sparkId), + Duration.ofMinutes(2)); + URI keptTimeline = URI.create(readyPersistentLink(appUi, "YTS")); + Response keptDags = open(keptTimeline.getScheme() + "://" + keptTimeline.getRawAuthority() + + "/ws/v1/timeline/TEZ_DAG_ID"); + assertFalse(keptDags.jsonPath().getList("entities").isEmpty(), keptDags.asString()); + URI keptTez = URI.create(readyPersistentLink(appUi, "TEZ")); + assertTrue(open(keptTez.toString()).asString().contains("Tez UI")); + String keptConfig = open(keptTez.getScheme() + "://" + keptTez.getRawAuthority() + + "/tez-ui/config/configs.js").asString(); + String keptTimelineHost = "http://" + keptTez.getHost().substring(0, 26) + "-8188.emrappui.localhost:" + PORT; + assertTrue(keptConfig.contains(keptTimelineHost), keptConfig); + // With no ResourceManager there, the Tez UI asks the timeline server in its place, which answers, rather than + // the primary node that has gone. + assertFalse(keptConfig.contains("8088"), keptConfig); + Response keptRm = open(keptTimelineHost + "/ws/v1/cluster/apps"); + assertTrue(keptRm.statusCode() < 500, keptRm.statusCode() + " " + keptRm.asString()); + } + + private static JsonPath persistentLink(String appUi, String type) { + return emr("GetPersistentAppUIPresignedURL", "{\"PersistentAppUIId\":\"" + appUi + + "\",\"PersistentAppUIType\":\"" + type + "\"}").then().statusCode(200).extract().jsonPath(); + } + + // The link once it is ready: the history's container starts first. + private static String readyPersistentLink(String appUi, String type) { + String[] url = new String[1]; + await(() -> { + JsonPath answer = persistentLink(appUi, type); + url[0] = answer.getString("PresignedURL"); + return answer.getBoolean("PresignedURLReady"); + }, Duration.ofMinutes(10)); + return url[0]; } // A browser's request to the link, following the redirects it is sent, each to a link's host. diff --git a/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java b/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java index 4b15c79496..73b247866b 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java @@ -6,6 +6,7 @@ import com.github.dockerjava.api.command.ExecCreateCmd; import com.github.dockerjava.api.command.InspectContainerCmd; import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.command.InspectNetworkCmd; +import com.github.dockerjava.api.command.InspectVolumeCmd; import com.github.dockerjava.api.command.InspectVolumeResponse; import com.github.dockerjava.api.command.ListContainersCmd; import com.github.dockerjava.api.command.ListNetworksCmd; @@ -131,6 +132,7 @@ class EmrClusterStorageTest { private final EmrClusterStorage storage = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv, roleCredentials, currentContainer, config, s3, Duration.ofSeconds(120), System::nanoTime); private final String hdfsName = ContainerStorageHelper.dockerName(config, "emr-j-1-hdfs"); + private final String historyName = ContainerStorageHelper.dockerName(config, "emr-j-1-history"); private final String coreName = ContainerStorageHelper.dockerName(config, "emr-j-1-node-1-1"); private final String taskName = ContainerStorageHelper.dockerName(config, "emr-j-1-node-2-1"); @@ -1400,8 +1402,9 @@ class EmrClusterStorageTest { // interface and the ResourceManager's open to the Tez UI's page on its own host. return script.contains("timeline=; [ -z \"$FLOCI_YARN_TIMELINE\" ] || timeline=\"" + "yarn.timeline-service.enabledtrue") + && script.contains("timeline_store=/mnt/yarn/timeline\n") && script.contains("yarn.timeline-service.leveldb-timeline-store.path" - + "/mnt/yarn/timeline") + + "$timeline_store") && script.contains("yarn.timeline-service.http-cross-origin.enabled" + "true") && script.contains(" \"$timeline\" '' > /tmp/floci-hdfs-conf/yarn-site.xml") @@ -1426,6 +1429,198 @@ class EmrClusterStorageTest { })); } + @Test + void aPrimaryNodeThatRunsAHistoryInterfaceKeepsItsTimelineStoreInAVolumeThatOutlivesTheCluster() { + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-7", Map.of())); + when(lifecycle.probeContainer("c-7")).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.resolveContainerNetworkIp("c-7", hdfsName)).thenReturn("172.18.0.8"); + ContainerExecStubs.completeEveryExec(docker, "c-7", 0L, "", ""); + + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, + () -> new ClusterStorage.Yarn(4096, 4).withSparkHistory(true).withHistories(true, false), + NOT_STOPPED); + + verify(lifecycle).ensureVolume(eq(historyName), argThat(labels -> "emr-history".equals( + labels.get(ContainerStorageHelper.COMPONENT_LABEL)) + && "j-1".equals(labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL)))); + verify(spec).withNamedVolume(historyName, EmrClusterStorage.HISTORY_PATH); + verify(spec).withEnv("FLOCI_HISTORY", "1"); + // Made the image's user's as root, the timeline server's store in it, kept as long as the history is. + verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains( + "if [ -n \"$FLOCI_HISTORY\" ]; then\n" + + " mkdir -p /var/lib/floci-history/spark-events /var/lib/floci-history/timeline" + + " && chown -R hadoop:hadoop /var/lib/floci-history || exit\n" + + " timeline_store=/var/lib/floci-history/timeline\nfi") + && entrypoint.get(2).contains("yarn.timeline-service.ttl-ms" + + "2592000000"))); + // Removing the cluster's storage leaves it. + storage.remove("j-1"); + verify(lifecycle, never()).removeVolume(historyName); + } + + @Test + void aClustersSparkEventLogsAreCopiedIntoItsKeptHistoryWhileItsPrimaryNodeStillRuns() { + InspectVolumeCmd inspect = mock(InspectVolumeCmd.class); + when(docker.inspectVolumeCmd(historyName)).thenReturn(inspect); + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING); + List> commands = ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", ""); + + assertTrue(storage.keepHistory("j-1")); + + assertEquals(1, commands.size(), commands.toString()); + assertEquals(List.of("setpriv", "--reuid=hadoop", "--regid=hadoop", "--clear-groups", "bash", "-c"), + commands.get(0).subList(0, 6)); + assertTrue(commands.get(0).get(6).endsWith("exec hdfs dfs -get -f '/var/log/spark/apps/*'" + + " /var/lib/floci-history/spark-events/"), commands.get(0).get(6)); + // A cluster that keeps no history has nothing copied. + when(inspect.exec()).thenThrow(new NotFoundException("no such volume")); + assertTrue(storage.keepHistory("j-1")); + assertEquals(1, commands.size()); + } + + @Test + void aFailedCopyOfTheSparkEventLogsIsReportedSoTheStorageStays() { + when(docker.inspectVolumeCmd(historyName)).thenReturn(mock(InspectVolumeCmd.class)); + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING); + ContainerExecStubs.completeEveryExec(docker, hdfsName, 1L, "", "get: Connection refused"); + + assertFalse(storage.keepHistory("j-1")); + } + + @Test + void aKeptHistoryIsServedByAContainerOfItsOwnStartedOnItsFirstLink() { + String historyUi = ContainerStorageHelper.dockerName(config, "emr-j-1-history-ui"); + when(lifecycle.probeContainer(historyUi)).thenReturn(ContainerLiveness.NOT_RUNNING); + when(docker.inspectVolumeCmd(historyName)).thenReturn(mock(InspectVolumeCmd.class)); + List released = new ArrayList<>(); + ClusterStorage.Yarn yarn = new ClusterStorage.Yarn(4096, 4).withSparkHistory(true).withHistories(true, true); + + Optional starting = storage.historyInterface("j-1", "123456789012", + "us-east-1", () -> IMAGE, released::add, HOST, yarn, EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT); + + assertTrue(starting.isEmpty()); + verify(spec).withName(historyUi); + verify(spec).withNamedVolume(historyName, EmrClusterStorage.HISTORY_PATH); + // On a network of its own, so no step's container reaches it. + verify(lifecycle).ensureNetwork(eq(historyName), argThat(labels -> "emr-history".equals( + labels.get(ContainerStorageHelper.COMPONENT_LABEL)))); + verify(spec).withDockerNetwork(Optional.of(historyName)); + verify(spec).withEnv("FLOCI_HDFS_HOST", HOST); + verify(spec).withEnv("FLOCI_SPARK_HISTORY", "1"); + verify(spec).withEnv("FLOCI_YARN_TIMELINE", "1"); + verify(spec).withEnv("FLOCI_TEZ_UI", "1"); + verify(spec).withLoopbackPortBinding(EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT, 0); + verify(spec).withLoopbackPortBinding(EmrClusterStorage.TIMELINE_WEB_PORT, 0); + verify(spec).withLoopbackPortBinding(EmrClusterStorage.TEZ_UI_PORT, 0); + verify(spec).withLabels(argThat(labels -> "emr-history".equals( + labels.get(ContainerStorageHelper.COMPONENT_LABEL)))); + // The event logs from the history, the timeline server on its store, as the cluster's ran them. + verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains( + "-Dspark.history.fs.logDirectory=file:///var/lib/floci-history/spark-events") + && entrypoint.get(2).contains("yarn.timeline-service.leveldb-timeline-store.path" + + "/var/lib/floci-history/timeline") + // With no ResourceManager there, the Tez UI asks the timeline server in its place. + && entrypoint.get(2).contains("\" rm: 'http://$FLOCI_HDFS_HOST:8188',\""))); + verify(lifecycle).createAndStart(any()); + assertEquals(List.of(IMAGE), released); + + ContainerLifecycleManager.EndpointInfo published = new ContainerLifecycleManager.EndpointInfo("localhost", + 32804); + when(lifecycle.probeContainer(historyUi)).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.resolveEndpoint(historyUi, EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT, historyName)) + .thenReturn(published); + ContainerExecStubs.completeEveryExec(docker, historyUi, 0L, "", ""); + assertEquals(Optional.of(published), storage.historyInterface("j-1", "123456789012", "us-east-1", + () -> IMAGE, released::add, HOST, yarn, EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT)); + } + + @Test + void aHistoryContainerStartedThroughATeardownIsRemovedAndNoneStartsOnceTheHistoryHasGone() { + String historyUi = ContainerStorageHelper.dockerName(config, "emr-j-1-history-ui"); + when(lifecycle.probeContainer(historyUi)).thenReturn(ContainerLiveness.NOT_RUNNING); + InspectVolumeCmd inspect = mock(InspectVolumeCmd.class); + when(docker.inspectVolumeCmd(historyName)).thenReturn(inspect); + ClusterStorage.Yarn yarn = new ClusterStorage.Yarn(4096, 4).withSparkHistory(true); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("h-1", Map.of())); + // A teardown runs as it starts, before its name is known, so the teardown misses it. + doAnswer(network -> { + storage.stopManagedContainers(); + return null; + }).when(lifecycle).ensureNetwork(eq(historyName), any()); + + storage.historyInterface("j-1", "123456789012", "us-east-1", () -> IMAGE, image -> { }, HOST, yarn, + EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT); + + // Once in place of any left before it, and once as it started through the teardown. + verify(lifecycle, times(2)).removeIfExistsStrict(historyUi); + // Its history gone, as its 30 days passed: no container makes its volume again, empty. + when(inspect.exec()).thenThrow(new NotFoundException("no such volume")); + storage.historyInterface("j-1", "123456789012", "us-east-1", () -> IMAGE, image -> { }, HOST, yarn, + EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT); + verify(lifecycle, times(1)).createAndStart(any()); + } + + @Test + void aFailureToTellWhetherAHistoryIsKeptIsNotTakenForNone() { + InspectVolumeCmd inspect = mock(InspectVolumeCmd.class); + when(docker.inspectVolumeCmd(historyName)).thenReturn(inspect); + when(inspect.exec()).thenThrow(new IllegalStateException("Docker went away")); + + assertThrows(IllegalStateException.class, () -> storage.historyKept("j-1")); + } + + @Test + void aRunningPrimaryNodesEventLogsAreKeptBeforeATeardownRemovesIt() { + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING, ContainerLiveness.RUNNING); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-7", Map.of())); + when(lifecycle.probeContainer("c-7")).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.resolveContainerNetworkIp("c-7", hdfsName)).thenReturn("172.18.0.8"); + ContainerExecStubs.completeEveryExec(docker, "c-7", 0L, "", ""); + storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, + () -> new ClusterStorage.Yarn(4096, 4).withSparkHistory(true), NOT_STOPPED); + List> commands = ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", ""); + + storage.stopManagedContainers(); + + assertTrue(commands.stream().anyMatch(command -> command.get(command.size() - 1) + .contains("hdfs dfs -get -f '/var/log/spark/apps/*'")), commands.toString()); + // Once as it was created, in place of any left before it, and once by the teardown. + verify(lifecycle, times(2)).removeIfExistsStrict(hdfsName); + } + + @Test + void theKeptHistoriesOfClustersNotKeptGoTheirContainersFirst() { + Container gone = historyContainer("c-gone", "j-1"); + Container kept = historyContainer("c-kept", "j-2"); + ListContainersCmd containers = mock(ListContainersCmd.class, RETURNS_SELF); + when(docker.listContainersCmd()).thenReturn(containers); + when(containers.exec()).thenReturn(List.of(gone, kept)); + InspectVolumeResponse goneVolume = mock(InspectVolumeResponse.class); + when(goneVolume.getName()).thenReturn(historyName); + when(goneVolume.getLabels()).thenReturn(Map.of(ContainerStorageHelper.RESOURCE_ID_LABEL, "j-1")); + InspectVolumeResponse keptVolume = mock(InspectVolumeResponse.class); + when(keptVolume.getName()).thenReturn("floci-aws-emr-j-2-history"); + when(keptVolume.getLabels()).thenReturn(Map.of(ContainerStorageHelper.RESOURCE_ID_LABEL, "j-2")); + nodeVolumes(goneVolume, keptVolume); + + storage.removeHistoriesBut(Set.of("j-2")); + + verify(lifecycle).removeIfExistsStrict("c-gone"); + verify(lifecycle, never()).removeIfExistsStrict("c-kept"); + verify(lifecycle).removeVolume(historyName); + verify(lifecycle).removeNetwork(historyName); + verify(lifecycle, never()).removeVolume("floci-aws-emr-j-2-history"); + } + + private static Container historyContainer(String id, String clusterId) { + Container container = mock(Container.class); + when(container.getId()).thenReturn(id); + when(container.getLabels()).thenReturn(Map.of(ContainerStorageHelper.RESOURCE_ID_LABEL, clusterId, + ContainerStorageHelper.COMPONENT_LABEL, "emr-history")); + return container; + } + @Test void aClusterWithSparkHasItsPrimaryNodeRunASparkHistoryServerOnItsApplicationsEventLogs() { when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING); diff --git a/src/test/java/io/floci/aws/services/emr/EmrPersistentAppUiTest.java b/src/test/java/io/floci/aws/services/emr/EmrPersistentAppUiTest.java new file mode 100644 index 0000000000..ecb7eed6ee --- /dev/null +++ b/src/test/java/io/floci/aws/services/emr/EmrPersistentAppUiTest.java @@ -0,0 +1,204 @@ +package io.floci.aws.services.emr; + +import io.floci.aws.core.common.LinkSigner; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.docker.ContainerLifecycleManager; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.services.emr.model.EmrCluster; +import io.floci.aws.services.emr.model.EmrPersistentAppUi; +import io.floci.aws.services.emrserverless.EmrServerlessSparkRunner; +import io.floci.aws.services.emrserverless.SparkJobRunner; +import io.floci.aws.services.iam.IamService; +import org.junit.jupiter.api.Test; + +import java.net.URI; +import java.time.Duration; +import java.util.List; + +import static io.floci.aws.services.emr.EmrServiceFixture.ACCOUNT; +import static io.floci.aws.services.emr.EmrServiceFixture.REGION; +import static io.floci.aws.services.emr.EmrServiceFixture.cluster; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +/** + * Persistent application UI links in the docker runner mode ({@link EmrAppUiService}): while the cluster runs, its + * primary node's interface; once it has ended, for 30 days, its kept history's, served by a container of its own + * that starts on the link and stops once no link to it is valid. + */ +class EmrPersistentAppUiTest { + + private static final int SPARK_HISTORY = EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT; + private static final ContainerLifecycleManager.EndpointInfo ON_HOST = + new ContainerLifecycleManager.EndpointInfo("localhost", 32803); + + private final EmrServiceFixture fixture = EmrServiceFixture.docker(new FinishingRunner(), + mock(IamService.class)); + private final EmrAppUiService appUis = new EmrAppUiService( + AccountAwareStorageBackend.inMemory(ACCOUNT), fixture.service, + new RegionResolver(REGION, ACCOUNT), fixture.clock, "http://localhost:4566", LinkSigner.withNewKey()); + + @Test + void aPersistentUiOpensItsClustersLiveInterfaceWhileTheClusterRuns() { + fixture.clusterStorage.webInterfaces.put(SPARK_HISTORY, ON_HOST); + EmrCluster cluster = sparkCluster(); + String appUi = appUis.create(arn(cluster), null, null).appUi().getId(); + + EmrAppUiService.Presigned link = appUis.persistentUrl(appUi, "SHS", "application_1_0001"); + + assertTrue(link.ready()); + URI url = URI.create(link.url()); + assertTrue(url.getAuthority().contains("-18080.emrappui."), link.url()); + assertEquals("/history/application_1_0001/", url.getPath()); + assertEquals(32803, appUis.route(url.getAuthority(), "http").port()); + } + + @Test + void onceItsClusterHasEndedItOpensTheKeptHistoryUntilItsThirtyDaysHavePassed() { + EmrCluster cluster = sparkCluster(); + String appUi = appUis.create(arn(cluster), null, null).appUi().getId(); + startAndEnd(cluster); + + // What its interfaces show was kept before its storage went. + assertEquals(List.of("kept " + cluster.getId()), fixture.clusterStorage.historyEvents); + EmrAppUiService.Presigned starting = appUis.persistentUrl(appUi, "SHS", null); + + assertFalse(starting.ready()); + String primary = EmrService.masterPrivateDnsName(cluster); + assertEquals("starting " + cluster.getId() + " as " + primary, + fixture.clusterStorage.historyEvents.get(1)); + URI url = URI.create(starting.url()); + assertEquals(EmrAppUiService.HISTORY_NOT_READY, appUis.route(url.getAuthority(), "http").refusal()); + fixture.clusterStorage.historyInterfaces.put(SPARK_HISTORY, ON_HOST); + EmrAppUiService.UiRoute route = appUis.route(url.getAuthority(), "http"); + assertNull(route.refusal()); + assertEquals(32803, route.port()); + assertTrue(appUis.persistentUrl(appUi, "SHS", null).ready()); + + fixture.clock.advance(EmrService.HISTORY_KEPT); + assertTrue(appUis.persistentUrl(appUi, "SHS", null).url() + .startsWith("http://localhost:4566" + EmrAppUiService.PATH + "?")); + } + + @Test + void theContainerServingAKeptHistoryStopsOnceNoLinkToItIsValid() { + EmrCluster cluster = sparkCluster(); + String appUi = appUis.create(arn(cluster), null, null).appUi().getId(); + startAndEnd(cluster); + fixture.clusterStorage.historyInterfaces.put(SPARK_HISTORY, ON_HOST); + appUis.persistentUrl(appUi, "SHS", null); + + appUis.reapHistory(ACCOUNT, REGION, cluster.getId()); + assertFalse(fixture.clusterStorage.historyEvents.contains("stopped " + cluster.getId())); + fixture.clock.advance(EmrAppUiService.VALIDITY); + appUis.reapHistory(ACCOUNT, REGION, cluster.getId()); + + assertTrue(fixture.clusterStorage.historyEvents.contains("stopped " + cluster.getId())); + // The histories within their 30 days stay, the cluster's among them. + assertTrue(fixture.clusterStorage.historySweeps.getLast().contains(cluster.getId())); + } + + @Test + void aLinkAskedWhileItsClustersStorageIsStillGoingIsNotReadyAndStartsNothing() { + EmrCluster cluster = sparkCluster(); + String appUi = appUis.create(arn(cluster), null, null).appUi().getId(); + appUis.onClusterUrl(cluster.getId(), null, null, false); + fixture.runStepThread(); + // Its history's volume, which the node made as it started. + fixture.clusterStorage.historiesKept.add(cluster.getId()); + fixture.service.terminateJobFlows(List.of(cluster.getId())); + + // Its primary node may still hold the timeline server's store, and its event logs are not yet copied. + EmrAppUiService.Presigned link = appUis.persistentUrl(appUi, "SHS", null); + + assertFalse(link.ready()); + assertTrue(fixture.clusterStorage.historyEvents.stream().noneMatch(event -> event.startsWith("starting")), + fixture.clusterStorage.historyEvents.toString()); + endStorage(cluster); + assertFalse(appUis.persistentUrl(appUi, "SHS", null).ready()); + assertEquals("starting " + cluster.getId() + " as " + EmrService.masterPrivateDnsName(cluster), + fixture.clusterStorage.historyEvents.get(1)); + } + + @Test + void aFailedCopyOfItsEventLogsKeepsTheClustersStorageForALaterTry() { + EmrCluster cluster = sparkCluster(); + String appUi = appUis.create(arn(cluster), null, null).appUi().getId(); + appUis.onClusterUrl(cluster.getId(), null, null, false); + fixture.runStepThread(); + fixture.clusterStorage.historiesKept.add(cluster.getId()); + fixture.clusterStorage.keepFails = true; + fixture.service.terminateJobFlows(List.of(cluster.getId())); + while (fixture.stepThreadsWaiting() > 0) { + fixture.runStepThread(); + } + + // Its HDFS, which holds the event logs, stays, and its history is not yet there to open. + assertEquals(List.of("could not keep " + cluster.getId()), fixture.clusterStorage.historyEvents); + assertFalse(fixture.clusterStorage.removed.contains(cluster.getId())); + assertTrue(fixture.service.describeCluster(cluster.getId()).isStorageCreated()); + assertFalse(appUis.persistentUrl(appUi, "SHS", null).ready()); + } + + @Test + void aKeptHistoryNoLinkAskedForGoesOnceItsThirtyDaysHavePassed() { + EmrCluster cluster = sparkCluster(); + startAndEnd(cluster); + assertTrue(fixture.clusterStorage.historySweeps.isEmpty()); + + // The sweep its end set, a minute past its 30 days. + fixture.pass(EmrService.HISTORY_KEPT); + + assertFalse(fixture.clusterStorage.historySweeps.isEmpty()); + assertFalse(fixture.clusterStorage.historySweeps.getLast().contains(cluster.getId())); + } + + // Its primary node started, as a link to it before any step starts it, then the cluster ended, its storage gone. + private void startAndEnd(EmrCluster cluster) { + appUis.onClusterUrl(cluster.getId(), null, null, false); + fixture.runStepThread(); + fixture.service.terminateJobFlows(List.of(cluster.getId())); + endStorage(cluster); + } + + private void endStorage(EmrCluster cluster) { + while (fixture.stepThreadsWaiting() > 0) { + fixture.runStepThread(); + } + assertTrue(fixture.clusterStorage.removed.contains(cluster.getId())); + fixture.clock.advance(Duration.ofMinutes(1)); + } + + private EmrCluster sparkCluster() { + fixture.clusterStorage.ownNetwork = true; + EmrCluster cluster = cluster("history", true); + cluster.setReleaseLabel("emr-7.5.0"); + cluster.setApplications("[{\"Name\":\"Hadoop\"},{\"Name\":\"Spark\"}]"); + return fixture.service.runJobFlow(cluster, REGION); + } + + private static String arn(EmrCluster cluster) { + return "arn:aws:elasticmapreduce:us-east-1:000000000000:cluster/" + cluster.getId(); + } + + /** Ends each command at once, as the Docker runner would one that runs nothing. */ + private static final class FinishingRunner implements SparkJobRunner { + + @Override + public Outcome run(Job job, Progress progress) { + progress.started(); + return Outcome.exitedWith(0); + } + + @Override + public void stop(String runId) { + } + + @Override + public void removeLeftoverDrivers(String service) { + } + } +} diff --git a/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java b/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java index 72c8d6ded5..47ab351212 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java @@ -20,6 +20,7 @@ import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; @@ -101,6 +102,14 @@ final class EmrServiceFixture { final List released = new ArrayList<>(); // Where each port of a primary node's web interfaces is reached, once the node is ready. final Map webInterfaces = new HashMap<>(); + // The clusters whose history is kept; where each port of a kept history's container is reached, once it + // answers; what was asked of the histories, in order; and the clusters each sweep kept. + final Set historiesKept = new HashSet<>(); + final Map historyInterfaces = new HashMap<>(); + final List historyEvents = new ArrayList<>(); + final List> historySweeps = new ArrayList<>(); + // Whether copying a cluster's event logs into its kept history fails. + boolean keepFails; // How each cluster's nodes are known as EC2 instances. final Map> identities = new HashMap<>(); @@ -159,6 +168,43 @@ final class EmrServiceFixture { return Optional.ofNullable(webInterfaces.get(port)); } + @Override + public boolean keepHistory(String clusterId) { + if (keepFails) { + historyEvents.add("could not keep " + clusterId); + return false; + } + historyEvents.add("kept " + clusterId + (removed.contains(clusterId) ? " after its removal" : "")); + historiesKept.add(clusterId); + return true; + } + + @Override + public boolean historyKept(String clusterId) { + return historiesKept.contains(clusterId); + } + + @Override + public Optional historyInterface(String clusterId, String accountId, + String region, Supplier image, Consumer released, String primaryHost, Yarn yarn, + int port) { + ContainerLifecycleManager.EndpointInfo endpoint = historyInterfaces.get(port); + if (endpoint == null) { + historyEvents.add("starting " + clusterId + " as " + primaryHost); + } + return Optional.ofNullable(endpoint); + } + + @Override + public void stopHistory(String clusterId) { + historyEvents.add("stopped " + clusterId); + } + + @Override + public void removeHistoriesBut(Set kept) { + historySweeps.add(Set.copyOf(kept)); + } + @Override public void resize(String clusterId, Supplier yarn) { resizes.add(yarn.get());