From c843dcbdfcfa04aff6b0b9913a1bdb64e3fb6449 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:05:46 -0400 Subject: [PATCH] fix(opensearch): start domain containers again when Floci restarts (#9434) Floci's shutdown removes every OpenSearch domain's container, and nothing started them again, so after a restart with persistent storage a domain reported an endpoint nothing answered on. At startup, each domain goes back to Processing, and its container comes back in the background. A container that outlived Floci, kept running across the shutdown or left behind by a killed Floci, is kept: found by the container ID the record names, started again if it stopped, and its host port reserved again. Otherwise the domain gets a new container on the data it kept, so its indices are back, and the readiness poller reports it ready once it answers. A domain started again keeps the storage its record names, whatever the data-volume setting says then: the operator's volume, or bind-mounted directory, whose path the record now keeps, or its own Floci-managed volume. With no Docker daemon reachable, a domain has no container, as one created then has. A domain deleted during its restore reads Deleted, keeps its name, and is removed with its container and data once the restore's start is through; one still Deleted at the next start is removed then. Each removal is confirmed with Docker, and deleting again a domain whose delete Docker kept the container of confirms it the same way, one retry at a time, on the record still stored. A start that shutdown overtakes removes its container. Part of #5664. --- .github/ci/prefetch-images.sh | 6 +- docs/services/opensearch.md | 1 + pom.xml | 6 + .../aws/lifecycle/EmulatorLifecycle.java | 11 + .../opensearch/OpenSearchDomainManager.java | 173 +++++++- .../opensearch/OpenSearchService.java | 283 ++++++++++++- .../aws/services/opensearch/model/Domain.java | 16 + .../aws/lifecycle/EmulatorLifecycleTest.java | 48 +++ .../OpenSearchDomainManagerTest.java | 210 ++++++++++ ...chDomainRestartNightlyIntegrationTest.java | 140 +++++++ .../opensearch/OpenSearchServiceTest.java | 379 ++++++++++++++++++ 11 files changed, 1261 insertions(+), 12 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/opensearch/OpenSearchDomainRestartNightlyIntegrationTest.java diff --git a/.github/ci/prefetch-images.sh b/.github/ci/prefetch-images.sh index 5adcce18e7..4a9128f7e1 100755 --- a/.github/ci/prefetch-images.sh +++ b/.github/ci/prefetch-images.sh @@ -77,7 +77,8 @@ starts ContainerHostNetworkDockerIntegrationTest ContainerBindDirectoryDockerInt EcsExecChannelDockerIntegrationTest EcsImagePullDockerIntegrationTest EcsLeftoverContainersDockerIntegrationTest \ BatchDockerRunnerDockerIntegrationTest SageMakerDockerNightlyIntegrationTest DockerPoolSaturationNightlyIntegrationTest \ && [ -n "$BUSYBOX_IMAGE" ] && pull "$BUSYBOX_IMAGE" -# Bind-directory ownership uses the default OpenSearch image, whose cold pull can outlast a test. +# Bind-directory ownership uses the default OpenSearch image, whose cold pull can outlast a test, and the nightly +# OpenSearchDomainRestartNightlyIntegrationTest runs a domain on it. OPENSEARCH_VERSIONS="$(find src/main/java -name OpenSearchVersions.java -print -quit)" opensearch_default_image() { file="${OPENSEARCH_VERSIONS:-/dev/null}" @@ -91,7 +92,8 @@ opensearch_default_image() { echo "$image" } OPENSEARCH_IMAGE="$(opensearch_default_image)" -starts ContainerBindDirectoryDockerIntegrationTest && [ -n "$OPENSEARCH_IMAGE" ] && pull "$OPENSEARCH_IMAGE" +starts ContainerBindDirectoryDockerIntegrationTest OpenSearchDomainRestartNightlyIntegrationTest \ + && [ -n "$OPENSEARCH_IMAGE" ] && pull "$OPENSEARCH_IMAGE" # EcsImagePullDockerIntegrationTest runs its own registry to move a tag in; the /ecr/ line below # covers the shards that run the ECR tests. REGISTRY_IMAGE="$(test_image REGISTRY)" diff --git a/docs/services/opensearch.md b/docs/services/opensearch.md index 60f10dc21f..8353d0e91d 100644 --- a/docs/services/opensearch.md +++ b/docs/services/opensearch.md @@ -163,6 +163,7 @@ services: - **Defaults for those settings:** a domain created without them reports `IPAddressType` `ipv4`, an empty `AdvancedOptions`, automatic software updates off, and an enabled off-peak window starting at 22:00, as AWS does for a new domain. AWS reads 10:00 P.M. in the Region's local time; Floci keeps no time zone per Region and reports 22:00 UTC. A window enabled without a start time gets the same default. - **Instance type families:** `t3.*` / `m5/m6g/m7g.*` / `r5/r6g/r7g.*` / `c5/c6g/c7g.*` are EBS-backed (3584 GiB max). `i3.*` are local-NVMe instance-store. `or1.*` are S3-backed and surface a much larger volume ceiling on `DescribeInstanceTypeLimits` (8–36 TiB depending on size). Floci still boots one Docker container per domain regardless of family — the metadata fidelity matters for SDK clients that introspect, not for runtime data placement. - **Container identity:** containers are named `floci-aws-opensearch---`, or `floci-aws--opensearch---` when `FLOCI_DOCKER_RESOURCE_NAMESPACE` is set. Account and Region come from the domain's stored ARN and are also recorded in its container labels. Restarts remove older containers by their persisted container ID and preserve the stored volume name. Legacy names that omit account and Region are never removed solely by name, because another domain may own them. +- **Restarts:** with persistent storage, each domain's container comes back when Floci starts again. Shutdown removes the containers unless `FLOCI_SERVICES_OPENSEARCH_KEEP_RUNNING_ON_SHUTDOWN` keeps them, so each domain goes back to `Processing` at once and its container comes back in the background, without Floci waiting for it to report itself ready. A container that outlived Floci, kept running or left behind when Floci was killed, is kept: it is found by the container ID the domain's record names, started again if it stopped, and its host port is reserved again. Otherwise the domain gets a new container on the data it kept, its Docker volume or data directory, so its indices are back. A domain keeps the storage it was created with: the volume or directory `FLOCI_SERVICES_OPENSEARCH_DATA_VOLUME` named then, even once that setting changes or is gone, or its own Floci-managed volume, even once one is configured. A domain recorded by an older Floci on a bind-mounted directory, whose path its record does not keep, is not started while that setting is gone, rather than started on empty storage. `Processing` turns `false` once the container answers `/_cluster/health`, as after `CreateDomain`. With no Docker daemon reachable, a domain reports `Processing` `false` and an AWS-shaped endpoint, as one created then does. A domain deleted while its container comes back reads `Deleted` `true`, as AWS reports a domain being deleted, and keeps its name until its container is up and removed with its data; one still `Deleted` when Floci stops is removed at the next start. - **Container storage:** each domain gets a named Docker volume (`floci-aws-opensearch-{volumeId}`) created automatically. In memory mode the volume is removed on domain delete; in persistent modes it is retained unless `FLOCI_STORAGE_PRUNE_VOLUMES_ON_DELETE=true`. Set `FLOCI_SERVICES_OPENSEARCH_DATA_VOLUME` to choose the storage yourself: an absolute path bind-mounts `///` (a directory on the Docker daemon's host), and any other value is a Docker volume name the domain gets its own `---` volume of. When `FLOCI_DOCKER_RESOURCE_NAMESPACE` is set, the namespace is inserted into both forms, so two namespaced deployments sharing a Docker daemon never converge on one data directory through the same configured base. Linux daemon paths starting with `/` retain Linux path syntax when Floci runs on Windows; native Windows absolute paths retain their native handling. Before a configured bind directory is mounted, a temporary root container using the selected OpenSearch image copies ownership from the image's data directory and grants the owner write access. Only the directory itself is adjusted; existing files retain their ownership and permissions. Preparation failures abort domain startup. Storage named that way is never removed on domain delete, and a volume created when absent carries no Floci label, so neither a floci-scoped volume prune nor a testcontainers run's labelled-children sweep collects it: the operator named it, so its lifecycle is theirs. Legacy host-path mode (`FLOCI_STORAGE_HOST_PERSISTENT_PATH` set to an absolute path) gives each domain its own `/[/]opensearch/floci-aws[-]-opensearch---` directory, so two domains sharing a name across Regions or accounts never share one data directory; a domain whose record predates regional scoping keeps the bare `` directory while it still exists, since that is where its data lives. ## Examples diff --git a/pom.xml b/pom.xml index 2977e93674..e6ded21c18 100644 --- a/pom.xml +++ b/pom.xml @@ -682,6 +682,12 @@ ${aws.sdk.version} test + + software.amazon.awssdk + opensearch + ${aws.sdk.version} + test + software.amazon.awssdk applicationautoscaling diff --git a/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java b/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java index 23cfc12fe9..ab6bfd1961 100644 --- a/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java +++ b/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java @@ -40,6 +40,7 @@ import io.floci.aws.services.memorydb.container.MemoryDbContainerManager; import io.floci.aws.services.memorydb.proxy.MemoryDbProxyManager; import io.floci.aws.services.neptune.container.NeptuneContainerManager; import io.floci.aws.services.neptune.proxy.NeptuneProxyManager; +import io.floci.aws.services.opensearch.OpenSearchService; import io.floci.aws.services.pipes.PipesService; import io.floci.aws.services.rds.RdsService; import io.floci.aws.services.rds.container.RdsContainerManager; @@ -107,6 +108,7 @@ public class EmulatorLifecycle { private final AmazonMqService amazonMqService; private final FlinkContainerManager flinkContainerManager; private final KinesisAnalyticsV2Service kinesisAnalyticsService; + private final OpenSearchService openSearchService; private final SageMakerService sageMakerService; private final RdsService rdsService; private final TimestreamInfluxDbService timestreamInfluxDbService; @@ -157,6 +159,7 @@ public class EmulatorLifecycle { AmazonMqService amazonMqService, FlinkContainerManager flinkContainerManager, KinesisAnalyticsV2Service kinesisAnalyticsService, + OpenSearchService openSearchService, SageMakerService sageMakerService, RdsService rdsService, TimestreamInfluxDbService timestreamInfluxDbService, @@ -204,6 +207,7 @@ public class EmulatorLifecycle { this.amazonMqService = amazonMqService; this.flinkContainerManager = flinkContainerManager; this.kinesisAnalyticsService = kinesisAnalyticsService; + this.openSearchService = openSearchService; this.sageMakerService = sageMakerService; this.rdsService = rdsService; this.timestreamInfluxDbService = timestreamInfluxDbService; @@ -328,6 +332,13 @@ public class EmulatorLifecycle { return null; }); } + if (config.services().opensearch().enabled()) { + // Starts the domains' containers in the background, failing the future with the ones it could not. + openSearchService.restorePersistedRuntime().exceptionally(ex -> { + LOG.error("Failed to restore persisted OpenSearch domains at startup", ex); + return null; + }); + } if (config.services().elbv2().enabled()) { elbV2Service.restorePersistedRuntime(); } diff --git a/src/main/java/io/floci/aws/services/opensearch/OpenSearchDomainManager.java b/src/main/java/io/floci/aws/services/opensearch/OpenSearchDomainManager.java index 5a6fe29a72..baf803690e 100644 --- a/src/main/java/io/floci/aws/services/opensearch/OpenSearchDomainManager.java +++ b/src/main/java/io/floci/aws/services/opensearch/OpenSearchDomainManager.java @@ -21,7 +21,9 @@ import java.net.HttpURLConnection; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; +import java.util.List; import java.util.Optional; +import java.util.OptionalInt; /** * Manages the Docker lifecycle of OpenSearch containers for real-mode domains. @@ -40,6 +42,14 @@ public class OpenSearchDomainManager { private final PortAllocator portAllocator; private final EmulatorConfig config; private volatile boolean dockerUnavailableLogged; + private boolean shuttingDown; + + /** A container start that shutdown overtook: shutdown has removed the domains' containers, and this one too. */ + public static final class ShuttingDownException extends IllegalStateException { + public ShuttingDownException(String domainName) { + super("Floci is shutting down; OpenSearch domain " + domainName + " was not started"); + } + } @Inject public OpenSearchDomainManager(ContainerBuilder containerBuilder, @@ -65,10 +75,32 @@ public class OpenSearchDomainManager { * reachable */ public boolean tryStartDomain(Domain domain) { + return tryStart(domain, false); + } + + /** + * {@link #tryStartDomain} for a domain started before, which the startup restore brings back: it keeps the storage + * its record names, whatever {@code floci.services.opensearch.data-volume} says now, so it opens its own data. A + * domain whose record names a bind-mounted directory without keeping its path, from before the path was kept, is + * not started while that setting is gone, rather than started on other, empty storage. + */ + public boolean tryRestartDomain(Domain domain) { + if (domain.getVolumeOwnership() == VolumeOwnership.OPERATOR_BIND && !hasText(domain.getDataDirectory()) + && config.services().opensearch().dataVolume().filter(OpenSearchDomainManager::hasText).isEmpty()) { + throw new IllegalStateException("OpenSearch domain " + domain.getDomainName() + " keeps its data in the " + + "directory floci.services.opensearch.data-volume named, which is no longer set; set it again " + + "to start the domain on its data"); + } + return tryStart(domain, true); + } + + private boolean tryStart(Domain domain, boolean restart) { try { - startDomain(domain); + startDomain(domain, restart); dockerUnavailableLogged = false; return true; + } catch (ShuttingDownException e) { + throw e; } catch (RuntimeException e) { if (isDockerReachable()) { throw e; @@ -93,10 +125,16 @@ public class OpenSearchDomainManager { } public void startDomain(Domain domain) { + startDomain(domain, false); + } + + private void startDomain(Domain domain, boolean restart) { + if (isShuttingDown()) { + throw new ShuttingDownException(domain.getDomainName()); + } String image = resolveImage(domain.getEngineVersion()); AwsArnUtils.Arn arn = AwsArnUtils.parse(domain.getArn()); - String containerName = ContainerStorageHelper.resourceName(config, "opensearch", null, - arn.accountId() + "-" + arn.region() + "-" + domain.getDomainName()); + String containerName = containerName(domain); LOG.infov("Starting OpenSearch container for domain: {0} (version={1}, image={2})", domain.getDomainName(), domain.getEngineVersion(), image); @@ -151,7 +189,9 @@ public class OpenSearchDomainManager { Optional configuredDataVolume = config.services().opensearch().dataVolume() .filter(dataVolume -> !dataVolume.isBlank()); - if (configuredDataVolume.isPresent()) { + if (restart && applySavedOperatorStorage(specBuilder, domain, image)) { + // Started again on the operator storage its record names, where its data is. + } else if (configuredDataVolume.isPresent() && !(restart && isFlociManaged(domain))) { applyConfiguredDataVolume(specBuilder, domain, configuredDataVolume.get(), image); } else if (ContainerStorageHelper.isNamedVolumeMode(config)) { domain.setVolumeOwnership(VolumeOwnership.FLOCI_MANAGED); @@ -174,8 +214,18 @@ public class OpenSearchDomainManager { portAllocator.release(hostPort); throw e; } - domain.setContainerId(info.containerId()); - domain.setHostPort(hostPort); + // Under the lock markShuttingDown takes: a shutdown already under way has stopped the domains' containers by + // the IDs their records name, so a container it overtook removes itself; otherwise the record names it before + // shutdown reads it. + synchronized (this) { + if (shuttingDown) { + lifecycleManager.stopAndRemove(info.containerId(), null); + portAllocator.release(hostPort); + throw new ShuttingDownException(domain.getDomainName()); + } + domain.setContainerId(info.containerId()); + domain.setHostPort(hostPort); + } EndpointInfo endpoint = info.getEndpoint(OPENSEARCH_PORT); domain.setEndpoint("http://" + endpoint.host() + ":" + endpoint.port()); @@ -184,6 +234,109 @@ public class OpenSearchDomainManager { info.containerId(), domain.getDomainName(), endpoint, String.valueOf(hostPort)); } + /** + * Keeps the container a domain ran on before Floci restarted: one kept running across the shutdown + * ({@code floci.services.opensearch.keep-running-on-shutdown}), or one that outlived a Floci that was killed. It is + * started again if it stopped, its endpoint is read afresh, and its host port is reserved again so no other domain + * is handed it. Only the container ID the record names proves the container is this domain's. False when there is + * no such container to keep, or shutdown is under way. + */ + public boolean adoptRunningDomain(Domain domain) { + String containerId = domain.getContainerId(); + if (containerId == null || containerId.isBlank() || isShuttingDown()) { + return false; + } + ContainerInfo info; + try { + info = lifecycleManager.adopt(containerId, List.of(OPENSEARCH_PORT), + containerBuilder.resolveDockerNetwork(config.services().dockerNetwork())); + } catch (RuntimeException e) { + LOG.debugv("OpenSearch domain {0} has no container {1} to keep: {2}", domain.getDomainName(), + containerId, e.getMessage()); + return false; + } + OptionalInt hostPort = info.publishedHostPort(OPENSEARCH_PORT); + if (hostPort.isEmpty()) { + LOG.debugv("Container {0} of OpenSearch domain {1} publishes no port; not keeping it", containerId, + domain.getDomainName()); + return false; + } + EndpointInfo endpoint = info.getEndpoint(OPENSEARCH_PORT); + synchronized (this) { + if (shuttingDown) { + // The record still names the container, so shutdown removes it, or keeps it running. + return false; + } + portAllocator.markReserved(hostPort.getAsInt()); + domain.setHostPort(hostPort.getAsInt()); + domain.setEndpoint("http://" + endpoint.host() + ":" + endpoint.port()); + } + LOG.infov("Kept the running container {0} of OpenSearch domain {1} at {2}", containerId, + domain.getDomainName(), domain.getEndpoint()); + return true; + } + + /** + * Removes a deleted domain's container, by the ID its record names and under its name in either form, and + * releases its host port: for a delete the startup restore finishes. Each removal is confirmed with Docker, so + * this throws while Docker keeps the container, and the record still names it. + */ + public void removeDomainContainers(Domain domain) { + if (domain.getContainerId() != null && !domain.getContainerId().isBlank()) { + lifecycleManager.removeIfExistsStrict(domain.getContainerId()); + } + String containerName = containerName(domain); + lifecycleManager.removeIfExistsStrict(containerName); + String legacyName = ContainerStorageHelper.legacyDockerName(config, containerName); + if (!legacyName.equals(containerName)) { + lifecycleManager.removeIfExistsStrict(legacyName); + } + domain.setContainerId(null); + if (domain.getHostPort() != null) { + portAllocator.release(domain.getHostPort()); + domain.setHostPort(null); + } + } + + /** Stops any domain container from starting or being kept: shutdown is removing them. */ + public synchronized void markShuttingDown() { + shuttingDown = true; + } + + /** Whether shutdown is under way, after which no domain container starts. */ + public synchronized boolean isShuttingDown() { + return shuttingDown; + } + + /** + * Mounts the operator storage a domain started again keeps, the volume or the directory its record names, and + * leaves it the operator's, so deleting the domain never removes it. False for Floci-managed storage, which the + * storage mode places as it did at creation, and for a directory a record from before the path was kept does not + * name, which only the setting that named it can find again. + */ + private boolean applySavedOperatorStorage(ContainerBuilder.Builder specBuilder, Domain domain, String image) { + if (domain.getVolumeOwnership() == VolumeOwnership.OPERATOR_NAMED && hasText(domain.getDockerVolumeName())) { + ContainerStorageHelper.applyOperatorNamedVolume(specBuilder, lifecycleManager, domain.getDockerVolumeName(), + CONTAINER_DATA_PATH); + return true; + } + if (domain.getVolumeOwnership() == VolumeOwnership.OPERATOR_BIND && hasText(domain.getDataDirectory())) { + lifecycleManager.ensureBindDirectory(domain.getDataDirectory(), image, CONTAINER_DATA_PATH); + specBuilder.withBind(domain.getDataDirectory(), CONTAINER_DATA_PATH); + return true; + } + return false; + } + + /** Storage Floci chose and owns, which a record from before the ownership marker always names. */ + private static boolean isFlociManaged(Domain domain) { + return domain.getVolumeOwnership() == null || domain.getVolumeOwnership() == VolumeOwnership.FLOCI_MANAGED; + } + + private static boolean hasText(String value) { + return value != null && !value.isBlank(); + } + public boolean isReady(Domain domain) { String endpoint = domain.getEndpoint(); if (endpoint == null || endpoint.isBlank()) { @@ -224,6 +377,12 @@ public class OpenSearchDomainManager { LOG.infov("Stopped OpenSearch container for domain {0}", domain.getDomainName()); } + private String containerName(Domain domain) { + AwsArnUtils.Arn arn = AwsArnUtils.parse(domain.getArn()); + return ContainerStorageHelper.resourceName(config, "opensearch", null, + arn.accountId() + "-" + arn.region() + "-" + domain.getDomainName()); + } + /** * The domain's host data directory, scoped by the account and region its ARN carries, so two * domains sharing one name across regions or accounts never share a data directory: two @@ -328,6 +487,8 @@ public class OpenSearchDomainManager { } lifecycleManager.ensureBindDirectory(hostPath, image, CONTAINER_DATA_PATH); specBuilder.withBind(hostPath, CONTAINER_DATA_PATH); + // Kept, so the domain started again finds its data here whatever the setting says then. + domain.setDataDirectory(hostPath); return; } String volumeName = ContainerStorageHelper.prefixedDockerName( diff --git a/src/main/java/io/floci/aws/services/opensearch/OpenSearchService.java b/src/main/java/io/floci/aws/services/opensearch/OpenSearchService.java index d7f7d24ff3..226ffa2f0f 100644 --- a/src/main/java/io/floci/aws/services/opensearch/OpenSearchService.java +++ b/src/main/java/io/floci/aws/services/opensearch/OpenSearchService.java @@ -7,6 +7,7 @@ import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.AwsRegions; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.StoredResourceArns; +import io.floci.aws.core.common.StripedLocks; import io.floci.aws.core.common.docker.ContainerStorageHelper; import io.floci.aws.core.resource.ExplorerResource; import io.floci.aws.core.resource.ResourceProvider; @@ -37,8 +38,10 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; @@ -66,6 +69,19 @@ public class OpenSearchService implements ResourceProvider, StoredResourceArns { // The account and storage key of each domain a createDomain is creating, from its existence // check to its save, so a concurrent create of the same name is refused and starts no container. private final Set creating = ConcurrentHashMap.newKeySet(); + /** + * The domains the startup restore is bringing back, by account and storage key, which the readiness poller leaves + * alone: their records still name the endpoint they had before Floci restarted until the restore keeps their + * container or starts a new one. + */ + private final Set restoringDomains = ConcurrentHashMap.newKeySet(); + /** + * Monitors over one stored domain, by account and storage key. The restore reads a domain again, and ends its + * restore, under its lock, under which {@code DeleteDomain} finds whether a restore is starting the domain's + * container. If one is, the delete leaves the domain {@code Deleted} for the restore to finish once that start is + * through, so the restore never writes a deleted domain back or leaves its container running. + */ + private final StripedLocks storedDomainLocks = new StripedLocks(256); @Inject public OpenSearchService(StorageFactory storageFactory, EmulatorConfig config, @@ -96,13 +112,216 @@ public class OpenSearchService implements ResourceProvider, StoredResourceArns { @PreDestroy public void shutdown() { poller.shutdownNow(); - if (!config.services().opensearch().mock() && !config.services().opensearch().keepRunningOnShutdown()) { + if (config.services().opensearch().mock()) { + return; + } + // First, so a restore still starting containers stops, and a start it overtakes removes its own. + domainManager.markShuttingDown(); + if (!config.services().opensearch().keepRunningOnShutdown()) { for (Domain domain : allDomains()) { domainManager.stopDomain(domain); } } } + /** + * Brings the persisted domains' containers back after Floci restarts. Shutdown removes them, unless + * {@code keep-running-on-shutdown} keeps them, so a domain read back from storage named an endpoint nothing + * answered on. Each domain goes back to {@code Processing} at once, and the containers come back in the + * background, so Floci does not wait for them to report itself ready; the readiness poller leaves a domain alone + * while its restore runs, and reports it ready once its container answers. + * + *

A container that outlived Floci, kept running or left by a Floci that was killed, is kept, found by the ID + * the record names. Otherwise the domain gets a new container, as {@code CreateDomain} starts one, on the data it + * kept: its Docker volume or data directory, so its indices are back. A domain with no reachable Docker daemon is + * not processing and reports an AWS-shaped endpoint, as one created then does. A domain deleted during its restore + * is {@code Deleted} until its container has started and been removed, as AWS reports a domain being deleted, and + * is gone then; one still {@code Deleted} at the next start has its container and data removed then. Every domain + * is tried, and the ones that could not be restored fail the returned future together. A shutdown during the + * restore leaves the domains not started yet as they are, for the next start. + */ + public CompletableFuture restorePersistedRuntime() { + if (config.services().opensearch().mock()) { + return CompletableFuture.completedFuture(null); + } + // Records stored before domains were keyed by Region move onto their keys first, as at startup. + migrateLegacyDomainKeys(); + List pending = new ArrayList<>(); + for (AccountAwareStorageBackend.AccountEntry entry + : domainStore.scanAllAccountEntries(key -> key.contains("::"))) { + RestoringDomain restoring = prepareRestore(entry.accountId(), entry.key()); + if (restoring != null) { + pending.add(restoring); + } + } + return CompletableFuture.runAsync(() -> { + RuntimeException failure = null; + for (RestoringDomain restoring : pending) { + if (domainManager.isShuttingDown()) { + // Domains not reached yet stay as they are, which the next start restores. + break; + } + Domain domain = restoring.domain(); + try { + restoreDomain(restoring); + } catch (OpenSearchDomainManager.ShuttingDownException e) { + LOG.debugv("OpenSearch domain {0} not restored: {1}", domain.getDomainName(), e.getMessage()); + } catch (RuntimeException e) { + RuntimeException restoreFailure = new IllegalStateException("Could not restore OpenSearch domain " + + domain.getDomainName() + " of account " + restoring.accountId(), e); + if (failure == null) { + failure = restoreFailure; + } else { + failure.addSuppressed(restoreFailure); + } + } finally { + endRestore(restoring); + } + } + if (failure != null) { + throw failure; + } + }); + } + + /** Marks a domain the restore brings back, under its lock; null for one it leaves as it is. */ + private RestoringDomain prepareRestore(String accountId, String key) { + synchronized (storedDomainLock(accountId, key)) { + Domain domain = domainStore.getForAccount(accountId, key).orElse(null); + if (domain == null) { + return null; + } + String region; + try { + region = AwsArnUtils.parse(domain.getArn()).region(); + } catch (IllegalArgumentException e) { + LOG.warnv("Not restoring OpenSearch domain {0}: its ARN {1} cannot be parsed", + domain.getDomainName(), domain.getArn()); + return null; + } + RestoringDomain restoring = new RestoringDomain(accountId, key, region, domain); + restoringDomains.add(restoring.lockKey()); + // A domain still Deleted was deleted during a restore Floci did not live to finish: the delete stands. + if (!domain.isDeleted()) { + domain.setProcessing(true); + domainStore.putForAccount(accountId, key, domain); + } + return restoring; + } + } + + private void restoreDomain(RestoringDomain restoring) { + Domain domain = restoring.domain(); + Object lock = storedDomainLock(restoring.accountId(), restoring.key()); + Boolean deleted; + synchronized (lock) { + deleted = storedDeleted(restoring); + } + if (deleted == null) { + return; + } + if (deleted) { + finishDelete(restoring); + return; + } + boolean running; + try { + running = domainManager.adoptRunningDomain(domain) || domainManager.tryRestartDomain(domain); + } catch (OpenSearchDomainManager.ShuttingDownException e) { + throw e; + } catch (RuntimeException e) { + // A container Docker would not start: the domain has none behind it, as when no daemon is reachable. + Boolean deletedNow; + synchronized (lock) { + deletedNow = storedDeleted(restoring); + if (Boolean.FALSE.equals(deletedNow)) { + restoringDomains.remove(restoring.lockKey()); + reportNoContainer(domain, restoring.region()); + domainStore.putForAccount(restoring.accountId(), restoring.key(), domain); + } + } + if (Boolean.TRUE.equals(deletedNow)) { + finishDelete(restoring); + } + throw e; + } + Boolean deletedNow; + synchronized (lock) { + deletedNow = storedDeleted(restoring); + if (Boolean.FALSE.equals(deletedNow)) { + // Its restore ends here: from now on the poller reports it ready, and a delete removes the container. + restoringDomains.remove(restoring.lockKey()); + if (!running) { + reportNoContainer(domain, restoring.region()); + } + domainStore.putForAccount(restoring.accountId(), restoring.key(), domain); + return; + } + } + if (deletedNow == null) { + // Its record went, or another domain took its name, with no delete of its own: only the container this + // restore kept or started goes, by its ID, leaving the name, the record and the data to whoever has them. + domainManager.stopDomain(domain); + return; + } + // Deleted while its container started: the delete finishes now the container is there to remove. + finishDelete(restoring); + } + + /** A domain with no container behind it, as {@link #createDomain} reports one with no Docker daemon reachable. */ + private static void reportNoContainer(Domain domain, String region) { + domain.setProcessing(false); + domain.setEndpoint(synthesizedEndpoint(domain, region)); + } + + /** + * Finishes the delete of a domain deleted during its restore: its container and data go, then its record. While + * Docker keeps the container this throws, and the record stays {@code Deleted}, naming it, for the next start. + */ + private void finishDelete(RestoringDomain restoring) { + Domain domain = restoring.domain(); + domainManager.removeDomainContainers(domain); + domainManager.removeDomainStorage(domain); + synchronized (storedDomainLock(restoring.accountId(), restoring.key())) { + restoringDomains.remove(restoring.lockKey()); + if (Boolean.TRUE.equals(storedDeleted(restoring))) { + domainStore.deleteForAccount(restoring.accountId(), restoring.key()); + } + } + LOG.infov("Deleted OpenSearch domain: {0}", domain.getDomainName()); + } + + /** + * Ends a domain's restore, if it has not ended already: the poller and {@code DeleteDomain} treat the domain as any + * other again. + */ + private void endRestore(RestoringDomain restoring) { + synchronized (storedDomainLock(restoring.accountId(), restoring.key())) { + restoringDomains.remove(restoring.lockKey()); + } + } + + /** + * Whether the stored domain is deleted, or null when it is gone or another domain was created under its name. + */ + private Boolean storedDeleted(RestoringDomain restoring) { + return domainStore.getForAccount(restoring.accountId(), restoring.key()) + .filter(current -> Objects.equals(current.getCreatedAt(), restoring.domain().getCreatedAt())) + .map(Domain::isDeleted) + .orElse(null); + } + + private Object storedDomainLock(String accountId, String key) { + return storedDomainLocks.lockFor(accountId + "/" + key); + } + + /** A domain the restore brings back, with the account, storage key and Region it is stored under. */ + private record RestoringDomain(String accountId, String key, String region, Domain domain) { + String lockKey() { + return accountId + "/" + key; + } + } + /** * Bag of optional configuration blocks parsed by {@link OpenSearchController} * and round-tripped on Describe. Any field can be null when the request @@ -344,16 +563,61 @@ public class OpenSearchService implements ResourceProvider, StoredResourceArns { public Domain deleteDomain(String domainName, String region) { Domain domain = describeDomain(domainName, region); - domain.setDeleted(true); + String accountId = regionResolver.getAccountId(); + String key = storageKey(region, domainName); + boolean restoring; + boolean deletedBefore; + synchronized (storedDomainLock(accountId, key)) { + deletedBefore = domain.isDeleted(); + domain.setDeleted(true); + restoring = restoringDomains.contains(accountId + "/" + key); + if (restoring) { + // The startup restore is starting its container, and finishes the delete once that start is through. + // Until then the domain reads Deleted, as AWS reports a domain being deleted, and its name stays taken. + domainStore.putForAccount(accountId, key, domain); + } + } + if (restoring) { + LOG.infov("Deleting OpenSearch domain {0} once its restore is through", domainName); + return domain; + } + if (deletedBefore && !config.services().opensearch().mock()) { + return retryDelete(accountId, key, domain); + } if (!config.services().opensearch().mock()) { domainManager.stopDomain(domain); domainManager.removeDomainStorage(domain); } - domainStore.deleteForAccount(regionResolver.getAccountId(), storageKey(region, domainName)); + domainStore.deleteForAccount(accountId, key); LOG.infov("Deleted OpenSearch domain: {0}", domainName); return domain; } + /** + * Retries a delete the restore could not finish, Docker keeping the container: removed the same confirmed way, or + * left {@code Deleted}, naming the container, for another delete or the next start. One retry runs at a time, under + * the domain's lock, on the record still stored: a retry that waited finds it gone, so it never removes, by name, + * the container of a domain created again since. + */ + private Domain retryDelete(String accountId, String key, Domain domain) { + synchronized (storedDomainLock(accountId, key)) { + Domain current = domainStore.getForAccount(accountId, key).orElse(null); + if (current == null || !Objects.equals(current.getCreatedAt(), domain.getCreatedAt())) { + return domain; + } + try { + domainManager.removeDomainContainers(current); + } catch (RuntimeException e) { + LOG.warnv("OpenSearch domain {0} is still being deleted: {1}", current.getDomainName(), e.getMessage()); + return current; + } + domainManager.removeDomainStorage(current); + domainStore.deleteForAccount(accountId, key); + LOG.infov("Deleted OpenSearch domain: {0}", current.getDomainName()); + return current; + } + } + /** Gives the domain a new map, its tags with {@code tags} added, one tag call at a time. */ public synchronized void addTags(String arn, Map tags) { Domain domain = findByArn(arn); @@ -635,7 +899,8 @@ public class OpenSearchService implements ResourceProvider, StoredResourceArns { void pollReadiness() { try { for (Domain domain : allDomains()) { - if (domain.isProcessing() && domainManager.isReady(domain)) { + if (domain.isProcessing() && !restoringDomains.contains(restoringKey(domain)) + && domainManager.isReady(domain)) { domain.setProcessing(false); putDomain(domain); LOG.infov("OpenSearch domain {0} is ready at {1}", @@ -651,6 +916,16 @@ public class OpenSearchService implements ResourceProvider, StoredResourceArns { return domainStore.scanAllAccounts(); } + /** The account and storage key the domain's ARN names, as its restore is known by; empty for an unparsable ARN. */ + private static String restoringKey(Domain domain) { + try { + AwsArnUtils.Arn arn = AwsArnUtils.parse(domain.getArn()); + return arn.accountId() + "/" + storageKey(arn.region(), domain.getDomainName()); + } catch (IllegalArgumentException e) { + return ""; + } + } + /** * Persists a domain under the key its ARN names, so the poller writes a record back to the * account and region that own it rather than to whatever account the background thread diff --git a/src/main/java/io/floci/aws/services/opensearch/model/Domain.java b/src/main/java/io/floci/aws/services/opensearch/model/Domain.java index 3712b7287f..2ec51e1d4e 100644 --- a/src/main/java/io/floci/aws/services/opensearch/model/Domain.java +++ b/src/main/java/io/floci/aws/services/opensearch/model/Domain.java @@ -110,6 +110,14 @@ public class Domain { @JsonProperty("VolumeOwnership") private VolumeOwnership volumeOwnership; + /** + * The host directory the domain's data is bind-mounted from, when + * {@code floci.services.opensearch.data-volume} named one at creation; null otherwise, and on records written + * before this field existed. A domain started again keeps it, whatever the setting says then. + */ + @JsonProperty("DataDirectory") + private String dataDirectory; + @JsonProperty("CreatedAt") @JsonFormat(shape = JsonFormat.Shape.NUMBER) private Instant createdAt; @@ -324,6 +332,14 @@ public class Domain { this.volumeOwnership = volumeOwnership; } + public String getDataDirectory() { + return dataDirectory; + } + + public void setDataDirectory(String dataDirectory) { + this.dataDirectory = dataDirectory; + } + public Instant getCreatedAt() { return createdAt; } diff --git a/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java index 62e9c63930..eb58a7c6b3 100644 --- a/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java +++ b/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java @@ -39,6 +39,7 @@ import io.floci.aws.services.memorydb.container.MemoryDbContainerManager; import io.floci.aws.services.memorydb.proxy.MemoryDbProxyManager; import io.floci.aws.services.neptune.container.NeptuneContainerManager; import io.floci.aws.services.neptune.proxy.NeptuneProxyManager; +import io.floci.aws.services.opensearch.OpenSearchService; import io.floci.aws.services.pipes.PipesService; import io.floci.aws.services.rds.RdsService; import io.floci.aws.services.rds.container.RdsContainerManager; @@ -128,6 +129,8 @@ class EmulatorLifecycleTest { @Mock private AmazonMqService amazonMqService; @Mock private KinesisAnalyticsV2Service kinesisAnalyticsService; @Mock private EmulatorConfig.KinesisAnalyticsServiceConfig kinesisAnalyticsServiceConfig; + @Mock private OpenSearchService openSearchService; + @Mock private EmulatorConfig.OpenSearchServiceConfig openSearchServiceConfig; @Mock private EmulatorConfig.AmazonMqServiceConfig amazonMqServiceConfig; @Mock private EmulatorConfig.SageMakerServiceConfig sageMakerServiceConfig; @Mock private EksService eksService; @@ -179,6 +182,8 @@ class EmulatorLifecycleTest { Mockito.lenient().when(codeArtifactServiceConfig.enabled()).thenReturn(true); Mockito.lenient().when(servicesConfig.kinesisAnalytics()).thenReturn(kinesisAnalyticsServiceConfig); Mockito.lenient().when(kinesisAnalyticsServiceConfig.enabled()).thenReturn(false); + Mockito.lenient().when(servicesConfig.opensearch()).thenReturn(openSearchServiceConfig); + Mockito.lenient().when(openSearchServiceConfig.enabled()).thenReturn(false); Mockito.lenient().when(servicesConfig.amazonmq()).thenReturn(amazonMqServiceConfig); Mockito.lenient().when(amazonMqServiceConfig.enabled()).thenReturn(false); Mockito.lenient().when(servicesConfig.sagemaker()).thenReturn(sageMakerServiceConfig); @@ -199,6 +204,7 @@ class EmulatorLifecycleTest { memoryDbContainerManager, memoryDbProxyManager, memoryDbService, docDbContainerManager, neptuneContainerManager, neptuneProxyManager, rabbitMqManager, amazonMqService, flinkContainerManager, kinesisAnalyticsService, + openSearchService, sageMakerService, rdsService, timestreamInfluxDbService, elbV2Service, elbClassicService, ecsService, initializationHooksRunner, sqsPoller, kinesisPoller, dynamodbStreamsPoller, @@ -570,6 +576,48 @@ class EmulatorLifecycleTest { verify(kinesisAnalyticsService, never()).restorePersistedRuntime(); } + @Test + void restoresPersistedOpenSearchDomainsAfterStorageLoad() { + stubStorageConfig(); + when(openSearchServiceConfig.enabled()).thenReturn(true); + when(openSearchService.restorePersistedRuntime()).thenReturn(CompletableFuture.completedFuture(null)); + when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false); + when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false); + + emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class)); + + InOrder inOrder = Mockito.inOrder(storageFactory, openSearchService); + inOrder.verify(storageFactory).loadAll(); + inOrder.verify(openSearchService).restorePersistedRuntime(); + } + + @Test + void aFailedOpenSearchRestoreDoesNotStopTheOtherRestores() { + stubStorageConfig(); + when(openSearchServiceConfig.enabled()).thenReturn(true); + when(elbv2ServiceConfig.enabled()).thenReturn(true); + when(openSearchService.restorePersistedRuntime()).thenReturn(CompletableFuture.failedFuture( + new IllegalStateException("Could not restore OpenSearch domain demo"))); + when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false); + when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false); + + emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class)); + + verify(elbV2Service).restorePersistedRuntime(); + verify(initLifecycleState).markReadyCompleted(); + } + + @Test + void leavesOpenSearchDomainsUntouchedWhenOpenSearchIsDisabled() { + stubStorageConfig(); + when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false); + when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false); + + emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class)); + + verify(openSearchService, never()).restorePersistedRuntime(); + } + @Test void restoresPersistedAmazonMqBrokersAfterStorageLoad() { stubStorageConfig(); diff --git a/src/test/java/io/floci/aws/services/opensearch/OpenSearchDomainManagerTest.java b/src/test/java/io/floci/aws/services/opensearch/OpenSearchDomainManagerTest.java index 16b835cf8c..e7906d6c6d 100644 --- a/src/test/java/io/floci/aws/services/opensearch/OpenSearchDomainManagerTest.java +++ b/src/test/java/io/floci/aws/services/opensearch/OpenSearchDomainManagerTest.java @@ -20,6 +20,7 @@ import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.MockMakers; import org.mockito.MockedStatic; +import org.mockito.Mockito; import java.io.IOException; import java.nio.file.Files; @@ -29,11 +30,13 @@ import java.util.Map; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.CALLS_REAL_METHODS; import static org.mockito.Mockito.RETURNS_SELF; import static org.mockito.Mockito.doThrow; @@ -296,6 +299,8 @@ class OpenSearchDomainManagerTest { verify(builder, never()).withNamedVolume(anyString(), anyString()); assertNull(domain.getDockerVolumeName()); assertEquals(VolumeOwnership.OPERATOR_BIND, domain.getVolumeOwnership()); + // Kept, for the domain started again to find its data whatever the setting says then. + assertEquals(expectedBind, domain.getDataDirectory()); } /** @@ -362,6 +367,90 @@ class OpenSearchDomainManagerTest { assertEquals(VolumeOwnership.OPERATOR_BIND, domain.getVolumeOwnership()); } + /** + * A domain created on an operator-named volume and started again once that volume is no longer configured keeps + * it, data included, and it stays the operator's: deleting the domain does not remove it. + */ + @Test + void aDomainStartedAgainKeepsItsOperatorNamedVolume() { + when(storage.pruneVolumesOnDelete()).thenReturn(true); + Domain domain = domain("000000000000", "us-east-1"); + domain.setVolumeId("abc123"); + domain.setDockerVolumeName("opensearch-data-000000000000-us-east-1-my-domain"); + domain.setVolumeOwnership(VolumeOwnership.OPERATOR_NAMED); + + manager.tryRestartDomain(domain); + + verify(lifecycleManager).ensureUnmanagedVolume("opensearch-data-000000000000-us-east-1-my-domain"); + verify(builder).withNamedVolume("opensearch-data-000000000000-us-east-1-my-domain", "/usr/share/opensearch/data"); + assertEquals("opensearch-data-000000000000-us-east-1-my-domain", domain.getDockerVolumeName()); + assertEquals(VolumeOwnership.OPERATOR_NAMED, domain.getVolumeOwnership()); + manager.removeDomainStorage(domain); + verify(lifecycleManager, never()).removeVolume(anyString()); + } + + /** A domain started again keeps the operator-named volume its record names, whatever the setting names now. */ + @Test + void aDomainStartedAgainKeepsItsOperatorNamedVolumeWhateverTheSettingSays() { + when(opensearch.dataVolume()).thenReturn(Optional.of("other-data")); + Domain domain = domain("000000000000", "us-east-1"); + domain.setDockerVolumeName("opensearch-data-000000000000-us-east-1-my-domain"); + domain.setVolumeOwnership(VolumeOwnership.OPERATOR_NAMED); + + manager.tryRestartDomain(domain); + + verify(builder).withNamedVolume("opensearch-data-000000000000-us-east-1-my-domain", "/usr/share/opensearch/data"); + verify(lifecycleManager, never()).ensureUnmanagedVolume("other-data-000000000000-us-east-1-my-domain"); + assertEquals("opensearch-data-000000000000-us-east-1-my-domain", domain.getDockerVolumeName()); + } + + /** A domain started again keeps the bind-mounted directory its record names, once the setting is gone too. */ + @Test + void aDomainStartedAgainKeepsItsBindDirectory() { + Domain domain = domain("000000000000", "us-east-1"); + domain.setVolumeOwnership(VolumeOwnership.OPERATOR_BIND); + domain.setDataDirectory("/srv/opensearch/000000000000/us-east-1/my-domain"); + + manager.tryRestartDomain(domain); + + verify(lifecycleManager).ensureBindDirectory("/srv/opensearch/000000000000/us-east-1/my-domain", + "opensearchproject/opensearch:2.11.0", "/usr/share/opensearch/data"); + verify(builder).withBind("/srv/opensearch/000000000000/us-east-1/my-domain", "/usr/share/opensearch/data"); + verify(builder, never()).withNamedVolume(anyString(), anyString()); + assertEquals(VolumeOwnership.OPERATOR_BIND, domain.getVolumeOwnership()); + } + + /** + * A domain whose record names a bind-mounted directory without its path, from before the path was kept, is not + * started once the setting that named it is gone, rather than started on other, empty storage. + */ + @Test + void aDomainWhoseDirectoryIsNoLongerKnownIsNotStartedOnOtherStorage() { + Domain domain = domain("000000000000", "us-east-1"); + domain.setVolumeOwnership(VolumeOwnership.OPERATOR_BIND); + + IllegalStateException refused = assertThrows(IllegalStateException.class, + () -> manager.tryRestartDomain(domain)); + + assertTrue(refused.getMessage().contains("floci.services.opensearch.data-volume"), refused.getMessage()); + verify(lifecycleManager, never()).createAndStart(any()); + } + + /** A Floci-managed domain started again keeps its own volume, though a data volume is configured now. */ + @Test + void aFlociManagedDomainStartedAgainKeepsItsVolume() { + when(opensearch.dataVolume()).thenReturn(Optional.of("opensearch-data")); + Domain domain = domain("000000000000", "us-east-1"); + domain.setDockerVolumeName("floci-aws-opensearch-abc123"); + domain.setVolumeOwnership(VolumeOwnership.FLOCI_MANAGED); + + manager.tryRestartDomain(domain); + + verify(builder).withNamedVolume("floci-aws-opensearch-abc123", "/usr/share/opensearch/data"); + verify(lifecycleManager, never()).ensureUnmanagedVolume(anyString()); + assertEquals(VolumeOwnership.FLOCI_MANAGED, domain.getVolumeOwnership()); + } + /** An operator-named volume is never deleted with the domain, whatever the storage policy. */ @Test void removeDomainStorageRetainsOperatorNamedVolume() { @@ -643,6 +732,127 @@ class OpenSearchDomainManagerTest { .toAbsolutePath().normalize().toString(), "/usr/share/opensearch/data"); } + /** A start shutdown overtakes removes the container it started and gives its port back. */ + @Test + void aStartShutdownOvertakesRemovesItsContainer() { + Domain domain = domain("000000000000", "us-east-1"); + when(lifecycleManager.createAndStart(any())).thenAnswer(start -> { + manager.markShuttingDown(); + return new ContainerLifecycleManager.ContainerInfo("container-id", Map.of( + 9200, new ContainerLifecycleManager.EndpointInfo("172.17.0.5", 9200))); + }); + + assertThrows(OpenSearchDomainManager.ShuttingDownException.class, () -> manager.startDomain(domain)); + + verify(lifecycleManager).stopAndRemove("container-id", null); + verify(portAllocator).release(9400); + assertNull(domain.getContainerId()); + } + + /** Once shutdown is under way no container starts, and the refusal is not mistaken for a missing daemon. */ + @Test + void noDomainStartsAfterShutdown() { + manager.markShuttingDown(); + when(lifecycleManager.isDockerReachable()).thenReturn(false); + + assertThrows(OpenSearchDomainManager.ShuttingDownException.class, + () -> manager.tryStartDomain(domain("000000000000", "us-east-1"))); + + verify(lifecycleManager, never()).createAndStart(any()); + } + + /** The container a domain's record names is kept: its endpoint read afresh, its host port reserved again. */ + @Test + void aRunningContainerIsKept() { + Domain domain = domain("000000000000", "us-east-1"); + domain.setContainerId("old-id"); + domain.setEndpoint("http://172.17.0.2:9200"); + when(lifecycleManager.adopt(eq("old-id"), eq(List.of(9200)), any())).thenReturn( + new ContainerLifecycleManager.ContainerInfo("old-id", + Map.of(9200, new ContainerLifecycleManager.EndpointInfo("172.17.0.9", 9200)), + Map.of(9200, 9411))); + + assertTrue(manager.adoptRunningDomain(domain)); + + verify(portAllocator).markReserved(9411); + assertEquals(9411, domain.getHostPort()); + assertEquals("http://172.17.0.9:9200", domain.getEndpoint()); + assertEquals("old-id", domain.getContainerId()); + } + + /** + * No container is kept for a domain whose record names none, whose container is gone, which publishes no port, or + * once shutdown is under way, before or while it is looked for. + */ + @Test + void aContainerThatCannotBeKeptIsNot() { + Domain none = domain("000000000000", "us-east-1"); + assertFalse(manager.adoptRunningDomain(none)); + verify(lifecycleManager, never()).adopt(anyString(), any(), any()); + + Domain gone = domain("000000000000", "us-east-1"); + gone.setContainerId("gone-id"); + when(lifecycleManager.adopt(eq("gone-id"), any(), any())) + .thenThrow(new IllegalStateException("No such container: gone-id")); + assertFalse(manager.adoptRunningDomain(gone)); + + Domain unpublished = domain("000000000000", "us-east-1"); + unpublished.setContainerId("unpublished-id"); + when(lifecycleManager.adopt(eq("unpublished-id"), any(), any())).thenReturn( + new ContainerLifecycleManager.ContainerInfo("unpublished-id", + Map.of(9200, new ContainerLifecycleManager.EndpointInfo("172.17.0.9", 9200)))); + assertFalse(manager.adoptRunningDomain(unpublished)); + + Domain overtaken = domain("000000000000", "us-east-1"); + overtaken.setContainerId("overtaken-id"); + when(lifecycleManager.adopt(eq("overtaken-id"), any(), any())).thenAnswer(adopt -> { + manager.markShuttingDown(); + return new ContainerLifecycleManager.ContainerInfo("overtaken-id", + Map.of(9200, new ContainerLifecycleManager.EndpointInfo("172.17.0.9", 9200)), Map.of(9200, 9412)); + }); + assertFalse(manager.adoptRunningDomain(overtaken)); + verify(portAllocator, never()).markReserved(Mockito.anyInt()); + assertEquals("overtaken-id", overtaken.getContainerId(), "shutdown still finds it by the ID its record names"); + + Domain late = domain("000000000000", "us-east-1"); + late.setContainerId("late-id"); + assertFalse(manager.adoptRunningDomain(late)); + verify(lifecycleManager, never()).adopt(eq("late-id"), any(), any()); + } + + /** A deleted domain's container goes by its ID and under both name forms, each removal confirmed. */ + @Test + void removingADeletedDomainsContainersConfirmsEach() { + Domain domain = domain("000000000000", "us-east-1"); + domain.setContainerId("old-id"); + domain.setHostPort(9405); + + manager.removeDomainContainers(domain); + + String current = ContainerStorageHelper.resourceName(config, "opensearch", null, + "000000000000-us-east-1-my-domain"); + ArgumentCaptor removed = ArgumentCaptor.forClass(String.class); + verify(lifecycleManager, times(3)).removeIfExistsStrict(removed.capture()); + assertEquals(List.of("old-id", current, ContainerStorageHelper.legacyDockerName(config, current)), + removed.getAllValues()); + verify(portAllocator).release(9405); + assertNull(domain.getContainerId()); + assertNull(domain.getHostPort()); + } + + /** A container Docker will not remove stays named in the record, for a later attempt. */ + @Test + void aContainerDockerKeepsStaysNamed() { + Domain domain = domain("000000000000", "us-east-1"); + domain.setContainerId("kept-id"); + doThrow(new IllegalStateException("Failed to remove stale container kept-id")) + .when(lifecycleManager).removeIfExistsStrict("kept-id"); + + assertThrows(IllegalStateException.class, () -> manager.removeDomainContainers(domain)); + + assertEquals("kept-id", domain.getContainerId()); + } + private Domain domain(String accountId, String region) { Domain domain = new Domain(); domain.setDomainName("my-domain"); diff --git a/src/test/java/io/floci/aws/services/opensearch/OpenSearchDomainRestartNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/opensearch/OpenSearchDomainRestartNightlyIntegrationTest.java new file mode 100644 index 0000000000..f88aca3b6a --- /dev/null +++ b/src/test/java/io/floci/aws/services/opensearch/OpenSearchDomainRestartNightlyIntegrationTest.java @@ -0,0 +1,140 @@ +package io.floci.aws.services.opensearch; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.github.dockerjava.api.DockerClient; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.opensearch.model.Domain; +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.DockerAvailability; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.opensearch.OpenSearchClient; +import software.amazon.awssdk.services.opensearch.model.DomainStatus; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * #5664: an OpenSearch domain comes back after Floci restarts with the documents it held. Shutdown removes the + * domain's container; the startup restore starts a new one on the domain's data, so a document indexed before is still + * there. Removing the container stands in for the shutdown, reloading the domain records from disk for what a + * restart reads back, and the restore is what startup calls. + * + *

A nightly check: it runs a real OpenSearch node, which the shared test configuration mocks, with the domain + * records on disk, which it keeps in memory. + */ +@QuarkusTest +@TestProfile(OpenSearchDomainRestartNightlyIntegrationTest.Profile.class) +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") +// Bounded waits: the OpenSearch image's pull, then the node starting twice. +@Timeout(value = 10, unit = TimeUnit.MINUTES) +class OpenSearchDomainRestartNightlyIntegrationTest { + + /** Real OpenSearch nodes, their domain records on disk. */ + public static final class Profile implements QuarkusTestProfile { + // Its own directory, so the restore finds no domain records but this test's. + private static final String DATA = "./target/test-data/opensearch-restart-" + UUID.randomUUID(); + + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.opensearch.mock", "false", + "floci.storage.services.opensearch.mode", "persistent", + "floci.storage.persistent-path", DATA); + } + } + + private static final String ACCOUNT = "000000000000"; + private static final String REGION = "us-east-1"; + private static final String DOCUMENT = "/restart-check/_doc/1"; + private static final Duration DOMAIN_TIMEOUT = Duration.ofMinutes(4); + + private final HttpClient http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1) + .connectTimeout(Duration.ofSeconds(5)).build(); + + @Inject + DockerClient dockerClient; + + @Inject + OpenSearchService openSearchService; + + @Inject + StorageFactory storageFactory; + + @BeforeEach + void requireDocker() { + Assumptions.assumeTrue(DockerAvailability.answers(dockerClient), + "Docker daemon must be available for the OpenSearch restart check"); + } + + @Test + void aDomainKeepsItsDocumentsAcrossARestart() throws Exception { + String name = "restart-" + UUID.randomUUID().toString().substring(0, 8); + try (OpenSearchClient client = AwsTestClients.create(OpenSearchClient.builder(), ACCOUNT, Region.of(REGION))) { + client.createDomain(request -> request.domainName(name).engineVersion(OpenSearchVersions.DEFAULT_VERSION)); + try { + String endpoint = awaitReady(client, name); + assertEquals(201, send(endpoint, "PUT", DOCUMENT + "?refresh=true", "{\"kept\":true}").statusCode()); + Domain running = openSearchService.describeDomain(name, REGION); + String container = running.getContainerId(); + + dockerClient.removeContainerCmd(container).withForce(true).exec(); + // What a restart reads back: the records on disk, not the ones in memory. + storageFactory.create("opensearch", "opensearch-domains.json", + new TypeReference>() {}).load(); + Domain reloaded = openSearchService.describeDomain(name, REGION); + assertNotSame(running, reloaded); + assertEquals(container, reloaded.getContainerId()); + openSearchService.restorePersistedRuntime().join(); + + String restored = awaitReady(client, name); + assertNotEquals(container, openSearchService.describeDomain(name, REGION).getContainerId()); + HttpResponse document = send(restored, "GET", DOCUMENT, null); + assertEquals(200, document.statusCode()); + assertTrue(document.body().contains("\"kept\":true"), document.body()); + } finally { + client.deleteDomain(request -> request.domainName(name)); + } + } + } + + /** Waits for the domain to stop processing and returns its endpoint as DescribeDomain reports it. */ + private static String awaitReady(OpenSearchClient client, String name) { + await("domain " + name + " ready").atMost(DOMAIN_TIMEOUT).pollInterval(Duration.ofSeconds(2)) + .until(() -> !describe(client, name).processing()); + return "http://" + describe(client, name).endpoint(); + } + + private static DomainStatus describe(OpenSearchClient client, String name) { + return client.describeDomain(request -> request.domainName(name)).domainStatus(); + } + + private HttpResponse send(String endpoint, String method, String path, String body) throws Exception { + HttpRequest request = HttpRequest.newBuilder(URI.create(endpoint + path)) + .header("Content-Type", "application/json") + .method(method, body == null ? HttpRequest.BodyPublishers.noBody() + : HttpRequest.BodyPublishers.ofString(body)) + .timeout(Duration.ofSeconds(30)) + .build(); + return http.send(request, HttpResponse.BodyHandlers.ofString()); + } +} diff --git a/src/test/java/io/floci/aws/services/opensearch/OpenSearchServiceTest.java b/src/test/java/io/floci/aws/services/opensearch/OpenSearchServiceTest.java index d9af68fe76..6f196cf8e4 100644 --- a/src/test/java/io/floci/aws/services/opensearch/OpenSearchServiceTest.java +++ b/src/test/java/io/floci/aws/services/opensearch/OpenSearchServiceTest.java @@ -10,19 +10,26 @@ import io.floci.aws.services.opensearch.model.Domain; import io.floci.aws.services.opensearch.model.VolumeOwnership; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.InOrder; import org.mockito.Mockito; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -43,6 +50,7 @@ class OpenSearchServiceTest { private static final String ACCOUNT = "000000000000"; private static final String US_EAST_1 = "us-east-1"; private static final String EU_WEST_1 = "eu-west-1"; + private static final String OTHER_ACCOUNT = "111111111111"; private OpenSearchService service; private AccountAwareStorageBackend domainStore; @@ -365,4 +373,375 @@ class OpenSearchServiceTest { assertFalse(service.describeDomain("poller-scoped", EU_WEST_1).isProcessing()); assertTrue(domainStore.keysForAccount(ACCOUNT).contains(EU_WEST_1 + "::poller-scoped")); } + + /** + * Each persisted domain, in any account, is processing again at once, and its container starts in the background, + * in its own account and Region; the poller leaves it alone while its restore runs, and reports it ready after. + */ + @Test + void restoringStartsEachDomainsContainerAgain() { + storedDomain("home", ACCOUNT, US_EAST_1); + Domain away = storedDomain("away", OTHER_ACCOUNT, EU_WEST_1); + away.setAccountId(null); + when(domainManager.tryRestartDomain(any())).thenAnswer(start -> { + Domain domain = start.getArgument(0); + assertTrue(domain.isProcessing()); + // Its record still names the endpoint it had before the restart. + service.pollReadiness(); + verify(domainManager, Mockito.never()).isReady( + Mockito.argThat(polled -> polled != null && polled.getDomainName().equals(domain.getDomainName()))); + domain.setEndpoint("http://new-" + domain.getDomainName() + ":9200"); + return true; + }); + + service.restorePersistedRuntime().join(); + + Domain home = domainStore.getForAccount(ACCOUNT, US_EAST_1 + "::home").orElseThrow(); + assertTrue(home.isProcessing()); + assertEquals("http://new-home:9200", home.getEndpoint()); + assertEquals("http://new-away:9200", + domainStore.getForAccount(OTHER_ACCOUNT, EU_WEST_1 + "::away").orElseThrow().getEndpoint()); + assertTrue(domainStore.getForAccount(ACCOUNT, EU_WEST_1 + "::away").isEmpty(), + "the record stays in its own account"); + when(domainManager.isReady(any())).thenReturn(true); + service.pollReadiness(); + assertFalse(domainStore.getForAccount(ACCOUNT, US_EAST_1 + "::home").orElseThrow().isProcessing()); + } + + /** A domain whose container outlived Floci keeps it, and starts none. */ + @Test + void aDomainKeepsItsSurvivingContainer() { + storedDomain("kept", ACCOUNT, US_EAST_1); + when(domainManager.adoptRunningDomain(any())).thenReturn(true); + + service.restorePersistedRuntime().join(); + + verify(domainManager, Mockito.never()).tryRestartDomain(any()); + assertTrue(service.describeDomain("kept", US_EAST_1).isProcessing(), "until the poller sees it answer"); + } + + /** With no Docker daemon reachable, a domain has no container behind it, as one created then has. */ + @Test + void withNoDockerDaemonADomainReportsNoContainer() { + storedDomain("no-docker", ACCOUNT, US_EAST_1); + when(domainManager.tryRestartDomain(any())).thenReturn(false); + + service.restorePersistedRuntime().join(); + + Domain domain = service.describeDomain("no-docker", US_EAST_1); + assertFalse(domain.isProcessing()); + assertTrue(domain.getEndpoint().startsWith("search-no-docker-"), domain.getEndpoint()); + } + + /** + * A domain whose container cannot start has none behind it, and the failure is thrown once every other domain + * has been restored. + */ + @Test + void aDomainWhoseContainerCannotStartFailsTheRestore() { + storedDomain("broken", ACCOUNT, US_EAST_1); + storedDomain("fine", ACCOUNT, US_EAST_1); + IllegalStateException cause = new IllegalStateException("image not found"); + Mockito.doReturn(true).when(domainManager).tryRestartDomain(any()); + Mockito.doThrow(cause).when(domainManager).tryRestartDomain( + Mockito.argThat(domain -> domain != null && "broken".equals(domain.getDomainName()))); + + CompletionException thrown = assertThrows(CompletionException.class, + () -> service.restorePersistedRuntime().join()); + + assertEquals("Could not restore OpenSearch domain broken of account " + ACCOUNT, + thrown.getCause().getMessage()); + assertSame(cause, thrown.getCause().getCause()); + Domain broken = service.describeDomain("broken", US_EAST_1); + assertFalse(broken.isProcessing()); + assertTrue(broken.getEndpoint().startsWith("search-broken-"), broken.getEndpoint()); + assertTrue(service.describeDomain("fine", US_EAST_1).isProcessing()); + } + + /** + * A domain deleted while its container starts reads Deleted, as AWS reports a domain being deleted, and its name + * stays taken; once the start is through its container and data go, and so does the domain. + */ + @Test + void aDomainDeletedWhileItsContainerStartsIsDeletedOnceTheStartIsThrough() { + storedDomain("deleted", ACCOUNT, US_EAST_1); + when(domainManager.tryRestartDomain(any())).thenAnswer(start -> { + assertTrue(service.deleteDomain("deleted", US_EAST_1).isDeleted()); + assertTrue(service.describeDomain("deleted", US_EAST_1).isDeleted()); + AwsException again = assertThrows(AwsException.class, + () -> service.createDomain("deleted", "OpenSearch_2.11", null, null, null, US_EAST_1)); + assertEquals("ResourceAlreadyExistsException", again.getErrorCode()); + return true; + }); + + service.restorePersistedRuntime().join(); + + verify(domainManager).removeDomainContainers( + Mockito.argThat(domain -> "deleted".equals(domain.getDomainName()))); + verify(domainManager).removeDomainStorage(Mockito.argThat(domain -> "deleted".equals(domain.getDomainName()))); + verify(domainManager, Mockito.never()).stopDomain(any()); + assertTrue(service.findDomain("deleted", US_EAST_1).isEmpty()); + verify(domainManager, Mockito.times(1)).tryRestartDomain(any()); + } + + /** A domain deleted while its container fails to start is still deleted: its data and record go. */ + @Test + void aDomainDeletedWhileItsContainerFailsToStartIsStillDeleted() { + storedDomain("doomed", ACCOUNT, US_EAST_1); + IllegalStateException cause = new IllegalStateException("image not found"); + when(domainManager.tryRestartDomain(any())).thenAnswer(start -> { + service.deleteDomain("doomed", US_EAST_1); + throw cause; + }); + + CompletionException thrown = assertThrows(CompletionException.class, + () -> service.restorePersistedRuntime().join()); + + assertSame(cause, thrown.getCause().getCause()); + verify(domainManager).removeDomainContainers(any()); + verify(domainManager).removeDomainStorage(any()); + assertTrue(service.findDomain("doomed", US_EAST_1).isEmpty()); + } + + /** A domain deleted while the restore starts another one is not started: its container and data go instead. */ + @Test + void aDomainDeletedWhileItWaitsIsNotStarted() { + storedDomain("first", ACCOUNT, US_EAST_1); + storedDomain("second", ACCOUNT, US_EAST_1); + List deleted = new ArrayList<>(); + when(domainManager.tryRestartDomain(any())).thenAnswer(start -> { + Domain domain = start.getArgument(0); + String waiting = "first".equals(domain.getDomainName()) ? "second" : "first"; + service.deleteDomain(waiting, US_EAST_1); + deleted.add(waiting); + return true; + }); + + service.restorePersistedRuntime().join(); + + verify(domainManager, Mockito.times(1)).tryRestartDomain(any()); + String waiting = deleted.getFirst(); + verify(domainManager).removeDomainContainers(Mockito.argThat(domain -> waiting.equals(domain.getDomainName()))); + assertTrue(service.findDomain(waiting, US_EAST_1).isEmpty()); + } + + /** + * A domain whose record goes during its restore without a delete of its own is left alone: only the container the + * restore started goes, and the record is not written back. + */ + @Test + void aDomainWhoseRecordGoesDuringItsRestoreIsLeftAlone() { + storedDomain("vanished", ACCOUNT, US_EAST_1); + when(domainManager.tryRestartDomain(any())).thenAnswer(start -> { + domainStore.deleteForAccount(ACCOUNT, US_EAST_1 + "::vanished"); + return true; + }); + + service.restorePersistedRuntime().join(); + + verify(domainManager).stopDomain(Mockito.argThat(domain -> "vanished".equals(domain.getDomainName()))); + verify(domainManager, Mockito.never()).removeDomainContainers(any()); + verify(domainManager, Mockito.never()).removeDomainStorage(any()); + assertTrue(service.findDomain("vanished", US_EAST_1).isEmpty()); + } + + /** + * A domain created again under the name of one being restored keeps its record: the restore removes only the + * container it started, not the name, the record or the data. + */ + @Test + void aDomainCreatedAgainUnderTheNameKeepsItsRecord() { + Domain old = storedDomain("again", ACCOUNT, US_EAST_1); + Domain again = storedDomain("again", ACCOUNT, US_EAST_1); + domainStore.putForAccount(ACCOUNT, US_EAST_1 + "::again", old); + again.setCreatedAt(old.getCreatedAt().plusSeconds(60)); + again.setEndpoint("http://new-again:9200"); + when(domainManager.tryRestartDomain(any())).thenAnswer(start -> { + domainStore.putForAccount(ACCOUNT, US_EAST_1 + "::again", again); + return true; + }); + + service.restorePersistedRuntime().join(); + + assertSame(again, domainStore.getForAccount(ACCOUNT, US_EAST_1 + "::again").orElseThrow()); + assertEquals("http://new-again:9200", again.getEndpoint()); + verify(domainManager).stopDomain(old); + verify(domainManager, Mockito.never()).removeDomainContainers(any()); + } + + /** A domain whose record goes while the restore starts another one is not started. */ + @Test + void aDomainWhoseRecordGoesWhileItWaitsIsNotStarted() { + storedDomain("first", ACCOUNT, US_EAST_1); + storedDomain("second", ACCOUNT, US_EAST_1); + when(domainManager.tryRestartDomain(any())).thenAnswer(start -> { + Domain domain = start.getArgument(0); + String waiting = "first".equals(domain.getDomainName()) ? "second" : "first"; + domainStore.deleteForAccount(ACCOUNT, US_EAST_1 + "::" + waiting); + return true; + }); + + service.restorePersistedRuntime().join(); + + verify(domainManager, Mockito.times(1)).tryRestartDomain(any()); + verify(domainManager, Mockito.never()).stopDomain(any()); + } + + /** A delete a restore did not live to finish is finished at the next start, which starts nothing for it. */ + @Test + void aDeleteFlociDidNotLiveToFinishIsFinishedAtTheNextStart() { + storedDomain("half-deleted", ACCOUNT, US_EAST_1).setDeleted(true); + + service.restorePersistedRuntime().join(); + + verify(domainManager).removeDomainContainers(any()); + verify(domainManager).removeDomainStorage(any()); + verify(domainManager, Mockito.never()).tryRestartDomain(any()); + assertTrue(service.findDomain("half-deleted", US_EAST_1).isEmpty()); + } + + /** A deleted domain whose container Docker keeps stays Deleted, naming it, for the next start to remove. */ + @Test + void aDeletedDomainWhoseContainerDockerKeepsStaysDeleted() { + storedDomain("kept-deleted", ACCOUNT, US_EAST_1).setDeleted(true); + IllegalStateException refused = new IllegalStateException("Failed to remove stale container old-id"); + Mockito.doThrow(refused).when(domainManager).removeDomainContainers(any()); + + CompletionException thrown = assertThrows(CompletionException.class, + () -> service.restorePersistedRuntime().join()); + + assertSame(refused, thrown.getCause().getCause()); + assertTrue(service.describeDomain("kept-deleted", US_EAST_1).isDeleted()); + verify(domainManager, Mockito.never()).removeDomainStorage(any()); + } + + /** + * Deleting again a domain whose delete Docker kept the container of removes it the same confirmed way: while + * Docker still keeps it the domain stays Deleted, and once Docker removes it the domain and its data go. + */ + @Test + void aDeleteRetriedAfterDockerKeptTheContainerConfirmsTheRemoval() { + storedDomain("retried", ACCOUNT, US_EAST_1).setDeleted(true); + IllegalStateException refused = new IllegalStateException("Failed to remove stale container old-retried"); + Mockito.doThrow(refused).doThrow(refused).doNothing().when(domainManager).removeDomainContainers(any()); + assertThrows(CompletionException.class, () -> service.restorePersistedRuntime().join()); + + assertTrue(service.deleteDomain("retried", US_EAST_1).isDeleted()); + assertTrue(service.describeDomain("retried", US_EAST_1).isDeleted(), "Docker still keeps the container"); + verify(domainManager, Mockito.never()).removeDomainStorage(any()); + + service.deleteDomain("retried", US_EAST_1); + + assertTrue(service.findDomain("retried", US_EAST_1).isEmpty()); + verify(domainManager).removeDomainStorage(any()); + verify(domainManager, Mockito.never()).stopDomain(any()); + } + + /** + * Two retried deletes of one domain run one at a time: the one that waits finds the domain gone, and removes + * nothing, so it could never remove the container of a domain created again under the name meanwhile. + */ + @Test + void retriedDeletesOfOneDomainRunOneAtATime() throws Exception { + storedDomain("contested", ACCOUNT, US_EAST_1).setDeleted(true); + CountDownLatch removing = new CountDownLatch(1); + CountDownLatch carryOn = new CountDownLatch(1); + AtomicInteger removals = new AtomicInteger(); + Mockito.doAnswer(remove -> { + if (removals.getAndIncrement() == 0) { + removing.countDown(); + assertTrue(carryOn.await(30, TimeUnit.SECONDS)); + } + return null; + }).when(domainManager).removeDomainContainers(any()); + Thread first = new Thread(() -> service.deleteDomain("contested", US_EAST_1)); + first.start(); + assertTrue(removing.await(30, TimeUnit.SECONDS)); + + Thread second = new Thread(() -> service.deleteDomain("contested", US_EAST_1)); + second.start(); + await().atMost(Duration.ofSeconds(30)).until(() -> second.getState() == Thread.State.BLOCKED + || second.getState() == Thread.State.TERMINATED); + carryOn.countDown(); + first.join(30_000); + second.join(30_000); + + assertEquals(1, removals.get()); + assertTrue(service.findDomain("contested", US_EAST_1).isEmpty()); + } + + /** Once its restore is through, a domain is deleted as any other: its container stopped and its data removed. */ + @Test + void aDomainIsDeletedAsUsualOnceItsRestoreIsThrough() { + storedDomain("restored", ACCOUNT, US_EAST_1); + when(domainManager.tryRestartDomain(any())).thenReturn(true); + service.restorePersistedRuntime().join(); + + service.deleteDomain("restored", US_EAST_1); + + verify(domainManager).stopDomain(Mockito.argThat(domain -> "restored".equals(domain.getDomainName()))); + verify(domainManager, Mockito.never()).removeDomainContainers(any()); + assertTrue(service.findDomain("restored", US_EAST_1).isEmpty()); + } + + /** + * A shutdown during the restore stops it: domains it has not reached, and one whose start shutdown overtook, are + * left processing for the next start, and the poller treats them as any other. + */ + @Test + void aShutdownDuringTheRestoreLeavesItsDomainsForTheNextStart() { + storedDomain("waiting", ACCOUNT, US_EAST_1); + when(domainManager.isShuttingDown()).thenReturn(true); + + service.restorePersistedRuntime().join(); + + verify(domainManager, Mockito.never()).tryRestartDomain(any()); + + when(domainManager.isShuttingDown()).thenReturn(false); + when(domainManager.tryRestartDomain(any())) + .thenThrow(new OpenSearchDomainManager.ShuttingDownException("waiting")); + service.restorePersistedRuntime().join(); + + assertTrue(service.describeDomain("waiting", US_EAST_1).isProcessing()); + service.pollReadiness(); + verify(domainManager).isReady(Mockito.argThat(domain -> "waiting".equals(domain.getDomainName()))); + } + + @Test + void restoringLeavesMockDomainsAsTheyAre() { + when(osConfig.mock()).thenReturn(true); + storedDomain("mocked", ACCOUNT, US_EAST_1); + + service.restorePersistedRuntime().join(); + + assertFalse(service.describeDomain("mocked", US_EAST_1).isProcessing()); + Mockito.verifyNoInteractions(domainManager); + } + + /** Shutdown stops restores and starts before it stops the domains' containers. */ + @Test + void shutdownStopsStartsBeforeItStopsTheContainers() { + storedDomain("running", ACCOUNT, US_EAST_1); + + service.shutdown(); + + InOrder order = Mockito.inOrder(domainManager); + order.verify(domainManager).markShuttingDown(); + order.verify(domainManager).stopDomain(any()); + } + + /** A domain stored in {@code account} and {@code region} whose record names the container it ran on. */ + private Domain storedDomain(String name, String account, String region) { + Domain domain = new Domain(); + domain.setDomainName(name); + domain.setAccountId(account); + domain.setRegion(region); + domain.setArn(AwsArnUtils.Arn.of("es", region, account, "domain/" + name).toString()); + domain.setEngineVersion("OpenSearch_2.11"); + domain.setCreatedAt(Instant.parse("2026-11-01T00:00:00Z")); + domain.setEndpoint("http://172.17.0.2:9200"); + domain.setContainerId("old-" + name); + domainStore.putForAccount(account, region + "::" + name, domain); + return domain; + } }