feat(core): label emulated resource containers with io.floci.* identity (#2497)

* feat(core): add io.floci.* resource-identity labels

Introduces ContainerStorageHelper.resourceIdentityLabels(service,
resourceId, accountId, region), so a container manager can tag its
spawned container with the emulated resource's identity. Additive to
the existing floci/floci_emulator/floci_namespace labels.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(rds): label RDS containers with resource identity

RDS backing containers now carry io.floci.service=rds,
io.floci.resource-id=<instanceId>, io.floci.account, and io.floci.region
so a spawned container can be mapped back to the DBInstanceIdentifier
it emulates without empirical docker exec probing.

Account/region reuse the same ARN parsing already done for log-stream
routing; extracted into resolveRuntimeIdentity so both call sites share
one source of truth.

Closes #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(docdb): label DocDB containers with resource identity

DocDB backing containers now carry io.floci.service=docdb and
io.floci.resource-id=<clusterId> alongside account/region.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(elasticache): label ElastiCache Redis/Valkey containers with resource identity

Backing containers now carry io.floci.service=elasticache and
io.floci.resource-id=<groupId> alongside account/region.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(elasticache): label ElastiCache Memcached containers with resource identity

Backing containers now carry io.floci.service=elasticache and
io.floci.resource-id=<clusterId> alongside account/region.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(memorydb): label MemoryDB containers with resource identity

Backing containers now carry io.floci.service=memorydb and
io.floci.resource-id=<clusterName> alongside account/region.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(neptune): label Neptune containers with resource identity

Backing containers now carry io.floci.service=neptune and
io.floci.resource-id=<clusterId> alongside account/region.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(msk): label MSK containers with resource identity

Redpanda backing containers now carry io.floci.service=msk and
io.floci.resource-id=<clusterName> alongside account/region.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(opensearch): label OpenSearch containers with resource identity

Backing containers now carry io.floci.service=opensearch and
io.floci.resource-id=<domainName> alongside account/region.
RegionResolver is now injected into OpenSearchDomainManager.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(ecs): label ECS task containers with resource identity

Backing containers now carry io.floci.service=ecs and
io.floci.resource-id=<taskId> alongside account/region.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(eks): label EKS k3s containers with resource identity

Backing containers now carry io.floci.service=eks and
io.floci.resource-id=<clusterName> alongside account/region.
RegionResolver is now injected into EksClusterManager.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(amazonmq): label AmazonMQ containers with resource identity

RabbitMQ backing containers now carry io.floci.service=amazonmq and
io.floci.resource-id=<brokerId> alongside account/region.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(mwaa): label MWAA containers with resource identity

Both the Postgres metadata container and the Airflow container now
carry io.floci.service=mwaa and io.floci.resource-id=<environmentName>
alongside account/region. RegionResolver is now injected into
MwaaEnvironmentManager.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(kinesisanalytics): label Flink containers with resource identity

Both the JobManager and TaskManager containers now carry
io.floci.service=kinesisanalytics and io.floci.resource-id=<applicationName>
alongside account/region.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(batch): label Batch job containers with resource identity

Job containers now carry io.floci.service=batch and
io.floci.resource-id=<jobId>, using the job's own account/region
(already carried on BatchJob) rather than RegionResolver.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(codebuild): label CodeBuild job containers with resource identity

Build containers now carry io.floci.service=codebuild and
io.floci.resource-id=<buildId> alongside account/region.

No new unit test: the container-spawn call site lives inside the
private multi-phase runBuild() method, entangled with real filesystem
and source-download side effects with no existing seam for unit
testing in isolation (CodeBuild's only coverage today is the
QuarkusTest-based CodeBuildIntegrationTest, which would need a real
Docker daemon and a full build run to assert container labels).

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(lambda): label function containers with resource identity

Lambda containers now carry io.floci.service=lambda and
io.floci.resource-id=<functionName>, reusing the existing
ARN-based region resolution and adding the equivalent account lookup.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(ec2): label EC2 instance containers with resource identity

Backing containers now carry io.floci.service=ec2 and
io.floci.resource-id=<instanceId>, using the already-passed region
parameter and a new RegionResolver dependency for the account id.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(ecr): label the shared registry container with resource identity

The registry:2 container carries io.floci.service=ecr with no
resource-id, since it is a shared singleton, not a per-resource
container.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* docs(core): document io.floci.* resource-identity labels

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* style(tests): use imports instead of inline FQCN in resource-identity label tests

Cleans up the Batch, EKS, and OpenSearch label tests added earlier in
this branch, which used fully-qualified names inline instead of imports.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* fix(kinesisanalytics): restore Mockito import and awsEnv param in Flink label test

Silently dropped by the rebase's clean auto-merge; the test no longer compiled
without them.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* docs(core): note ECR keeps every identity label except resource-id

EcrRegistryManager still passes account/region for the shared registry
container; only resourceId is omitted. Docs previously said the opposite.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* test(elasticache): log swallowed IOException in label test cleanup

Matches the pattern already used in the DocDB/Neptune/MemoryDB label tests.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

---------

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-08-23 20:47:00 -04:00
1 parent 6f1ce9b23f
commit 824701481c
38 files changed
+972 -48

No files matched your search

+14
View File
@@ -140,6 +140,20 @@ Extra labels are a list of key/value entries rather than a map so that label key
!!! note
Entries using one of the reserved keys (`floci`, `floci_emulator`, `floci_namespace`) are ignored with a warning — user configuration can never break Floci's own container discovery and volume pruning.
### Resource Identity Labels
A container backing an emulated AWS resource also carries labels tying it back to that resource, additive to the labels above:
| Label | Value | Purpose |
|---|---|---|
| `io.floci` | `aws` | Cloud provider, for multi-cloud discovery when several Floci-like emulators share a host |
| `io.floci.service` | e.g. `rds` | The AWS service the container backs |
| `io.floci.resource-id` | e.g. `orders-db-primary` | The resource's identifier (DB instance identifier, cluster name, function name, ...) |
| `io.floci.account` | the resolved account id | The AWS account the resource belongs to |
| `io.floci.region` | the resolved region | The AWS region the resource belongs to |
This makes `docker ps --filter label=io.floci.resource-id=orders-db-primary` resolve a specific emulated resource to its backing container directly, without inferring it from names or creation order. Applied to RDS, DocDB, ElastiCache (Redis/Valkey and Memcached), MemoryDB, Neptune, MSK, OpenSearch, ECS, EKS, AmazonMQ, MWAA, Kinesis Data Analytics (Flink), Batch, CodeBuild, Lambda, and EC2. ECR's backing registry container carries every label except `io.floci.resource-id`, since it is a shared singleton with no single resource identifier.
## Docker Network
Containers spawned by Floci (Lambda, RDS, ElastiCache, OpenSearch, MSK, ECS) need to be on the same Docker network to communicate with each other and with Floci itself.
@@ -105,6 +105,31 @@ public final class ContainerStorageHelper {
return labels;
}
/**
* Labels tying a container to the specific AWS resource it emulates: {@code io.floci}
* (cloud provider, for multi-cloud discovery), {@code io.floci.service},
* {@code io.floci.resource-id}, {@code io.floci.account}, and {@code io.floci.region}.
* Merged into a spec's own labels (never into {@link #defaultLabels}), so callers pass
* this to {@link ContainerBuilder.Builder#withLabels}. A blank or null value omits that
* key entirely, e.g. ECR's shared registry container has no per-resource id.
*/
public static Map<String, String> resourceIdentityLabels(
String service, String resourceId, String accountId, String region) {
Map<String, String> labels = new LinkedHashMap<>();
labels.put("io.floci", CLOUD);
putIfNotBlank(labels, "io.floci.service", service);
putIfNotBlank(labels, "io.floci.resource-id", resourceId);
putIfNotBlank(labels, "io.floci.account", accountId);
putIfNotBlank(labels, "io.floci.region", region);
return labels;
}
private static void putIfNotBlank(Map<String, String> labels, String key, String value) {
if (value != null && !value.isBlank()) {
labels.put(key, value);
}
}
public static Path hostResourcePath(EmulatorConfig config, String service, String resourceId) {
String namespace = resourceNamespace(config);
Path base = Path.of(config.storage().hostPersistentPath());
@@ -83,7 +83,10 @@ public class RabbitMqManager {
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
.withName(containerName)
.withDockerNetwork(config.services().dockerNetwork())
.withLogRotation();
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"amazonmq", broker.getBrokerId(), regionResolver.getAccountId(),
regionResolver.getDefaultRegion()));
// Seed the broker's admin user. RabbitMQ's built-in `guest` user is
// loopback-only, so it cannot authenticate over the mapped host port; a user
@@ -74,7 +74,9 @@ public class BatchDockerRunner implements ContainerTeardown {
.withDockerNetwork(config.services().batch().dockerNetwork())
.withHostDockerInternalOnLinux()
.withEmbeddedDns()
.withLogRotation();
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"batch", job.getJobId(), job.getAccountId(), job.getRegion()));
if (job.getResolvedCommand() != null && !job.getResolvedCommand().isEmpty()) {
builder.withCmd(job.getResolvedCommand());
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.services.codebuild.BuildspecParser.ParsedArtifacts;
import io.github.hectorvent.floci.services.codebuild.BuildspecParser.ParsedBuildspec;
import io.github.hectorvent.floci.services.codebuild.model.Build;
@@ -220,6 +221,8 @@ public class CodeBuildRunner implements ContainerTeardown {
.withHostDockerInternalOnLinux()
.withPrivileged(privileged)
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"codebuild", buildId, regionResolver.getAccountId(), region))
.build();
ContainerLifecycleManager.ContainerInfo info = lifecycleManager.createAndStart(spec);
@@ -115,14 +115,16 @@ public class DocDbContainerManager {
.withName(containerName)
.withDockerNetwork(config.services().docdb().dockerNetwork())
.withLogRotation()
.withEnv(envVars);
.withEnv(envVars)
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"docdb", clusterId, regionResolver.getAccountId(), regionResolver.getDefaultRegion()));
if (!containerDetector.isRunningInContainer()) {
specBuilder.withDynamicPort(MONGO_PORT);
} else {
specBuilder.withExposedPort(MONGO_PORT);
}
ContainerSpec spec = specBuilder.build();
ContainerInfo info = lifecycleManager.createAndStart(spec);
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.ec2;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
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;
@@ -74,6 +75,7 @@ public class Ec2ContainerManager {
private final EmulatorConfig config;
private final Ec2MetadataServer metadataServer;
private final Ec2PortForwardManager portForwardManager;
private final RegionResolver regionResolver;
private final ExecutorService executor = Executors.newCachedThreadPool(r -> {
Thread t = new Thread(r, "ec2-container-launcher");
@@ -91,7 +93,8 @@ public class Ec2ContainerManager {
PortAllocator portAllocator,
EmulatorConfig config,
Ec2MetadataServer metadataServer,
Ec2PortForwardManager portForwardManager) {
Ec2PortForwardManager portForwardManager,
RegionResolver regionResolver) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.logStreamer = logStreamer;
@@ -100,6 +103,7 @@ public class Ec2ContainerManager {
this.dockerClient = dockerClient;
this.portAllocator = portAllocator;
this.config = config;
this.regionResolver = regionResolver;
this.metadataServer = metadataServer;
this.portForwardManager = portForwardManager;
}
@@ -309,6 +313,8 @@ public class Ec2ContainerManager {
.withPortBinding(22, sshHostPort)
.withHostDockerInternalOnLinux()
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"ec2", instanceId, regionResolver.getAccountId(), region))
// EC2 instances expose IMDS on 169.254.169.254. Floci needs network administration
// privileges in the local container to attach that link-local address.
.withPrivileged(true)
@@ -172,7 +172,9 @@ public class EcrRegistryManager {
.withEnv(env)
.withPortBinding(CONTAINER_INTERNAL_PORT, chosenPort)
.withDockerNetwork(resolveRegistryDockerNetwork())
.withLogRotation();
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"ecr", null, regionResolver.getAccountId(), regionResolver.getDefaultRegion()));
// Handle persistence mounting based on storage configuration
addPersistenceMounts(specBuilder, env);
@@ -136,7 +136,9 @@ public class EcsContainerManager {
// own loopback.
.withHostDockerInternalOnLinux()
.withEmbeddedDns()
.withLogRotation();
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"ecs", taskId, regionResolver.getAccountId(), region));
// Add memory limit if specified
if (def.getMemory() != null) {
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.eks;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.RegionResolver;
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;
@@ -60,6 +61,7 @@ public class EksClusterManager {
private final DockerHostResolver dockerHostResolver;
private final EcrRegistryManager ecrRegistryManager;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
@Inject
public EksClusterManager(ContainerBuilder containerBuilder,
@@ -68,7 +70,8 @@ public class EksClusterManager {
PortAllocator portAllocator,
DockerHostResolver dockerHostResolver,
EcrRegistryManager ecrRegistryManager,
EmulatorConfig config) {
EmulatorConfig config,
RegionResolver regionResolver) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.containerDetector = containerDetector;
@@ -76,6 +79,7 @@ public class EksClusterManager {
this.dockerHostResolver = dockerHostResolver;
this.ecrRegistryManager = ecrRegistryManager;
this.config = config;
this.regionResolver = regionResolver;
}
/**
@@ -120,7 +124,9 @@ public class EksClusterManager {
.withNamedVolume(volumeName, "/var/lib/rancher/k3s")
.withDockerNetwork(config.services().eks().dockerNetwork())
.withPrivileged(true)
.withLogRotation();
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"eks", cluster.getName(), regionResolver.getAccountId(), regionResolver.getDefaultRegion()));
// Wire a token-authentication webhook so `aws eks get-token` bearer tokens are validated by
// Floci and mapped to cluster-admin. The k3s API server POSTs a TokenReview to Floci's
@@ -84,7 +84,9 @@ public class ElastiCacheContainerManager {
.withName(containerName)
.withEnv("VALKEY_EXTRA_FLAGS", "--loglevel verbose")
.withDockerNetwork(config.services().elasticache().dockerNetwork())
.withLogRotation();
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"elasticache", groupId, regionResolver.getAccountId(), regionResolver.getDefaultRegion()));
if (!containerDetector.isRunningInContainer()) {
specBuilder.withDynamicPort(BACKEND_PORT);
@@ -74,7 +74,9 @@ public class ElastiCacheMemcachedContainerManager {
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
.withName(containerName)
.withDockerNetwork(config.services().elasticache().dockerNetwork())
.withLogRotation();
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"elasticache", clusterId, regionResolver.getAccountId(), regionResolver.getDefaultRegion()));
if (!containerDetector.isRunningInContainer()) {
specBuilder.withDynamicPort(BACKEND_PORT);
@@ -153,7 +153,10 @@ public class FlinkContainerManager {
.withDockerNetwork(config.services().dockerNetwork())
.withHostDockerInternalOnLinux()
.withEmbeddedDns()
.withLogRotation();
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"kinesisanalytics", app.getApplicationName(), regionResolver.getAccountId(),
regionResolver.getDefaultRegion()));
// Named volume (not the container's ephemeral filesystem) so snapshots survive a
// Stop/StartApplication cycle — stopCluster() removes the JobManager container, but this
// volume is only removed on DeleteApplication (removeSavepointsVolume), mirroring how other
@@ -194,6 +197,9 @@ public class FlinkContainerManager {
.withEnv("FLINK_PROPERTIES", tmProps)
.withNetworkMode("container:" + jm.containerId())
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"kinesisanalytics", app.getApplicationName(), regionResolver.getAccountId(),
regionResolver.getDefaultRegion()))
.build();
try {
ContainerInfo tm = lifecycleManager.createAndStart(tmSpec);
@@ -251,6 +251,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
String cwLogGroup = "/aws/lambda/" + fn.getFunctionName();
String cwLogStream = LOG_STREAM_DATE_FMT.format(LocalDate.now()) + "/[$LATEST]" + shortId;
String lambdaRegion = extractRegionFromArn(fn.getFunctionArn(), config.defaultRegion());
String lambdaAccountId = AwsArnUtils.accountOrDefault(fn.getFunctionArn(), config.defaultAccountId());
// When TLS is on, the container must trust Floci's self-signed cert so HTTPS callbacks
// to Floci succeed (e.g. a CDK custom resource's cfn-response, which hardcodes https://).
@@ -298,7 +299,9 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
.withMemoryMb(fn.getMemorySize())
.withDockerNetwork(config.services().lambda().dockerNetwork())
.withHostDockerInternalOnLinux()
.withLogRotation();
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"lambda", fn.getFunctionName(), lambdaAccountId, lambdaRegion));
specBuilder.withEmbeddedDns();
@@ -119,7 +119,9 @@ public class MemoryDbContainerManager {
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
.withName(containerName)
.withDockerNetwork(config.services().memorydb().dockerNetwork())
.withLogRotation();
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"memorydb", clusterName, regionResolver.getAccountId(), regionResolver.getDefaultRegion()));
if (!containerDetector.isRunningInContainer()) {
specBuilder.withDynamicPort(BACKEND_PORT);
@@ -103,7 +103,10 @@ public class RedpandaManager {
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
.withName(containerName)
.withDockerNetwork(config.services().dockerNetwork())
.withLogRotation();
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"msk", cluster.getClusterName(), regionResolver.getAccountId(),
regionResolver.getDefaultRegion()));
if (!containerDetector.isRunningInContainer()) {
specBuilder.withPortBinding(KAFKA_PORT, kafkaHostPort).withDynamicPort(ADMIN_PORT);
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.mwaa;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
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;
@@ -65,18 +66,21 @@ public class MwaaEnvironmentManager {
private final ContainerDetector containerDetector;
private final EmulatorConfig config;
private final LaunchedContainerAwsEnv awsEnv;
private final RegionResolver regionResolver;
@Inject
public MwaaEnvironmentManager(ContainerBuilder containerBuilder,
ContainerLifecycleManager lifecycleManager,
ContainerDetector containerDetector,
EmulatorConfig config,
LaunchedContainerAwsEnv awsEnv) {
LaunchedContainerAwsEnv awsEnv,
RegionResolver regionResolver) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.containerDetector = containerDetector;
this.config = config;
this.awsEnv = awsEnv;
this.regionResolver = regionResolver;
}
/**
@@ -109,6 +113,8 @@ public class MwaaEnvironmentManager {
.withDockerNetwork(config.services().mwaa().dockerNetwork())
.withExposedPort(POSTGRES_PORT)
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"mwaa", name, regionResolver.getAccountId(), regionResolver.getDefaultRegion()))
.build();
String dbContainerId = lifecycleManager.create(dbSpec);
@@ -169,7 +175,9 @@ public class MwaaEnvironmentManager {
.withNamedVolume(dagsVolume, DAGS_MOUNT)
.withNamedVolume(logsVolume, LOGS_MOUNT)
.withDockerNetwork(config.services().mwaa().dockerNetwork())
.withLogRotation();
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"mwaa", name, regionResolver.getAccountId(), regionResolver.getDefaultRegion()));
if (!containerDetector.isRunningInContainer()) {
specBuilder.withDynamicPort(AIRFLOW_WEBSERVER_PORT);
@@ -117,7 +117,9 @@ public class NeptuneContainerManager {
.withName(containerName)
.withEnv(backendEnv(dbType))
.withDockerNetwork(config.services().neptune().dockerNetwork())
.withLogRotation();
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"neptune", clusterId, regionResolver.getAccountId(), regionResolver.getDefaultRegion()));
if (!containerDetector.isRunningInContainer()) {
specBuilder.withDynamicPort(backendPort);
@@ -1,6 +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.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
@@ -32,18 +33,21 @@ public class OpenSearchDomainManager {
private final ContainerDetector containerDetector;
private final PortAllocator portAllocator;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
@Inject
public OpenSearchDomainManager(ContainerBuilder containerBuilder,
ContainerLifecycleManager lifecycleManager,
ContainerDetector containerDetector,
PortAllocator portAllocator,
EmulatorConfig config) {
EmulatorConfig config,
RegionResolver regionResolver) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.containerDetector = containerDetector;
this.portAllocator = portAllocator;
this.config = config;
this.regionResolver = regionResolver;
}
public void startDomain(Domain domain) {
@@ -64,7 +68,10 @@ public class OpenSearchDomainManager {
.withEnv("discovery.type", "single-node")
.withPortBinding(OPENSEARCH_PORT, hostPort)
.withDockerNetwork(config.services().dockerNetwork())
.withLogRotation();
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"opensearch", domain.getDomainName(), regionResolver.getAccountId(),
regionResolver.getDefaultRegion()));
applyEngineEnv(specBuilder, domain.getEngineVersion());
@@ -130,6 +130,8 @@ public class RdsContainerManager {
// Build environment variables
List<String> envVars = buildEnvVars(engine, masterUsername, masterPassword, dbName);
RuntimeIdentity runtimeIdentity = resolveRuntimeIdentity(effectiveRuntimeId);
// Build container spec with bind mounts for persistence. Publish the
// engine port to the host only in native mode; in Docker mode the auth
// proxy reaches the DB via the container network.
@@ -137,7 +139,9 @@ public class RdsContainerManager {
.withName(containerName)
.withEnv(envVars)
.withDockerNetwork(config.services().rds().dockerNetwork())
.withLogRotation();
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"rds", instanceId, runtimeIdentity.accountId(), runtimeIdentity.region()));
if (!containerDetector.isRunningInContainer()) {
specBuilder.withDynamicPort(enginePort);
@@ -179,29 +183,13 @@ public class RdsContainerManager {
: info.containerId();
String logGroup = "/aws/rds/instance/" + instanceId + "/error";
String logStream = logStreamer.generateLogStreamName(shortId);
String region = regionResolver.getDefaultRegion();
String accountId = null;
try {
AwsArnUtils.Arn runtimeArn = AwsArnUtils.parse(effectiveRuntimeId);
if ("rds".equals(runtimeArn.service())) {
if (!runtimeArn.region().isBlank()) {
region = runtimeArn.region();
}
if (!runtimeArn.accountId().isBlank()) {
accountId = runtimeArn.accountId();
}
}
} catch (IllegalArgumentException ignored) {
LOG.debugv("Using legacy RDS runtime identity for log routing: {0}",
effectiveRuntimeId);
}
Closeable logHandle = accountId != null
Closeable logHandle = runtimeIdentity.arnAccountId() != null
? logStreamer.attachForAccount(
accountId, info.containerId(), logGroup, logStream, region,
"rds:" + effectiveRuntimeId)
runtimeIdentity.arnAccountId(), info.containerId(), logGroup,
logStream, runtimeIdentity.region(), "rds:" + effectiveRuntimeId)
: logStreamer.attach(
info.containerId(), logGroup, logStream, region,
info.containerId(), logGroup, logStream, runtimeIdentity.region(),
"rds:" + effectiveRuntimeId);
handle.setLogStream(logHandle);
activeContainers.put(effectiveRuntimeId, handle);
@@ -237,6 +225,34 @@ public class RdsContainerManager {
}
}
/**
* Resolves the region and account id backing an RDS runtime identity. {@code accountId} is
* never blank (falls back to {@link RegionResolver#getAccountId}); {@code arnAccountId} keeps
* the pre-existing null-when-absent semantics that log-stream routing depends on to pick
* between {@code attach} and {@code attachForAccount}.
*/
private RuntimeIdentity resolveRuntimeIdentity(String runtimeId) {
String region = regionResolver.getDefaultRegion();
String arnAccountId = null;
try {
AwsArnUtils.Arn runtimeArn = AwsArnUtils.parse(runtimeId);
if ("rds".equals(runtimeArn.service())) {
if (!runtimeArn.region().isBlank()) {
region = runtimeArn.region();
}
if (!runtimeArn.accountId().isBlank()) {
arnAccountId = runtimeArn.accountId();
}
}
} catch (IllegalArgumentException ignored) {
LOG.debugv("Using legacy RDS runtime identity for log routing: {0}", runtimeId);
}
String accountId = arnAccountId != null ? arnAccountId : regionResolver.getAccountId();
return new RuntimeIdentity(region, accountId, arnAccountId);
}
private record RuntimeIdentity(String region, String accountId, String arnAccountId) {}
public void stop(RdsContainerHandle handle) {
if (handle == null) {
return;
@@ -115,6 +115,26 @@ class ContainerStorageHelperTest {
ContainerStorageHelper.defaultLabels(config));
}
@Test
void resourceIdentityLabelsCarryTheFullEmulatedResourceIdentity() {
assertEquals(
Map.of("io.floci", "aws",
"io.floci.service", "rds",
"io.floci.resource-id", "orders-db-primary",
"io.floci.account", "000000000000",
"io.floci.region", "us-east-1"),
ContainerStorageHelper.resourceIdentityLabels(
"rds", "orders-db-primary", "000000000000", "us-east-1"));
}
@Test
void resourceIdentityLabelsOmitBlankOrMissingValues() {
// ECR's sibling registry is a shared singleton with no per-resource identifier.
assertEquals(
Map.of("io.floci", "aws", "io.floci.service", "ecr"),
ContainerStorageHelper.resourceIdentityLabels("ecr", null, "", " "));
}
private static EmulatorConfig.DockerConfig.LabelEntry label(String key, String value) {
return new EmulatorConfig.DockerConfig.LabelEntry() {
@Override
@@ -6,13 +6,20 @@ 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;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.services.amazonmq.model.Broker;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.Map;
import java.util.Optional;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
class RabbitMqManagerTest {
@@ -36,6 +43,52 @@ class RabbitMqManagerTest {
"SINGLE_INSTANCE", "mq.t3.micro");
}
@Test
void startContainerLabelsContainerWithResourceIdentity() {
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = Mockito.mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.AmazonMqServiceConfig amazonmq = Mockito.mock(EmulatorConfig.AmazonMqServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.amazonmq()).thenReturn(amazonmq);
when(services.dockerNetwork()).thenReturn(Optional.empty());
when(amazonmq.defaultImage()).thenReturn("rabbitmq:3.13-management");
EmulatorConfig.DockerConfig docker = Mockito.mock(EmulatorConfig.DockerConfig.class);
when(config.docker()).thenReturn(docker);
when(docker.logMaxSize()).thenReturn("10m");
when(docker.logMaxFile()).thenReturn("3");
EmulatorConfig.StorageConfig storage = Mockito.mock(EmulatorConfig.StorageConfig.class);
when(config.storage()).thenReturn(storage);
when(storage.hostPersistentPath()).thenReturn("floci-data");
ContainerLifecycleManager lifecycleManager = Mockito.mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(
new ContainerLifecycleManager.ContainerInfo("container-id", Map.of(
5672, new ContainerLifecycleManager.EndpointInfo("localhost", 5672),
15672, new ContainerLifecycleManager.EndpointInfo("localhost", 15672))));
ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class));
RegionResolver regionResolver = Mockito.mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
RabbitMqManager manager = new RabbitMqManager(containerBuilder, lifecycleManager,
Mockito.mock(ContainerLogStreamer.class), Mockito.mock(ContainerDetector.class),
config, regionResolver);
manager.startContainer(broker("b-1"));
verify(builder).withLabels(Map.of(
"io.floci", "aws",
"io.floci.service", "amazonmq",
"io.floci.resource-id", "b-1",
"io.floci.account", "000000000000",
"io.floci.region", "us-east-1"));
}
@Test
void stopContainerUsesContainerIdWhenPresent() {
Broker broker = broker("b-1");
@@ -6,12 +6,21 @@ 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;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.services.batch.model.BatchJob;
import com.github.dockerjava.api.DockerClient;
import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class BatchDockerRunnerTest {
@@ -40,6 +49,56 @@ class BatchDockerRunnerTest {
assertEquals(EmbeddedDnsServer.DEFAULT_SUFFIX, runner(config(Optional.empty()), detector).resolveEndpointHostname());
}
@Test
void runLabelsContainerWithResourceIdentity() {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.BatchServiceConfig batch = mock(EmulatorConfig.BatchServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.batch()).thenReturn(batch);
when(batch.dockerNetwork()).thenReturn(Optional.empty());
when(config.port()).thenReturn(4566);
when(config.hostname()).thenReturn(Optional.empty());
ContainerDetector detector = mock(ContainerDetector.class);
when(detector.isRunningInContainer()).thenReturn(false);
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(
new ContainerLifecycleManager.ContainerInfo("container-id", Map.of()));
DockerClient dockerClient =
mock(DockerClient.class, RETURNS_DEEP_STUBS);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
when(dockerClient.inspectContainerCmd("container-id").exec().getState().getRunning()).thenReturn(false);
when(dockerClient.inspectContainerCmd("container-id").exec().getState().getExitCodeLong()).thenReturn(0L);
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(mock(ContainerSpec.class));
BatchDockerRunner runner = new BatchDockerRunner(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), config, detector);
BatchJob job = new BatchJob();
job.setJobId("job-1");
job.setJobName("my-job");
job.setJobQueueName("my-queue");
job.setJobDefinitionName("my-def");
job.setContainerImage("busybox:stable");
job.setRegion("us-east-1");
job.setAccountId("000000000000");
runner.run(job, 1);
verify(builder).withLabels(Map.of(
"io.floci", "aws",
"io.floci.service", "batch",
"io.floci.resource-id", "job-1",
"io.floci.account", "000000000000",
"io.floci.region", "us-east-1"));
}
private BatchDockerRunner runner(EmulatorConfig config, ContainerDetector detector) {
return new BatchDockerRunner(
mock(ContainerBuilder.class),
@@ -26,6 +26,7 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class DocDbContainerManagerTest {
@@ -99,6 +100,55 @@ class DocDbContainerManagerTest {
}
}
@Test
void startLabelsContainerWithResourceIdentity() throws IOException {
try (ServerSocket serverSocket = new ServerSocket(0)) {
Thread acceptor = new Thread(() -> {
try (Socket socket = serverSocket.accept()) {
socket.getInputStream().read(new byte[1]);
} catch (IOException e) {
LOG.debugv(e, "Acceptor socket closed during test teardown");
}
});
acceptor.setDaemon(true);
acceptor.start();
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
"container-id", Map.of(27017,
new ContainerLifecycleManager.EndpointInfo(
"127.0.0.1", serverSocket.getLocalPort()))));
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(mock(ContainerSpec.class));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.DocDbServiceConfig docdb = mock(EmulatorConfig.DocDbServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.docdb()).thenReturn(docdb);
when(docdb.dockerNetwork()).thenReturn(Optional.empty());
DocDbContainerManager manager = new DocDbContainerManager(containerBuilder, lifecycleManager,
logStreamer, mock(ContainerDetector.class), config,
new RegionResolver("us-east-1", "000000000000"));
manager.start("cluster1", "mongo:7.0", "admin", "secret");
verify(builder).withLabels(Map.of(
"io.floci", "aws",
"io.floci.service", "docdb",
"io.floci.resource-id", "cluster1",
"io.floci.account", "000000000000",
"io.floci.region", "us-east-1"));
}
}
private DocDbContainerManager newManager(ContainerLifecycleManager lifecycleManager) {
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
@@ -17,6 +17,7 @@ import java.nio.charset.StandardCharsets;
import com.github.dockerjava.api.model.NetworkSettings;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
import io.github.hectorvent.floci.core.common.RegionResolver;
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;
@@ -135,7 +136,8 @@ class Ec2ContainerManagerTest {
mock(PortAllocator.class),
mock(EmulatorConfig.class, RETURNS_DEEP_STUBS),
metadataServer,
mock(Ec2PortForwardManager.class));
mock(Ec2PortForwardManager.class),
mock(RegionResolver.class));
Instance instance = new Instance();
instance.setInstanceId("i-restored");
@@ -237,6 +239,27 @@ class Ec2ContainerManagerTest {
);
}
@Test
void launchLabelsContainerWithResourceIdentity() throws Exception {
LaunchHarness harness = launchHarness();
harness.stubSuccessfulExecs(new CountDownLatch(0), new CountDownLatch(0));
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
InspectContainerResponse response = inspectResponse("192.168.215.42");
when(harness.dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect);
when(inspect.exec()).thenReturn(response);
Instance instance = instance("i-labeltest");
harness.manager.launch(instance, "ubuntu:24.04", null, "us-west-2");
verify(harness.builder, timeout(2000)).withLabels(Map.of(
"io.floci", "aws",
"io.floci.service", "ec2",
"io.floci.resource-id", "i-labeltest",
"io.floci.account", "000000000000",
"io.floci.region", "us-west-2"));
}
@Test
void metadataProxyInstallCommandInstallsLinkLocalProxyDependencies() {
String[] command = Ec2ContainerManager.metadataProxyInstallCommand();
@@ -739,6 +762,8 @@ class Ec2ContainerManagerTest {
Ec2MetadataServer metadataServer = mock(Ec2MetadataServer.class);
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
Ec2PortForwardManager portForwardManager = mock(Ec2PortForwardManager.class);
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
Ec2ContainerManager manager = new Ec2ContainerManager(
containerBuilder,
lifecycleManager,
@@ -749,7 +774,8 @@ class Ec2ContainerManagerTest {
portAllocator,
config,
metadataServer,
portForwardManager);
portForwardManager,
regionResolver);
return new LaunchHarness(manager, lifecycleManager, dockerClient, metadataServer, logStreamer, builder,
portAllocator, portForwardManager, new CopyOnWriteArrayList<>());
}
@@ -24,6 +24,7 @@ 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.Mockito.verify;
import static org.mockito.Mockito.when;
/**
@@ -42,6 +43,7 @@ class EcrRegistryManagerTest {
private ContainerDetector containerDetector;
private CurrentContainerNetworkResolver currentContainerNetworkResolver;
private EmulatorConfig.DockerConfig docker;
private ContainerBuilder.Builder builder;
private EcrRegistryManager manager;
@BeforeEach
@@ -49,8 +51,7 @@ class EcrRegistryManagerTest {
portAllocator = new PortAllocator();
ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class);
ContainerBuilder.Builder builder =
Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class));
@@ -83,6 +84,20 @@ class EcrRegistryManagerTest {
containerDetector, currentContainerNetworkResolver, portAllocator, config, regionResolver);
}
@Test
void ensureStartedLabelsContainerWithResourceIdentity() {
when(lifecycleManager.createAndStart(any())).thenReturn(
new ContainerLifecycleManager.ContainerInfo("container-id", Map.of()));
manager.ensureStarted();
verify(builder).withLabels(Map.of(
"io.floci", "aws",
"io.floci.service", "ecr",
"io.floci.account", "000000000000",
"io.floci.region", "us-east-1"));
}
@Test
void ensureStarted_releasesPortWhenDockerStartFails_soPoolIsNotExhausted() {
when(lifecycleManager.createAndStart(any()))
@@ -60,6 +60,7 @@ class EcsContainerManagerPortMappingsTest {
private ContainerBuilder.Builder builder;
private ContainerLifecycleManager lifecycleManager;
private ContainerDetector containerDetector;
private RegionResolver regionResolver;
private EcsContainerManager manager;
@BeforeEach
@@ -79,7 +80,7 @@ class EcsContainerManagerPortMappingsTest {
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
containerDetector = mock(ContainerDetector.class);
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
RegionResolver regionResolver = mock(RegionResolver.class);
regionResolver = mock(RegionResolver.class);
LaunchedContainerAwsEnv awsEnv = mock(LaunchedContainerAwsEnv.class);
when(awsEnv.sdkBaselineEnv(any(), any())).thenReturn(List.of());
SsmService ssmService = mock(SsmService.class);
@@ -110,6 +111,32 @@ class EcsContainerManagerPortMappingsTest {
manager.startTask(task, taskDef, List.of(), "us-east-1");
}
@Test
void startTaskLabelsContainerWithResourceIdentity() {
when(containerDetector.isRunningInContainer()).thenReturn(false);
when(regionResolver.getAccountId()).thenReturn("000000000000");
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
app.setImage("app:latest");
TaskDefinition taskDef = new TaskDefinition();
taskDef.setFamily("test-family");
taskDef.setContainerDefinitions(List.of(app));
EcsTask task = new EcsTask();
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123");
manager.startTask(task, taskDef, List.of(), "us-east-1");
verify(builder).withLabels(Map.of(
"io.floci", "aws",
"io.floci.service", "ecs",
"io.floci.resource-id", "abc123",
"io.floci.account", "000000000000",
"io.floci.region", "us-east-1"));
}
@Test
void explicitHostPortIsPublishedAsFixedBindingInNativeMode() {
when(containerDetector.isRunningInContainer()).thenReturn(false);
@@ -2,12 +2,16 @@ package io.github.hectorvent.floci.services.eks;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.RegionResolver;
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;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.core.common.docker.PortAllocator;
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
import io.github.hectorvent.floci.services.eks.model.Cluster;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
import org.junit.jupiter.api.BeforeEach;
@@ -18,6 +22,8 @@ import org.mockito.Mockito;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -154,6 +160,53 @@ class EksClusterManagerTest {
assertEquals(serverArgs, wrapped.subList(1, wrapped.size()));
}
@Test
void startClusterLabelsContainerWithResourceIdentity() {
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = Mockito.mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.EksServiceConfig eks = Mockito.mock(EmulatorConfig.EksServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.eks()).thenReturn(eks);
when(eks.defaultImage()).thenReturn("rancher/k3s:v1.30.0-k3s1");
when(eks.apiServerBasePort()).thenReturn(6440);
when(eks.apiServerMaxPort()).thenReturn(6499);
when(eks.dockerNetwork()).thenReturn(Optional.empty());
when(eks.disableCni()).thenReturn(false);
when(eks.iamAuthWebhook()).thenReturn(false);
when(eks.ecrRegistryMirror()).thenReturn(false);
ContainerLifecycleManager lifecycleManager = Mockito.mock(ContainerLifecycleManager.class);
when(lifecycleManager.create(any())).thenReturn("container-id");
when(lifecycleManager.startCreated(any(), any())).thenReturn(
new ContainerInfo("container-id", Map.of()));
ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class));
RegionResolver regionResolver = Mockito.mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
EksClusterManager manager = new EksClusterManager(containerBuilder, lifecycleManager,
Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class),
Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class),
config, regionResolver);
Cluster cluster = new Cluster();
cluster.setName("my-cluster");
manager.startCluster(cluster);
verify(builder).withLabels(Map.of(
"io.floci", "aws",
"io.floci.service", "eks",
"io.floci.resource-id", "my-cluster",
"io.floci.account", "000000000000",
"io.floci.region", "us-east-1"));
}
/** Mirror-injection guard behavior, without a Docker daemon. */
@Nested
class InjectEcrRegistryMirror {
@@ -196,7 +249,8 @@ class EksClusterManagerTest {
manager = new EksClusterManager(
Mockito.mock(ContainerBuilder.class), lifecycleManager,
Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class),
Mockito.mock(DockerHostResolver.class), registryManager, config);
Mockito.mock(DockerHostResolver.class), registryManager, config,
Mockito.mock(RegionResolver.class));
}
@Test
@@ -6,13 +6,28 @@ 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;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import org.jboss.logging.Logger;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Optional;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ElastiCacheContainerManagerTest {
private static final Logger LOG = Logger.getLogger(ElastiCacheContainerManagerTest.class);
@Test
void stopByGroupIdRemovesByDeterministicNameWhenNothingRegistered() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
@@ -26,4 +41,55 @@ class ElastiCacheContainerManagerTest {
verify(lifecycleManager).removeIfExists("floci-valkey-my-group");
}
@Test
void startLabelsContainerWithResourceIdentity() throws IOException {
try (ServerSocket serverSocket = new ServerSocket(0)) {
Thread acceptor = new Thread(() -> {
try (Socket socket = serverSocket.accept()) {
socket.getInputStream().read(new byte[1024]);
socket.getOutputStream().write("+PONG\r\n".getBytes(StandardCharsets.UTF_8));
socket.getOutputStream().flush();
} catch (IOException e) {
LOG.debugv(e, "Acceptor socket closed during test teardown");
}
});
acceptor.setDaemon(true);
acceptor.start();
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
"container-id", Map.of(6379,
new ContainerLifecycleManager.EndpointInfo(
"127.0.0.1", serverSocket.getLocalPort()))));
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(mock(ContainerSpec.class));
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.ElastiCacheServiceConfig elasticache = mock(EmulatorConfig.ElastiCacheServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.elasticache()).thenReturn(elasticache);
when(elasticache.dockerNetwork()).thenReturn(Optional.empty());
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
ElastiCacheContainerManager manager = new ElastiCacheContainerManager(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), mock(ContainerDetector.class), config, regionResolver);
manager.start("my-group", "valkey/valkey:7.2");
verify(builder).withLabels(Map.of(
"io.floci", "aws",
"io.floci.service", "elasticache",
"io.floci.resource-id", "my-group",
"io.floci.account", "000000000000",
"io.floci.region", "us-east-1"));
}
}
}
@@ -0,0 +1,82 @@
package io.github.hectorvent.floci.services.elasticache.container;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
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;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import org.jboss.logging.Logger;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Optional;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ElastiCacheMemcachedContainerManagerTest {
private static final Logger LOG = Logger.getLogger(ElastiCacheMemcachedContainerManagerTest.class);
@Test
void startLabelsContainerWithResourceIdentity() throws IOException {
try (ServerSocket serverSocket = new ServerSocket(0)) {
Thread acceptor = new Thread(() -> {
try (Socket socket = serverSocket.accept()) {
socket.getInputStream().read(new byte[1024]);
socket.getOutputStream().write("VERSION 1.6.0\r\n".getBytes(StandardCharsets.UTF_8));
socket.getOutputStream().flush();
} catch (IOException e) {
LOG.debugv(e, "Acceptor socket closed during test teardown");
}
});
acceptor.setDaemon(true);
acceptor.start();
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
"container-id", Map.of(11211,
new ContainerLifecycleManager.EndpointInfo(
"127.0.0.1", serverSocket.getLocalPort()))));
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(mock(ContainerSpec.class));
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.ElastiCacheServiceConfig elasticache = mock(EmulatorConfig.ElastiCacheServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.elasticache()).thenReturn(elasticache);
when(elasticache.dockerNetwork()).thenReturn(Optional.empty());
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
ElastiCacheMemcachedContainerManager manager = new ElastiCacheMemcachedContainerManager(
containerBuilder, lifecycleManager, mock(ContainerLogStreamer.class),
mock(ContainerDetector.class), config, regionResolver);
manager.start("my-cluster", "memcached:1.6");
verify(builder).withLabels(Map.of(
"io.floci", "aws",
"io.floci.service", "elasticache",
"io.floci.resource-id", "my-cluster",
"io.floci.account", "000000000000",
"io.floci.region", "us-east-1"));
}
}
}
@@ -20,6 +20,7 @@ import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import java.util.LinkedHashMap;
import java.util.List;
@@ -31,6 +32,7 @@ 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.atLeastOnce;
import static org.mockito.Mockito.mock;
@@ -121,6 +123,56 @@ class FlinkContainerManagerTest {
"FLINK-1_18", "arn:aws:iam::000000000000:role/x", "STREAMING");
}
@Test
void startClusterLabelsJobManagerContainerWithResourceIdentity() {
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = Mockito.mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.KinesisAnalyticsServiceConfig kinesisAnalytics =
Mockito.mock(EmulatorConfig.KinesisAnalyticsServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.kinesisAnalytics()).thenReturn(kinesisAnalytics);
when(services.dockerNetwork()).thenReturn(Optional.empty());
when(kinesisAnalytics.defaultImage()).thenReturn(Optional.empty());
EmulatorConfig.DockerConfig docker = Mockito.mock(EmulatorConfig.DockerConfig.class);
when(config.docker()).thenReturn(docker);
when(docker.logMaxSize()).thenReturn("10m");
when(docker.logMaxFile()).thenReturn("3");
EmulatorConfig.StorageConfig storage = Mockito.mock(EmulatorConfig.StorageConfig.class);
when(config.storage()).thenReturn(storage);
when(storage.hostPersistentPath()).thenReturn("floci-data");
ContainerLifecycleManager lifecycleManager = Mockito.mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(
new ContainerLifecycleManager.ContainerInfo("jm-container-id", Map.of(8081,
new ContainerLifecycleManager.EndpointInfo("localhost", 8081))));
ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class));
RegionResolver regionResolver = Mockito.mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
FlinkContainerManager manager = new FlinkContainerManager(containerBuilder, lifecycleManager,
Mockito.mock(ContainerLogStreamer.class), Mockito.mock(ContainerDetector.class), config,
regionResolver, Mockito.mock(LaunchedContainerAwsEnv.class), Mockito.mock(S3Service.class),
Mockito.mock(FlinkRestClient.class), MAPPER);
FlinkApplication app = new FlinkApplication();
app.setApplicationName("my-app");
manager.startCluster(app);
verify(builder).withLabels(Map.of(
"io.floci", "aws",
"io.floci.service", "kinesisanalytics",
"io.floci.resource-id", "my-app",
"io.floci.account", "000000000000",
"io.floci.region", "us-east-1"));
}
@Test
void applicationPropertiesJsonMatchesTheRealMsfFileShape() throws Exception {
FlinkApplication app = new FlinkApplication("demo", "arn:aws:kinesisanalytics:us-east-1:000000000000:application/demo",
@@ -107,6 +107,7 @@ class ContainerLauncherTest {
when(config.tls()).thenReturn(tls);
lenient().when(tls.enabled()).thenReturn(false);
lenient().when(config.defaultRegion()).thenReturn("us-east-1");
lenient().when(config.defaultAccountId()).thenReturn("000000000000");
lenient().when(config.hostname()).thenReturn(Optional.empty());
// The large-code path resolves a code-volume completion marker under the storage persistent path.
lenient().when(config.storage()).thenReturn(storage);
@@ -210,6 +211,29 @@ class ContainerLauncherTest {
.orElse(null);
}
@Test
void launchFunction_labelsContainerWithResourceIdentity() throws Exception {
Path codePath = Files.createDirectory(tempDir.resolve("code"));
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("standard-fn");
fn.setFunctionArn("arn:aws:lambda:us-west-2:222222222222:function:standard-fn");
fn.setRuntime("nodejs20.x");
fn.setHandler("index.handler");
fn.setCodeLocalPath(codePath.toString());
launcher.launch(fn);
ContainerSpec spec = captureRealContainerSpec();
assertEquals(Map.of(
"io.floci", "aws",
"io.floci.service", "lambda",
"io.floci.resource-id", "standard-fn",
"io.floci.account", "222222222222",
"io.floci.region", "us-west-2"),
spec.labels());
}
@Test
void launchFunction_createsWithoutBindMountsOrVolume_forSmallCode() throws Exception {
Path codePath = Files.createDirectory(tempDir.resolve("code"));
@@ -118,6 +118,54 @@ class MemoryDbContainerManagerTest {
}
}
@Test
void startLabelsContainerWithResourceIdentity() throws IOException {
try (ServerSocket serverSocket = new ServerSocket(0)) {
Thread responder = new Thread(() -> {
try (Socket socket = serverSocket.accept()) {
socket.getInputStream().read(new byte[64]);
OutputStream out = socket.getOutputStream();
out.write("+PONG\r\n".getBytes(java.nio.charset.StandardCharsets.UTF_8));
out.flush();
} catch (IOException e) {
LOG.debugv(e, "Acceptor socket closed during test teardown");
}
});
responder.setDaemon(true);
responder.start();
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
"container-id", Map.of(6379, new ContainerLifecycleManager.EndpointInfo(
"127.0.0.1", serverSocket.getLocalPort()))));
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(mock(ContainerSpec.class));
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.MemoryDbServiceConfig memorydb = mock(EmulatorConfig.MemoryDbServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.memorydb()).thenReturn(memorydb);
when(memorydb.dockerNetwork()).thenReturn(Optional.empty());
MemoryDbContainerManager manager = new MemoryDbContainerManager(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), mock(ContainerDetector.class), config,
new RegionResolver("us-east-1", "000000000000"));
manager.start("cluster1", "valkey/valkey:8");
verify(builder).withLabels(Map.of(
"io.floci", "aws",
"io.floci.service", "memorydb",
"io.floci.resource-id", "cluster1",
"io.floci.account", "000000000000",
"io.floci.region", "us-east-1"));
}
}
private MemoryDbContainerManager newManager(ContainerLifecycleManager lifecycleManager) {
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
@@ -101,6 +101,7 @@ class RedpandaManagerTest {
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
lenient().when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
lenient().when(regionResolver.getAccountId()).thenReturn("000000000000");
}
@AfterEach
@@ -207,6 +208,28 @@ class RedpandaManagerTest {
verifyNoInteractions(portAllocator);
}
@Test
void startContainerLabelsContainerWithResourceIdentity() {
when(containerDetector.isRunningInContainer()).thenReturn(true);
ContainerInfo info = new ContainerInfo("container-456",
Map.of(KAFKA_PORT, new EndpointInfo("172.18.0.5", KAFKA_PORT)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
manager.startContainer(newCluster());
verify(lifecycleManager).createAndStart(specCaptor.capture());
assertEquals(
Map.of("io.floci", "aws",
"io.floci.service", "msk",
"io.floci.resource-id", "test-cluster",
"io.floci.account", "000000000000",
"io.floci.region", "us-east-1"),
specCaptor.getValue().labels());
}
@Test
void stopContainerReleasesAllocatedKafkaHostPort() {
when(containerDetector.isRunningInContainer()).thenReturn(false);
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.mwaa;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
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;
@@ -40,6 +41,7 @@ class MwaaEnvironmentManagerTest {
private ContainerLifecycleManager lifecycleManager;
private ContainerDetector containerDetector;
private RegionResolver regionResolver;
private MwaaEnvironmentManager manager;
@BeforeEach
@@ -77,7 +79,12 @@ class MwaaEnvironmentManagerTest {
"AWS_SECRET_ACCESS_KEY=test",
"AWS_ENDPOINT_URL=http://localhost:4566"));
manager = new MwaaEnvironmentManager(containerBuilder, lifecycleManager, containerDetector, config, awsEnv);
regionResolver = Mockito.mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
manager = new MwaaEnvironmentManager(containerBuilder, lifecycleManager, containerDetector, config,
awsEnv, regionResolver);
}
@SuppressWarnings("unchecked")
@@ -108,6 +115,19 @@ class MwaaEnvironmentManagerTest {
return captor.getValue();
}
@Test
void startAirflowContainerLabelsContainerWithResourceIdentity() {
ContainerSpec spec = startAirflowAndCaptureSpec(false);
assertEquals(Map.of(
"io.floci", "aws",
"io.floci.service", "mwaa",
"io.floci.resource-id", "my-env",
"io.floci.account", "000000000000",
"io.floci.region", "us-east-1"),
spec.labels());
}
@Test
void airflowImageTagSubstitutesTheRequestedVersion() {
ContainerSpec spec = startAirflowAndCaptureSpec(false);
@@ -120,6 +120,54 @@ class NeptuneContainerManagerTest {
}
}
@Test
void startLabelsContainerWithResourceIdentity() throws IOException {
try (ServerSocket serverSocket = new ServerSocket(0)) {
Thread responder = new Thread(() -> {
try (Socket socket = serverSocket.accept()) {
socket.getInputStream().read(new byte[64]);
OutputStream out = socket.getOutputStream();
out.write("HTTP/1.1 400 Bad Request\r\n\r\n".getBytes(java.nio.charset.StandardCharsets.UTF_8));
out.flush();
} catch (IOException e) {
LOG.debugv(e, "Acceptor socket closed during test teardown");
}
});
responder.setDaemon(true);
responder.start();
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
"container-id", Map.of(8182, new ContainerLifecycleManager.EndpointInfo(
"127.0.0.1", serverSocket.getLocalPort()))));
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(mock(ContainerSpec.class));
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.NeptuneServiceConfig neptune = mock(EmulatorConfig.NeptuneServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.neptune()).thenReturn(neptune);
when(neptune.dockerNetwork()).thenReturn(Optional.empty());
NeptuneContainerManager manager = new NeptuneContainerManager(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), mock(ContainerDetector.class), config,
new RegionResolver("us-east-1", "000000000000"));
manager.start("cluster1", "tinkerpop/gremlin-server:3.7.3", NeptuneDbType.GREMLIN);
verify(builder).withLabels(Map.of(
"io.floci", "aws",
"io.floci.service", "neptune",
"io.floci.resource-id", "cluster1",
"io.floci.account", "000000000000",
"io.floci.region", "us-east-1"));
}
}
private NeptuneContainerManager newManager(ContainerLifecycleManager lifecycleManager) {
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
@@ -0,0 +1,80 @@
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.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.PortAllocator;
import io.github.hectorvent.floci.services.opensearch.model.Domain;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class OpenSearchDomainManagerTest {
@Test
void startDomainLabelsContainerWithResourceIdentity() {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.OpenSearchServiceConfig opensearch = mock(EmulatorConfig.OpenSearchServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.opensearch()).thenReturn(opensearch);
when(services.dockerNetwork()).thenReturn(Optional.empty());
when(opensearch.proxyBasePort()).thenReturn(9400);
when(opensearch.proxyMaxPort()).thenReturn(9499);
when(opensearch.defaultImage()).thenReturn(Optional.of("opensearchproject/opensearch:2.11.0"));
EmulatorConfig.DockerConfig docker = mock(EmulatorConfig.DockerConfig.class);
when(config.docker()).thenReturn(docker);
lenient().when(docker.logMaxSize()).thenReturn("10m");
lenient().when(docker.logMaxFile()).thenReturn("3");
EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);
when(config.storage()).thenReturn(storage);
when(storage.hostPersistentPath()).thenReturn("floci-data");
when(storage.persistentPath()).thenReturn("/data");
PortAllocator portAllocator = mock(PortAllocator.class);
when(portAllocator.allocate(9400, 9499)).thenReturn(9400);
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(
new ContainerLifecycleManager.ContainerInfo("container-id", Map.of()));
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(mock(ContainerSpec.class));
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
OpenSearchDomainManager manager = new OpenSearchDomainManager(containerBuilder, lifecycleManager,
mock(ContainerDetector.class), portAllocator, config, regionResolver);
Domain domain = new Domain();
domain.setDomainName("my-domain");
domain.setEngineVersion("OpenSearch_2.11");
manager.startDomain(domain);
verify(builder).withLabels(Map.of(
"io.floci", "aws",
"io.floci.service", "opensearch",
"io.floci.resource-id", "my-domain",
"io.floci.account", "000000000000",
"io.floci.region", "us-east-1"));
}
}
@@ -147,6 +147,67 @@ class RdsContainerManagerTest {
"log-stream", "us-west-2", "rds:" + runtimeId);
}
@Test
void startLabelsContainerWithResourceIdentityFromRuntimeArn() {
EmulatorConfig config = config(tempDir.resolve("host-root"));
ContainerDetector containerDetector = mock(ContainerDetector.class);
when(containerDetector.isRunningInContainer()).thenReturn(true);
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
stubStarts(lifecycleManager, new ContainerLifecycleManager.ContainerInfo(
"container-id", Map.of(3306, new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
RdsContainerManager manager = new RdsContainerManager(
new ContainerBuilder(config, mock(DockerHostResolver.class),
mock(EmbeddedDnsServer.class)),
lifecycleManager, logStreamer, containerDetector, config,
new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class));
manager.start("arn:aws:rds:us-west-2:222222222222:db:db1", "db1", null,
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db");
var spec = org.mockito.ArgumentCaptor.forClass(ContainerSpec.class);
verify(lifecycleManager).create(spec.capture());
assertEquals(
Map.of("io.floci", "aws",
"io.floci.service", "rds",
"io.floci.resource-id", "db1",
"io.floci.account", "222222222222",
"io.floci.region", "us-west-2"),
spec.getValue().labels());
}
@Test
void startLabelsContainerWithResourceIdentityFallingBackToDefaultAccountAndRegion() {
EmulatorConfig config = config(tempDir.resolve("host-root"));
ContainerDetector containerDetector = mock(ContainerDetector.class);
when(containerDetector.isRunningInContainer()).thenReturn(true);
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
stubStarts(lifecycleManager, new ContainerLifecycleManager.ContainerInfo(
"container-id", Map.of(3306, new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
RdsContainerManager manager = new RdsContainerManager(
new ContainerBuilder(config, mock(DockerHostResolver.class),
mock(EmbeddedDnsServer.class)),
lifecycleManager, logStreamer, containerDetector, config,
new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class));
manager.start("db1", "vol1", DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db");
var spec = org.mockito.ArgumentCaptor.forClass(ContainerSpec.class);
verify(lifecycleManager).create(spec.capture());
assertEquals(
Map.of("io.floci", "aws",
"io.floci.service", "rds",
"io.floci.resource-id", "db1",
"io.floci.account", "000000000000",
"io.floci.region", "us-east-1"),
spec.getValue().labels());
}
@Test
void sameNamedResourcesKeepIndependentActiveContainerEntries() {
EmulatorConfig config = config(tempDir.resolve("host-root"));