feat(opensearch): allow configuring a data volume for domain containers (#5581)

* feat(opensearch): allow configuring a data volume for domain containers

* fix(opensearch): isolate configured storage and prepare bind mounts

Include account and Region from the domain ARN in configured volume
names and bind paths, preserving the optional deployment namespace.

Treat missing ownership markers as FLOCI_MANAGED and remove name-based
ownership inference. Retain explicitly operator-owned storage and use
persisted volume names for managed cleanup.

Reuse the storage helper container lifecycle to prepare bind-directory
ownership and owner write access from the selected image. Leave existing
files untouched, propagate preparation failures, and release reserved
ports when storage preparation fails.

Preserve Linux daemon path syntax on Windows while keeping native
Windows paths and named volumes working.

Consolidate OpenSearchDomainManagerTest setup, add regression coverage
and a Linux Docker integration test, and update configuration comments
and documentation examples.

Fix an existing bug where opensearch container names did not include
account or region id.
This commit is contained in:
LiamCato authored and GitHub committed 2026-10-14 20:34:28 -04:00
1 parent 66756f7b9c
commit 8145ffd00e
15 files changed
+1023 -145

No files matched your search

@@ -2116,6 +2116,29 @@ public interface EmulatorConfig {
@WithDefault("${floci.storage.persistent-path}/opensearch")
String dataPath();
/**
* Optional data volume for the domain containers Floci spawns, replacing the
* per-domain volume Floci derives by default. An absolute path is bind-mounted as
* {@code <path>/<account-id>/<region>/<domain-name>}, nested under a {@code <namespace>} subdirectory
* when a resource namespace is configured; any other value is a Docker volume
* name and each domain gets its own {@code <name>-<namespace>-<account-id>-<region>-<domain-name>}
* volume, without the namespace segment when none is configured. No two domains
* and no two namespaced deployments sharing a Docker daemon ever share a data
* directory. Storage named here is never removed on domain delete,
* regardless of storage mode and prune policy: the operator named it, so its
* lifecycle is theirs. A volume Floci creates when absent carries no Floci
* label, so neither a floci-scoped volume prune nor a sweep of Floci-labelled
* child resources, a testcontainers module reaping a run's labelled children,
* removes it. When Floci itself runs in a container, an absolute path
* resolves on the Docker daemon's host. Paths starting with / retain Linux path syntax
* even when Floci runs on Windows. A temporary root container using the selected
* image creates and prepares bind-directory ownership and owner write access there;
* existing files are untouched, and preparation failure aborts domain startup.
*
* Env var: FLOCI_SERVICES_OPENSEARCH_DATA_VOLUME
*/
Optional<String> dataVolume();
@WithDefault("false")
boolean keepRunningOnShutdown();
}
@@ -20,6 +20,7 @@ import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.Mount;
import com.github.dockerjava.api.model.MountType;
import com.github.dockerjava.api.model.Ports;
import com.github.dockerjava.api.model.Volume;
import com.github.dockerjava.core.command.WaitContainerResultCallback;
import io.github.hectorvent.floci.config.ContainerCaBundle;
import io.github.hectorvent.floci.config.EmulatorConfig;
@@ -580,18 +581,33 @@ public class ContainerLifecycleManager {
* and do nothing, the volume analogue of start treating an HTTP 304 as success.
*/
public void ensureVolume(String volumeName) {
createVolumeIfAbsent(volumeName);
createVolumeIfAbsent(volumeName, ContainerStorageHelper.defaultLabels(config));
}
/**
* {@link #ensureVolume} for a volume an operator named, created when absent without any
* Floci label, the umbrella and extra ones alike. The operator named the volume, so its
* lifecycle is theirs: nothing that sweeps Floci-labelled volumes may collect it, neither
* a floci-scoped {@code docker volume prune} nor a testcontainers module reaping a run's
* labelled child resources through labels injected into {@code floci.docker.extra-labels}.
*/
public void ensureUnmanagedVolume(String volumeName) {
if (volumeExists(volumeName)) {
return;
}
dockerClient.createVolumeCmd()
.withName(volumeName)
// An explicit empty map, never mergedLabels: the operator-named volume
// carries no Floci label, so no label-based sweep collects it.
.withLabels(Map.of())
.exec();
LOG.debugv("Created unmanaged volume {0}", volumeName);
}
/** Creates a volume with resource ownership labels for recoverable cleanup. */
public void ensureVolume(String volumeName, Map<String, String> labels) {
createVolumeIfAbsent(volumeName, labels);
}
private boolean createVolumeIfAbsent(String volumeName) {
return createVolumeIfAbsent(volumeName, Map.of());
}
/** Creates the named volume when it is missing; returns whether it was created. */
private boolean createVolumeIfAbsent(String volumeName, Map<String, String> labels) {
if (volumeExists(volumeName)) {
@@ -642,7 +658,7 @@ public class ContainerLifecycleManager {
Optional<String> rootPermissions, String initImage) {
// A volume created now is root:root 0755 again, so a memo left by a volume of the same name
// that was removed since (e.g. DeleteApplication, docker volume rm) is stale.
if (createVolumeIfAbsent(volumeName)) {
if (createVolumeIfAbsent(volumeName, ContainerStorageHelper.defaultLabels(config))) {
initializedSharedVolumes.remove(volumeName);
}
if (rootPermissions.isEmpty() && ownerUid.isEmpty() && ownerGid.isEmpty()) {
@@ -697,11 +713,37 @@ public class ContainerLifecycleManager {
HostConfig hostConfig = HostConfig.newHostConfig().withMounts(List.of(
new Mount().withType(MountType.VOLUME).withSource(volumeName).withTarget(mount)));
CreateContainerResponse created = dockerClient.createContainerCmd(image)
CreateContainerCmd command = dockerClient.createContainerCmd(image)
.withHostConfig(hostConfig)
.withCmd("sh", "-c", script.toString())
.withLabels(ContainerStorageHelper.defaultLabels(config))
.exec();
.withCmd("sh", "-c", script.toString());
runStorageInitHelper(command, "shared volume " + volumeName);
LOG.infov("Initialised shared volume {0} root (cmd: {1})", volumeName, script);
}
/**
* Makes a bind directory writable by the owner of the image's data directory. The
* helper runs on the Docker daemon's host, using the workload image so custom image
* ownership is respected. Only the mount root is changed; existing files are untouched.
* Unlike shared-volume initialisation, failure propagates and every launch checks the root.
*/
public void ensureBindDirectory(String hostPath, String image, String imageDataPath) {
imageCacheService.ensureImageExists(image);
String mount = "/floci-bind-directory";
String script = "ownership=$(stat -c '%u:%g' \"$1\") && "
+ "chown \"$ownership\" \"$2\" && chmod u+rwx \"$2\"";
HostConfig hostConfig = HostConfig.newHostConfig()
.withBinds(new Bind(hostPath, new Volume(mount)));
CreateContainerCmd command = dockerClient.createContainerCmd(image)
.withHostConfig(hostConfig)
.withUser("0")
.withEntrypoint("sh")
.withCmd("-c", script, "floci-bind-init", imageDataPath, mount);
runStorageInitHelper(command, "bind directory " + hostPath);
LOG.infov("Initialised bind directory {0} using ownership from {1}:{2}", hostPath, image, imageDataPath);
}
private void runStorageInitHelper(CreateContainerCmd command, String description) {
CreateContainerResponse created = command.withLabels(ContainerStorageHelper.defaultLabels(config)).exec();
String helperId = created.getId();
try {
startContainer(helperId);
@@ -709,17 +751,14 @@ public class ContainerLifecycleManager {
.exec(new WaitContainerResultCallback())
.awaitStatusCode(60, TimeUnit.SECONDS);
if (status == null || status != 0) {
// Throw so the caller leaves the volume unmemoised and retries on the next launch,
// rather than leaving it root:root 0755 with no further attempt.
throw new IllegalStateException("shared-volume init for " + volumeName
+ " exited with status " + status + " (cmd: " + script + ")");
throw new IllegalStateException("Storage init for " + description + " exited with status " + status);
}
LOG.infov("Initialised shared volume {0} root (cmd: {1})", volumeName, script);
} finally {
try {
dockerClient.removeContainerCmd(helperId).withForce(true).exec();
} catch (Exception ignore) {
// best-effort cleanup of the one-off helper
} catch (Exception e) {
LOG.warnv("Failed to remove storage init helper {0} for {1}: {2}",
helperId, description, e.getMessage());
}
}
}
@@ -273,7 +273,11 @@ public final class ContainerStorageHelper {
return base.resolve(namespace).resolve(service).resolve(resourceId);
}
private static String resourceNamespace(EmulatorConfig config) {
/**
* The configured resource namespace, sanitized for use inside Docker names and paths;
* empty when no namespace is configured or {@code config} carries no Docker config.
*/
public static String resourceNamespace(EmulatorConfig config) {
if (config == null || config.docker() == null || config.docker().resourceNamespace() == null) {
return "";
}
@@ -338,6 +342,22 @@ public final class ContainerStorageHelper {
builder.withNamedVolume(volumeName, internalMount);
}
/**
* {@link #applyNamedVolume} for a volume an operator named through their own
* configuration: created when absent without any Floci label, so nothing that sweeps
* Floci-labelled volumes, a floci-scoped {@code docker volume prune} above all, and a
* testcontainers module reaping a run's labelled child resources above all, collects it.
* The operator named the volume, so its lifecycle is theirs.
*/
public static void applyOperatorNamedVolume(
ContainerBuilder.Builder builder,
ContainerLifecycleManager lifecycleManager,
String volumeName,
String internalMount) {
lifecycleManager.ensureUnmanagedVolume(volumeName);
builder.withNamedVolume(volumeName, internalMount);
}
/**
* Removes the named volume on resource delete, honouring the configured prune policy.
*
@@ -1,7 +1,7 @@
package io.github.hectorvent.floci.services.opensearch;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
@@ -11,13 +11,16 @@ import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.PortAllocator;
import io.github.hectorvent.floci.services.opensearch.model.Domain;
import io.github.hectorvent.floci.services.opensearch.model.VolumeOwnership;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.File;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.file.Path;
import java.util.Optional;
/**
* Manages the Docker lifecycle of OpenSearch containers for real-mode domains.
@@ -28,6 +31,7 @@ public class OpenSearchDomainManager {
private static final Logger LOG = Logger.getLogger(OpenSearchDomainManager.class);
private static final int OPENSEARCH_PORT = 9200;
private static final String CONTAINER_DATA_PATH = "/usr/share/opensearch/data";
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
@@ -35,21 +39,18 @@ public class OpenSearchDomainManager {
private final PortAllocator portAllocator;
private final EmulatorConfig config;
private volatile boolean dockerUnavailableLogged;
private final RegionResolver regionResolver;
@Inject
public OpenSearchDomainManager(ContainerBuilder containerBuilder,
ContainerLifecycleManager lifecycleManager,
ContainerDetector containerDetector,
PortAllocator portAllocator,
EmulatorConfig config,
RegionResolver regionResolver) {
EmulatorConfig config) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.containerDetector = containerDetector;
this.portAllocator = portAllocator;
this.config = config;
this.regionResolver = regionResolver;
}
/**
@@ -98,11 +99,17 @@ public class OpenSearchDomainManager {
public void startDomain(Domain domain) {
String image = resolveImage(domain.getEngineVersion());
String containerName = containerName(domain);
AwsArnUtils.Arn arn = AwsArnUtils.parse(domain.getArn());
String containerName = ContainerStorageHelper.resourceName(config, "opensearch", null,
arn.accountId() + "-" + arn.region() + "-" + domain.getDomainName());
LOG.infov("Starting OpenSearch container for domain: {0} (version={1}, image={2})",
domain.getDomainName(), domain.getEngineVersion(), image);
// Older container names omit account and Region, so only the persisted ID proves ownership.
if (domain.getContainerId() != null && !domain.getContainerId().isBlank()) {
lifecycleManager.removeIfExists(domain.getContainerId());
}
ContainerStorageHelper.removeStaleContainer(config, lifecycleManager, containerName);
// A restart of an existing domain has just removed the old container, so its
@@ -122,8 +129,7 @@ public class OpenSearchDomainManager {
// DeleteDomain, and every shutdown for each domain, waited out the whole stop timeout.
.withInit()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"opensearch", domain.getDomainName(), regionResolver.getAccountId(),
regionResolver.getDefaultRegion()));
"opensearch", domain.getDomainName(), arn.accountId(), arn.region()));
// Container-name DNS only resolves on a user-defined Docker network, and
// nothing guarantees the spawned OpenSearch container and floci itself land
@@ -144,27 +150,32 @@ public class OpenSearchDomainManager {
config.services().opensearch().proxyMaxPort());
specBuilder.withPortBinding(OPENSEARCH_PORT, hostPort);
applyEngineEnv(specBuilder, domain.getEngineVersion());
if (ContainerStorageHelper.isNamedVolumeMode(config)) {
ContainerStorageHelper.applyNamedVolume(specBuilder, lifecycleManager,
resolveVolumeName(domain), "/usr/share/opensearch/data");
} else {
// Legacy host-path mode: host-persistent-path is an absolute path
Path dataPath = ContainerStorageHelper.hostResourcePath(config, "opensearch", domain.getDomainName());
if (!containerDetector.isRunningInContainer()) {
ContainerStorageHelper.ensureHostDir(dataPath.toString());
}
String dataPathStr = dataPath.toAbsolutePath().normalize().toString();
String persistentPathStr = Path.of(config.storage().persistentPath()).toAbsolutePath().normalize().toString();
String hostDataPath = dataPathStr.replace(persistentPathStr, config.storage().hostPersistentPath());
specBuilder.withBind(hostDataPath, "/usr/share/opensearch/data");
}
ContainerSpec spec = specBuilder.build();
ContainerInfo info;
try {
applyEngineEnv(specBuilder, domain.getEngineVersion());
Optional<String> configuredDataVolume = config.services().opensearch().dataVolume()
.filter(dataVolume -> !dataVolume.isBlank());
if (configuredDataVolume.isPresent()) {
applyConfiguredDataVolume(specBuilder, domain, configuredDataVolume.get(), image);
} else if (ContainerStorageHelper.isNamedVolumeMode(config)) {
domain.setVolumeOwnership(VolumeOwnership.FLOCI_MANAGED);
ContainerStorageHelper.applyNamedVolume(specBuilder, lifecycleManager,
resolveVolumeName(domain), CONTAINER_DATA_PATH);
} else {
// Legacy host-path mode: host-persistent-path is an absolute path
Path dataPath = ContainerStorageHelper.hostResourcePath(config, "opensearch", domain.getDomainName());
if (!containerDetector.isRunningInContainer()) {
ContainerStorageHelper.ensureHostDir(dataPath.toString());
}
String dataPathStr = dataPath.toAbsolutePath().normalize().toString();
String persistentPathStr = Path.of(config.storage().persistentPath()).toAbsolutePath().normalize().toString();
String hostDataPath = dataPathStr.replace(persistentPathStr, config.storage().hostPersistentPath());
specBuilder.withBind(hostDataPath, CONTAINER_DATA_PATH);
}
ContainerSpec spec = specBuilder.build();
info = lifecycleManager.createAndStart(spec);
} catch (RuntimeException e) {
portAllocator.release(hostPort);
@@ -220,8 +231,31 @@ public class OpenSearchDomainManager {
LOG.infov("Stopped OpenSearch container for domain {0}", domain.getDomainName());
}
/**
* Removes the domain's Docker volume on delete, honouring the configured prune policy.
* The decision rides on the {@link VolumeOwnership} marker persisted when the storage
* was selected, not on names recomputed from the configuration held at delete time: a
* recomputed name stops matching the persisted one as soon as the resource namespace
* changes, and a name composed from {@code floci.services.opensearch.data-volume} can
* be spelled exactly like one Floci derives. Records predating the marker also predate
* configured data volumes, so their volumes are always Floci-managed.
*/
public void removeDomainStorage(Domain domain) {
ContainerStorageHelper.removeNamedVolume(config, lifecycleManager, resolveVolumeName(domain));
VolumeOwnership ownership = domain.getVolumeOwnership();
if (ownership == VolumeOwnership.OPERATOR_BIND) {
LOG.infov("Retained the bind-mounted data directory of domain {0}. It was named by "
+ "floci.services.opensearch.data-volume, which Floci never removes.",
domain.getDomainName());
return;
}
String volumeName = resolveVolumeName(domain);
if (ownership == VolumeOwnership.OPERATOR_NAMED) {
LOG.infov("Retained Docker volume {0}. It was named by "
+ "floci.services.opensearch.data-volume, which Floci never removes. "
+ "Remove manually: docker volume rm {0}", volumeName);
return;
}
ContainerStorageHelper.removeNamedVolume(config, lifecycleManager, volumeName);
}
/**
@@ -243,8 +277,55 @@ public class OpenSearchDomainManager {
config.services().opensearch().defaultImage(), engineVersion);
}
private String containerName(Domain domain) {
return ContainerStorageHelper.resourceName(config, "opensearch", null, domain.getDomainName());
/**
* Mounts the operator-configured {@code floci.services.opensearch.data-volume}. An
* absolute path is bind-mounted as {@code <path>/<account-id>/<region>/<domain-name>}, nested under a
* {@code <namespace>} subdirectory when a resource namespace is configured; any
* other value is a Docker volume name and the domain gets its own
* {@code <name>-<namespace>-<account-id>-<region>-<domain-name>} volume of it, without the namespace
* segment when none is configured. Per-domain, per-deployment naming is deliberate:
* two OpenSearch nodes sharing one data directory corrupt each other's cluster
* state, and two namespaced deployments on one Docker daemon must not converge on
* one volume through the same configured base. The domain record is stamped with
* the volume name and the operator ownership marker so
* {@link #removeDomainStorage} can tell operator-named storage, which it never
* deletes, from the kind Floci derives. The bind branch clears any managed name
* stamped at creation: a stale one would read as a volume the domain never mounted.
* A volume created when absent carries no Floci label, so no sweep of
* Floci-labelled volumes, a floci-scoped prune or a testcontainers run's
* labelled-children reap, collects operator storage.
*/
private void applyConfiguredDataVolume(ContainerBuilder.Builder specBuilder, Domain domain,
String dataVolume, String image) {
AwsArnUtils.Arn arn = AwsArnUtils.parse(domain.getArn());
if (dataVolume.startsWith("/") || Path.of(dataVolume).isAbsolute()) {
domain.setVolumeOwnership(VolumeOwnership.OPERATOR_BIND);
domain.setDockerVolumeName(null);
String namespace = ContainerStorageHelper.resourceNamespace(config);
String hostPath;
if (dataVolume.startsWith("/") && File.separatorChar != '/') {
// A Linux daemon path must not be resolved against the Windows client's drive.
String base = dataVolume.endsWith("/") ? dataVolume : dataVolume + "/";
String prefix = namespace.isBlank() ? base : base + namespace + "/";
hostPath = prefix + arn.accountId() + "/" + arn.region() + "/" + domain.getDomainName();
} else {
Path domainDataPath = namespace.isBlank()
? Path.of(dataVolume, arn.accountId(), arn.region(), domain.getDomainName())
: Path.of(dataVolume, namespace, arn.accountId(), arn.region(), domain.getDomainName());
if (!containerDetector.isRunningInContainer()) {
ContainerStorageHelper.ensureHostDir(domainDataPath.toString());
}
hostPath = domainDataPath.toAbsolutePath().normalize().toString();
}
lifecycleManager.ensureBindDirectory(hostPath, image, CONTAINER_DATA_PATH);
specBuilder.withBind(hostPath, CONTAINER_DATA_PATH);
return;
}
String volumeName = ContainerStorageHelper.prefixedDockerName(
config, dataVolume, arn.accountId() + "-" + arn.region() + "-" + domain.getDomainName());
domain.setDockerVolumeName(volumeName);
domain.setVolumeOwnership(VolumeOwnership.OPERATOR_NAMED);
ContainerStorageHelper.applyOperatorNamedVolume(specBuilder, lifecycleManager, volumeName, CONTAINER_DATA_PATH);
}
/**
@@ -20,6 +20,7 @@ import io.github.hectorvent.floci.services.opensearch.model.DomainEndpointOption
import io.github.hectorvent.floci.services.opensearch.model.EbsOptions;
import io.github.hectorvent.floci.services.opensearch.model.EncryptionAtRestOptions;
import io.github.hectorvent.floci.services.opensearch.model.NodeToNodeEncryptionOptions;
import io.github.hectorvent.floci.services.opensearch.model.VolumeOwnership;
import io.github.hectorvent.floci.services.opensearch.model.VpcOptions;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
@@ -136,6 +137,10 @@ public class OpenSearchService implements ResourceProvider {
// recomputed later. Only records predating this field fall back to the legacy name.
domain.setDockerVolumeName(ContainerStorageHelper.resourceName(
config, "opensearch", domain.getVolumeId(), domain.getDomainName()));
// The ownership marker travels with the name, so deletion removes what was persisted
// instead of recomputing ownership against whatever configuration holds at delete time.
// A configured data volume overwrites both when startDomain mounts operator storage.
domain.setVolumeOwnership(VolumeOwnership.FLOCI_MANAGED);
if (clusterConfig != null) {
domain.setClusterConfig(clusterConfig);
@@ -82,6 +82,13 @@ public class Domain {
@JsonProperty("DockerVolumeName")
private String dockerVolumeName;
/**
* Who owns the storage the domain's container mounts; null on records written before
* this field existed, whose volumes are always Floci-managed.
*/
@JsonProperty("VolumeOwnership")
private VolumeOwnership volumeOwnership;
@JsonProperty("CreatedAt")
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
private Instant createdAt;
@@ -248,6 +255,14 @@ public class Domain {
this.dockerVolumeName = dockerVolumeName;
}
public VolumeOwnership getVolumeOwnership() {
return volumeOwnership;
}
public void setVolumeOwnership(VolumeOwnership volumeOwnership) {
this.volumeOwnership = volumeOwnership;
}
public Instant getCreatedAt() {
return createdAt;
}
@@ -0,0 +1,27 @@
package io.github.hectorvent.floci.services.opensearch.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* Who owns the storage a domain's container mounts, stamped on the domain record when
* the storage is selected. Deletion acts on this marker rather than recomputing
* ownership from whatever configuration holds at delete time: a recomputed name no
* longer matches the persisted one as soon as the resource namespace changes, and a
* name an operator picked through {@code floci.services.opensearch.data-volume} can
* be spelled exactly like one Floci derives.
*
* <p>Null on records written before this field existed, which predate configured data volumes
* and therefore always have Floci-managed storage.</p>
*/
@RegisterForReflection
public enum VolumeOwnership {
/** Floci derived the per-domain volume name; deletion removes it per storage policy. */
FLOCI_MANAGED,
/** The operator named the volume through {@code floci.services.opensearch.data-volume}; never removed. */
OPERATOR_NAMED,
/** The operator bind-mounted a host path through {@code floci.services.opensearch.data-volume}; never removed. */
OPERATOR_BIND
}