diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerDetector.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerDetector.java new file mode 100644 index 0000000000..fc2e5ce1ad --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerDetector.java @@ -0,0 +1,147 @@ +package io.github.hectorvent.floci.core.common.docker; + +import jakarta.enterprise.context.ApplicationScoped; +import org.jboss.logging.Logger; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Locale; + +/** + * Detects whether the application is running inside a container. + *

+ * Supports detection for Docker, Moby, Docker Desktop, and Podman + * on Linux, macOS, and Windows. + *

+ * Detection heuristics (checked in order): + *

    + *
  1. Presence of the {@code /.dockerenv} marker file (Docker / Moby / Docker Desktop)
  2. + *
  3. Presence of {@code /run/.containerenv} (Podman)
  4. + *
  5. The {@code container} environment variable set by some runtimes (e.g. Podman sets it to {@code "podman"})
  6. + *
  7. {@code /proc/1/cgroup} containing {@code docker}, {@code kubepods}, or {@code libpod} (cgroup v1)
  8. + *
  9. {@code /proc/self/mountinfo} containing {@code /docker/} or {@code /libpod-} overlay paths (cgroup v2 / Podman)
  10. + *
  11. On Windows: the {@code CONTAINER} or {@code DOTNET_RUNNING_IN_CONTAINER} environment variable
  12. + *
+ */ +@ApplicationScoped +public class ContainerDetector { + + private static final Logger LOG = Logger.getLogger(ContainerDetector.class); + + private static final String DOCKER_ENV_MARKER = "/.dockerenv"; + private static final String PODMAN_ENV_MARKER = "/run/.containerenv"; + private static final String CGROUP_V1_FILE = "/proc/1/cgroup"; + private static final String MOUNTINFO_FILE = "/proc/self/mountinfo"; + + private volatile Boolean cachedResult; + + /** + * Returns {@code true} if the application is running inside a container. + * The result is evaluated once and cached for the lifetime of the application. + */ + public boolean isRunningInContainer() { + if (cachedResult != null) { + return cachedResult; + } + cachedResult = detect(); + LOG.infov("Container detection result: {0}", cachedResult); + return cachedResult; + } + + private boolean detect() { + // 1. Docker / Moby / Docker Desktop marker file (Linux & macOS containers) + if (fileExists(DOCKER_ENV_MARKER)) { + LOG.debugv("Detected container via {0}", DOCKER_ENV_MARKER); + return true; + } + + // 2. Podman marker file + if (fileExists(PODMAN_ENV_MARKER)) { + LOG.debugv("Detected container via {0}", PODMAN_ENV_MARKER); + return true; + } + + // 3. Environment variable set by some container runtimes + if (hasContainerEnvVariable()) { + LOG.debugv("Detected container via environment variable"); + return true; + } + + // 4. cgroup v1 markers (Linux) + if (hasCgroupV1Markers()) { + LOG.debugv("Detected container via cgroup v1 markers in {0}", CGROUP_V1_FILE); + return true; + } + + // 5. cgroup v2 / overlay mount markers (Linux) + if (hasMountInfoMarkers()) { + LOG.debugv("Detected container via mount markers in {0}", MOUNTINFO_FILE); + return true; + } + + return false; + } + + private boolean hasContainerEnvVariable() { + // Podman sets "container=podman"; systemd-nspawn sets "container=systemd-nspawn" + String containerEnv = getEnv("container"); + if (containerEnv != null && !containerEnv.isBlank()) { + return true; + } + + // Docker Desktop on Windows sometimes exposes this (.NET convention reused by some images) + String dotnetContainer = getEnv("DOTNET_RUNNING_IN_CONTAINER"); + if ("true".equalsIgnoreCase(dotnetContainer)) { + return true; + } + + // Generic CONTAINER env var used in some Windows container images + String genericContainer = getEnv("CONTAINER"); + return genericContainer != null && !genericContainer.isBlank(); + } + + private boolean hasCgroupV1Markers() { + return fileContainsAny(CGROUP_V1_FILE, "docker", "kubepods", "libpod", "moby", + "containerd", "cri-containerd"); + } + + private boolean hasMountInfoMarkers() { + return fileContainsAny(MOUNTINFO_FILE, "/docker/", "/libpod-", "/moby/", + "/containerd/", "/cri-containerd-"); + } + + private boolean fileContainsAny(String filePath, String... markers) { + if (!fileExists(filePath)) { + return false; + } + try { + Path path = Path.of(filePath); + String content = readFileContent(path); + String lower = content.toLowerCase(Locale.ROOT); + for (String marker : markers) { + if (lower.contains(marker.toLowerCase(Locale.ROOT))) { + return true; + } + } + } catch (IOException e) { + LOG.debugv("Could not read {0}: {1}", filePath, e.getMessage()); + } + return false; + } + + // --- Following methods are not private to be able to override them in test --- + + boolean fileExists(String path) { + return Files.exists(Path.of(path)); + } + + String getEnv(String name) { + return System.getenv(name); + } + + String readFileContent(Path path) throws IOException { + return Files.readString(path); + } +} + diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/DockerHostResolver.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/DockerHostResolver.java similarity index 78% rename from src/main/java/io/github/hectorvent/floci/services/lambda/launcher/DockerHostResolver.java rename to src/main/java/io/github/hectorvent/floci/core/common/docker/DockerHostResolver.java index fdee437bb2..8a90fcce5d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/DockerHostResolver.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/DockerHostResolver.java @@ -1,4 +1,4 @@ -package io.github.hectorvent.floci.services.lambda.launcher; +package io.github.hectorvent.floci.core.common.docker; import io.github.hectorvent.floci.config.EmulatorConfig; import jakarta.enterprise.context.ApplicationScoped; @@ -6,12 +6,10 @@ import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.net.InetAddress; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.concurrent.atomic.AtomicBoolean; /** - * Detects the hostname that Lambda containers should use to reach the Floci host. + * Detects the hostname that containers should use to reach the Floci host. * Different on Linux native Docker vs Docker Desktop (macOS/Windows). */ @ApplicationScoped @@ -19,17 +17,18 @@ public class DockerHostResolver { private static final Logger LOG = Logger.getLogger(DockerHostResolver.class); - private static final String DOCKER_ENV_MARKER = "/.dockerenv"; - private static final String CGROUP_FILE = "/proc/1/cgroup"; private static final String HOST_DOCKER_INTERNAL = "host.docker.internal"; private static final String LINUX_DOCKER_BRIDGE = "172.17.0.1"; private final EmulatorConfig config; private final AtomicBoolean ufwHintLogged = new AtomicBoolean(false); + private final ContainerDetector containerDetector; + @Inject - public DockerHostResolver(EmulatorConfig config) { + public DockerHostResolver(EmulatorConfig config, ContainerDetector containerDetector) { this.config = config; + this.containerDetector = containerDetector; } public String resolve() { @@ -39,10 +38,7 @@ public class DockerHostResolver { return override.get(); } - boolean runningInDocker = Files.exists(Path.of(DOCKER_ENV_MARKER)) - || isRunningInContainer(); - - if (runningInDocker) { + if (containerDetector.isRunningInContainer()) { // Use this container's own IP so Lambda containers on the same network // can reach the Runtime API server bound to all interfaces inside this container. try { @@ -80,18 +76,4 @@ public class DockerHostResolver { String os = System.getProperty("os.name", "").toLowerCase(); return os.contains("linux") || os.contains("nix") || os.contains("nux"); } - - private boolean isRunningInContainer() { - Path cgroup = Path.of(CGROUP_FILE); - if (!Files.exists(cgroup)) { - return false; - } - try { - String content = Files.readString(cgroup); - return content.contains("docker") || content.contains("kubepods"); - } catch (Exception e) { - return false; - } - } - } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java index 563e6bf2fa..66323abfce 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.ecs.container; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.docker.ContainerDetector; import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService; import io.github.hectorvent.floci.services.ecs.model.Container; import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition; @@ -10,7 +11,6 @@ import io.github.hectorvent.floci.services.ecs.model.EcsTask; import io.github.hectorvent.floci.services.ecs.model.NetworkBinding; import io.github.hectorvent.floci.services.ecs.model.PortMapping; import io.github.hectorvent.floci.services.ecs.model.TaskDefinition; -import io.github.hectorvent.floci.services.lambda.launcher.DockerHostResolver; import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.async.ResultCallback; @@ -42,26 +42,25 @@ import java.util.Map; public class EcsContainerManager { private static final Logger LOG = Logger.getLogger(EcsContainerManager.class); - private static final String HOST_DOCKER_INTERNAL = "host.docker.internal"; private static final DateTimeFormatter LOG_STREAM_DATE_FMT = DateTimeFormatter.ofPattern("yyyy/MM/dd"); private final DockerClient dockerClient; private final ImageCacheService imageCacheService; - private final DockerHostResolver dockerHostResolver; + private final ContainerDetector containerDetector; private final EmulatorConfig config; private final CloudWatchLogsService cloudWatchLogsService; private final RegionResolver regionResolver; @Inject public EcsContainerManager(DockerClient dockerClient, - ImageCacheService imageCacheService, - DockerHostResolver dockerHostResolver, - EmulatorConfig config, - CloudWatchLogsService cloudWatchLogsService, - RegionResolver regionResolver) { + ImageCacheService imageCacheService, + ContainerDetector containerDetector, + EmulatorConfig config, + CloudWatchLogsService cloudWatchLogsService, + RegionResolver regionResolver) { this.dockerClient = dockerClient; this.imageCacheService = imageCacheService; - this.dockerHostResolver = dockerHostResolver; + this.containerDetector = containerDetector; this.config = config; this.cloudWatchLogsService = cloudWatchLogsService; this.regionResolver = regionResolver; @@ -73,7 +72,6 @@ public class EcsContainerManager { */ public EcsTaskHandle startTask(EcsTask task, TaskDefinition taskDef, String region) { String taskId = extractTaskId(task.getTaskArn()); - boolean nativeMode = HOST_DOCKER_INTERNAL.equals(dockerHostResolver.resolve()); Map containerIds = new LinkedHashMap<>(); List logStreams = new ArrayList<>(); @@ -83,7 +81,7 @@ public class EcsContainerManager { imageCacheService.ensureImageExists(def.getImage()); List exposedPorts = buildExposedPorts(def); - HostConfig hostConfig = buildHostConfig(nativeMode, def, exposedPorts); + HostConfig hostConfig = buildHostConfig(def, exposedPorts); applyDockerNetwork(hostConfig); @@ -112,7 +110,7 @@ public class EcsContainerManager { dockerClient.startContainerCmd(dockerId).exec(); LOG.infov("Started ECS container {0}", dockerId); - List networkBindings = resolveNetworkBindings(dockerId, def, nativeMode); + List networkBindings = resolveNetworkBindings(dockerId, def); Container container = buildContainer(task.getTaskArn(), def, dockerId, networkBindings, region); runtimeContainers.add(container); @@ -169,14 +167,14 @@ public class EcsContainerManager { return exposed; } - private HostConfig buildHostConfig(boolean nativeMode, ContainerDefinition def, List exposedPorts) { + private HostConfig buildHostConfig(ContainerDefinition def, List exposedPorts) { HostConfig hostConfig = HostConfig.newHostConfig(); if (def.getMemory() != null) { hostConfig.withMemory((long) def.getMemory() * 1024 * 1024); } - if (nativeMode && !exposedPorts.isEmpty()) { + if (!containerDetector.isRunningInContainer() && !exposedPorts.isEmpty()) { Ports portBindings = new Ports(); for (ExposedPort ep : exposedPorts) { portBindings.bind(ep, Ports.Binding.bindPort(0)); // 0 = dynamic host port @@ -207,7 +205,7 @@ public class EcsContainerManager { return envVars; } - private List resolveNetworkBindings(String dockerId, ContainerDefinition def, boolean nativeMode) { + private List resolveNetworkBindings(String dockerId, ContainerDefinition def) { List bindings = new ArrayList<>(); if (def.getPortMappings() == null || def.getPortMappings().isEmpty()) { return bindings; @@ -222,7 +220,7 @@ public class EcsContainerManager { int hostPort = pm.containerPort(); String bindIp = "0.0.0.0"; - if (nativeMode && binding != null && binding.length > 0) { + if (!containerDetector.isRunningInContainer() && binding != null && binding.length > 0) { hostPort = Integer.parseInt(binding[0].getHostPortSpec()); if (binding[0].getHostIp() != null && !binding[0].getHostIp().isBlank()) { bindIp = binding[0].getHostIp(); @@ -255,7 +253,7 @@ public class EcsContainerManager { ensureLogGroupAndStream(logGroup, logStream, region); try { - ResultCallback.Adapter callback = dockerClient.logContainerCmd(dockerId) + return dockerClient.logContainerCmd(dockerId) .withStdOut(true) .withStdErr(true) .withFollowStream(true) @@ -270,7 +268,6 @@ public class EcsContainerManager { } } }); - return callback; } catch (Exception e) { LOG.warnv("Could not attach log stream for ECS container {0}: {1}", dockerId, e.getMessage()); return null; diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/container/ElastiCacheContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/container/ElastiCacheContainerManager.java index 729d6c1a7d..d844e62539 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elasticache/container/ElastiCacheContainerManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/container/ElastiCacheContainerManager.java @@ -3,8 +3,8 @@ package io.github.hectorvent.floci.services.elasticache.container; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.docker.ContainerDetector; import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService; -import io.github.hectorvent.floci.services.lambda.launcher.DockerHostResolver; import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.async.ResultCallback; @@ -36,12 +36,11 @@ public class ElastiCacheContainerManager { private static final Logger LOG = Logger.getLogger(ElastiCacheContainerManager.class); private static final int BACKEND_PORT = 6379; - private static final String HOST_DOCKER_INTERNAL = "host.docker.internal"; private static final DateTimeFormatter LOG_STREAM_DATE_FMT = DateTimeFormatter.ofPattern("yyyy/MM/dd"); private final DockerClient dockerClient; private final ImageCacheService imageCacheService; - private final DockerHostResolver dockerHostResolver; + private final ContainerDetector containerDetector; private final EmulatorConfig config; private final CloudWatchLogsService cloudWatchLogsService; private final RegionResolver regionResolver; @@ -49,13 +48,13 @@ public class ElastiCacheContainerManager { @Inject public ElastiCacheContainerManager(DockerClient dockerClient, ImageCacheService imageCacheService, - DockerHostResolver dockerHostResolver, + ContainerDetector containerDetector, EmulatorConfig config, CloudWatchLogsService cloudWatchLogsService, RegionResolver regionResolver) { this.dockerClient = dockerClient; this.imageCacheService = imageCacheService; - this.dockerHostResolver = dockerHostResolver; + this.containerDetector = containerDetector; this.config = config; this.cloudWatchLogsService = cloudWatchLogsService; this.regionResolver = regionResolver; @@ -65,9 +64,7 @@ public class ElastiCacheContainerManager { LOG.infov("Starting ElastiCache backend container for group: {0}", groupId); imageCacheService.ensureImageExists(image); - boolean nativeMode = HOST_DOCKER_INTERNAL.equals(dockerHostResolver.resolve()); - - HostConfig hostConfig = buildHostConfig(nativeMode); + HostConfig hostConfig = buildHostConfig(); String containerName = "floci-valkey-" + groupId; config.services().elasticache().dockerNetwork() @@ -95,7 +92,7 @@ public class ElastiCacheContainerManager { String backendHost; int backendPort; - if (nativeMode) { + if (!containerDetector.isRunningInContainer()) { // Retrieve the actual allocated host port from the container inspect var inspect = dockerClient.inspectContainerCmd(containerId).exec(); var bindings = inspect.getNetworkSettings().getPorts().getBindings(); @@ -163,9 +160,9 @@ public class ElastiCacheContainerManager { } } - private HostConfig buildHostConfig(boolean nativeMode) { + private HostConfig buildHostConfig() { HostConfig hostConfig = HostConfig.newHostConfig(); - if (nativeMode) { + if (!containerDetector.isRunningInContainer()) { // Bind BACKEND_PORT → random host port so the JVM can reach the container int freePort = findFreePort(); Ports portBindings = new Ports(); diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java index e6cf990ec4..2df7d6b39d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.lambda.launcher; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.docker.DockerHostResolver; import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService; import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager; import io.github.hectorvent.floci.services.lambda.model.ContainerState; diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java index 64e1bb0aa8..60fd1b30d0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java @@ -3,8 +3,8 @@ package io.github.hectorvent.floci.services.rds.container; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.docker.ContainerDetector; import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService; -import io.github.hectorvent.floci.services.lambda.launcher.DockerHostResolver; import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService; import io.github.hectorvent.floci.services.rds.model.DatabaseEngine; import com.github.dockerjava.api.DockerClient; @@ -35,12 +35,11 @@ import java.util.Map; public class RdsContainerManager { private static final Logger LOG = Logger.getLogger(RdsContainerManager.class); - private static final String HOST_DOCKER_INTERNAL = "host.docker.internal"; private static final DateTimeFormatter LOG_STREAM_DATE_FMT = DateTimeFormatter.ofPattern("yyyy/MM/dd"); private final DockerClient dockerClient; private final ImageCacheService imageCacheService; - private final DockerHostResolver dockerHostResolver; + private final ContainerDetector containerDetector; private final EmulatorConfig config; private final CloudWatchLogsService cloudWatchLogsService; private final RegionResolver regionResolver; @@ -48,13 +47,13 @@ public class RdsContainerManager { @Inject public RdsContainerManager(DockerClient dockerClient, ImageCacheService imageCacheService, - DockerHostResolver dockerHostResolver, + ContainerDetector containerDetector, EmulatorConfig config, CloudWatchLogsService cloudWatchLogsService, RegionResolver regionResolver) { this.dockerClient = dockerClient; this.imageCacheService = imageCacheService; - this.dockerHostResolver = dockerHostResolver; + this.containerDetector = containerDetector; this.config = config; this.cloudWatchLogsService = cloudWatchLogsService; this.regionResolver = regionResolver; @@ -66,10 +65,9 @@ public class RdsContainerManager { LOG.infov("Starting RDS backend container for instance: {0} engine={1}", instanceId, engine); imageCacheService.ensureImageExists(image); - boolean nativeMode = HOST_DOCKER_INTERNAL.equals(dockerHostResolver.resolve()); int enginePort = engine.defaultPort(); - HostConfig hostConfig = buildHostConfig(nativeMode, enginePort); + HostConfig hostConfig = buildHostConfig(enginePort); String containerName = "floci-rds-" + instanceId; config.services().rds().dockerNetwork() @@ -104,7 +102,7 @@ public class RdsContainerManager { String backendHost; int backendPort; - if (nativeMode) { + if (!containerDetector.isRunningInContainer()) { var inspect = dockerClient.inspectContainerCmd(containerId).exec(); var bindings = inspect.getNetworkSettings().getPorts().getBindings(); var binding = bindings.get(ExposedPort.tcp(enginePort)); @@ -165,9 +163,9 @@ public class RdsContainerManager { } } - private HostConfig buildHostConfig(boolean nativeMode, int enginePort) { + private HostConfig buildHostConfig(int enginePort) { HostConfig hostConfig = HostConfig.newHostConfig(); - if (nativeMode) { + if (!containerDetector.isRunningInContainer()) { int freePort = findFreePort(); Ports portBindings = new Ports(); portBindings.bind(ExposedPort.tcp(enginePort), Ports.Binding.bindPort(freePort)); diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerDetectorTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerDetectorTest.java new file mode 100644 index 0000000000..2c95c2ba6c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerDetectorTest.java @@ -0,0 +1,185 @@ +package io.github.hectorvent.floci.core.common.docker; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.*; + +class ContainerDetectorTest { + + private static ContainerDetector detector(boolean dockerEnvExists, + boolean podmanEnvExists, + String cgroupContent, + String mountInfoContent, + String containerEnv, + String dotnetEnv, + String genericContainerEnv) { + return new ContainerDetector() { + @Override + boolean fileExists(String path) { + if ("/.dockerenv".equals(path)) return dockerEnvExists; + if ("/run/.containerenv".equals(path)) return podmanEnvExists; + // For cgroup / mountinfo we control via readFileContent + if ("/proc/1/cgroup".equals(path)) return cgroupContent != null; + if ("/proc/self/mountinfo".equals(path)) return mountInfoContent != null; + return false; + } + + @Override + String readFileContent(Path path) throws IOException { + if (path.equals(Path.of("/proc/1/cgroup")) && cgroupContent != null) { + return cgroupContent; + } + if (path.equals(Path.of("/proc/self/mountinfo")) && mountInfoContent != null) { + return mountInfoContent; + } + throw new IOException("File not available in test stub: " + path); + } + + @Override + String getEnv(String name) { + return switch (name) { + case "container" -> containerEnv; + case "DOTNET_RUNNING_IN_CONTAINER" -> dotnetEnv; + case "CONTAINER" -> genericContainerEnv; + default -> null; + }; + } + }; + } + + @Test + void notInContainer() { + ContainerDetector d = detector(false, false, null, null, null, null, null); + assertFalse(d.isRunningInContainer()); + } + + @Test + void detectedViaDockerenvMarker() { + ContainerDetector d = detector(true, false, null, null, null, null, null); + assertTrue(d.isRunningInContainer()); + } + + @Test + void detectedViaPodmanMarker() { + ContainerDetector d = detector(false, true, null, null, null, null, null); + assertTrue(d.isRunningInContainer()); + } + + @Test + void detectedViaPodmanContainerEnv() { + ContainerDetector d = detector(false, false, null, null, "podman", null, null); + assertTrue(d.isRunningInContainer()); + } + + @Test + void detectedViaDotnetEnvVariable() { + ContainerDetector d = detector(false, false, null, null, null, "true", null); + assertTrue(d.isRunningInContainer()); + } + + @Test + void dotnetEnvFalseDoesNotDetect() { + ContainerDetector d = detector(false, false, null, null, null, "false", null); + assertFalse(d.isRunningInContainer()); + } + + @Test + void detectedViaGenericContainerEnv() { + ContainerDetector d = detector(false, false, null, null, null, null, "docker"); + assertTrue(d.isRunningInContainer()); + } + + @Test + void detectedViaCgroupDocker() { + ContainerDetector d = detector(false, false, + "12:memory:/docker/abc123\n", null, null, null, null); + assertTrue(d.isRunningInContainer()); + } + + @Test + void detectedViaCgroupMoby() { + ContainerDetector d = detector(false, false, + "12:memory:/moby/abc123\n", null, null, null, null); + assertTrue(d.isRunningInContainer()); + } + + @Test + void detectedViaCgroupKubepods() { + ContainerDetector d = detector(false, false, + "10:cpuset:/kubepods/pod-xyz\n", null, null, null, null); + assertTrue(d.isRunningInContainer()); + } + + @Test + void detectedViaCgroupLibpod() { + ContainerDetector d = detector(false, false, + "3:pids:/libpod-abc123\n", null, null, null, null); + assertTrue(d.isRunningInContainer()); + } + + @Test + void detectedViaCgroupContainerd() { + ContainerDetector d = detector(false, false, + "5:memory:/containerd/xyz\n", null, null, null, null); + assertTrue(d.isRunningInContainer()); + } + + @Test + void detectedViaCgroupCriContainerd() { + ContainerDetector d = detector(false, false, + "5:memory:/cri-containerd-abc\n", null, null, null, null); + assertTrue(d.isRunningInContainer()); + } + + @Test + void cgroupWithoutMarkers() { + ContainerDetector d = detector(false, false, + "12:memory:/user.slice\n", null, null, null, null); + assertFalse(d.isRunningInContainer()); + } + + @Test + void detectedViaMountInfoDocker() { + ContainerDetector d = detector(false, false, null, + "100 95 0:54 / / rw,relatime - overlay overlay rw,lowerdir=/docker/overlay2/l/ABC\n", + null, null, null); + assertTrue(d.isRunningInContainer()); + } + + @Test + void detectedViaMountInfoMoby() { + ContainerDetector d = detector(false, false, null, + "100 95 0:54 / / rw - overlay overlay lowerdir=/moby/something\n", + null, null, null); + assertTrue(d.isRunningInContainer()); + } + + @Test + void detectedViaMountInfoLibpod() { + ContainerDetector d = detector(false, false, null, + "100 95 0:54 / / rw - overlay overlay lowerdir=/libpod-abc123/overlay\n", + null, null, null); + assertTrue(d.isRunningInContainer()); + } + + @Test + void mountInfoWithoutMarkers() { + ContainerDetector d = detector(false, false, null, + "100 95 0:54 / / rw - ext4 /dev/sda1 rw\n", + null, null, null); + assertFalse(d.isRunningInContainer()); + } + + @Test + void resultIsCached() { + ContainerDetector d = detector(true, false, null, null, null, null, null); + assertTrue(d.isRunningInContainer()); + // Second call should return the cached result (still true) + assertTrue(d.isRunningInContainer()); + } +} + +