mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 14:10:49 -05:00
feat(lambda): add the ability to name and label lambda containers, code volumes (#2409)
This commit is contained in:
1 parent
3f12428d97
commit
f8b07a78ff
10 files changed
+321
-6
No files matched your search
@@ -101,6 +101,45 @@ floci:
|
||||
log-max-file: "3" # Number of rotated log files to retain per container
|
||||
```
|
||||
|
||||
## Container Labels
|
||||
|
||||
Every container and volume Floci creates carries three reserved labels for discovery and cleanup:
|
||||
|
||||
| Label | Value | Purpose |
|
||||
|---|---|---|
|
||||
| `floci` | `true` | Umbrella across all Floci emulators — `docker ps --filter label=floci=true` |
|
||||
| `floci_emulator` | `floci-aws` | Per-emulator discriminator |
|
||||
| `floci_namespace` | *(the configured namespace)* | Only present when `resource-namespace` is set |
|
||||
|
||||
Add your own labels with `extra-labels` — they are applied to every container **and** volume Floci creates (Lambda functions and code volumes, RDS databases, ElastiCache, OpenSearch, MSK, ECS, ...):
|
||||
|
||||
```yaml
|
||||
floci:
|
||||
docker:
|
||||
extra-labels:
|
||||
- key: "com.example.project"
|
||||
value: my-project
|
||||
- key: environment
|
||||
value: dev
|
||||
```
|
||||
|
||||
Or via environment variables (indexed entries, like `registry-credentials`):
|
||||
|
||||
```yaml
|
||||
services:
|
||||
floci:
|
||||
environment:
|
||||
FLOCI_DOCKER_EXTRA_LABELS_0__KEY: "com.example.project"
|
||||
FLOCI_DOCKER_EXTRA_LABELS_0__VALUE: my-project
|
||||
FLOCI_DOCKER_EXTRA_LABELS_1__KEY: environment
|
||||
FLOCI_DOCKER_EXTRA_LABELS_1__VALUE: dev
|
||||
```
|
||||
|
||||
Extra labels are a list of key/value entries rather than a map so that label keys containing dots, colons, or uppercase characters survive the environment-variable naming convention.
|
||||
|
||||
!!! 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.
|
||||
|
||||
## 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.
|
||||
@@ -184,4 +223,7 @@ What each setting does and why it is needed:
|
||||
| `FLOCI_DOCKER_REGISTRY_CREDENTIALS_0__PASSWORD` | _(unset)_ | Password for credential entry 0 |
|
||||
| `FLOCI_DOCKER_LOG_MAX_SIZE` | `10m` | Max container log file size before rotation |
|
||||
| `FLOCI_DOCKER_LOG_MAX_FILE` | `3` | Number of rotated log files to retain |
|
||||
| `FLOCI_DOCKER_EXTRA_LABELS_0__KEY` | _(unset)_ | Label key for extra-label entry 0, applied to every Floci-created container and volume (increment the index for more) |
|
||||
| `FLOCI_DOCKER_EXTRA_LABELS_0__VALUE` | _(unset)_ | Label value for extra-label entry 0 |
|
||||
| `FLOCI_SERVICES_DOCKER_NETWORK` | _(unset)_ | Shared Docker network for all container-based services |
|
||||
| `FLOCI_SERVICES_LAMBDA_CONTAINER_NAME_PREFIX` | `floci` | Base name prefix for spawned Lambda containers and code volumes (e.g. `acme` → `acme-<function>-<id>` containers, `acme-code-<function>-<hash>` volumes). Must be a valid Docker name segment (`[A-Za-z0-9][A-Za-z0-9_.-]*`); invalid values are ignored with a warning. See the [Lambda docs](../services/lambda.md#configuration) |
|
||||
@@ -94,6 +94,8 @@ See [Storage Modes](./storage.md) for a full explanation of each mode.
|
||||
| `FLOCI_DOCKER_LOG_MAX_SIZE` | `10m` | Log rotation max size for spawned containers (e.g. `10m`, `1g`) |
|
||||
| `FLOCI_DOCKER_LOG_MAX_FILE` | `3` | Number of rotated log files to keep for spawned containers |
|
||||
| `FLOCI_DOCKER_RESOURCE_NAMESPACE` | _(none)_ | Optional namespace prefix for managed child Docker container and volume names |
|
||||
| `FLOCI_DOCKER_EXTRA_LABELS_0__KEY` | _(none)_ | Label key for extra-label entry 0, applied to every Floci-created container and volume (increment the index for more) |
|
||||
| `FLOCI_DOCKER_EXTRA_LABELS_0__VALUE` | _(none)_ | Label value for extra-label entry 0 |
|
||||
|
||||
### Registry credentials
|
||||
|
||||
@@ -197,6 +199,7 @@ See [Initialization Hooks](./initialization-hooks.md) for lifecycle phases and s
|
||||
| `FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ENABLED` | `false` | Watch Lambda code directories for changes and reload without redeployment |
|
||||
| `FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ALLOWED_PATHS` | _(none)_ | Comma-separated host paths that hot-reload is allowed to watch |
|
||||
| `FLOCI_SERVICES_LAMBDA_DOCKER_NETWORK` | _(none)_ | Docker network for Lambda containers (overrides `FLOCI_SERVICES_DOCKER_NETWORK`) |
|
||||
| `FLOCI_SERVICES_LAMBDA_CONTAINER_NAME_PREFIX` | `floci` | Base name prefix for Lambda-spawned containers and code volumes (must match `[A-Za-z0-9][A-Za-z0-9_.-]*`) |
|
||||
| `FLOCI_SERVICES_LAMBDA_DOCKER_HOST_OVERRIDE` | _(none)_ | Explicit host/IP Lambda containers use to reach the Runtime API, bypassing auto-detection (e.g. rootless Podman) |
|
||||
| `FLOCI_SERVICES_LAMBDA_AWS_CONFIG_PATH` | _(none)_ | Host path bind-mounted read-only at `/opt/aws-config` inside Lambda containers for real credential discovery |
|
||||
|
||||
|
||||
@@ -205,6 +205,20 @@ These AWS Lambda operations have no handler in Floci. Calls will return `404` or
|
||||
| `FLOCI_SERVICES_LAMBDA_DOCKER_NETWORK` | *(unset)* | Docker network to attach Lambda containers to (overrides `FLOCI_SERVICES_DOCKER_NETWORK`) |
|
||||
| `FLOCI_SERVICES_LAMBDA_EXTRA_HOSTS` | *(unset)* | Comma-separated `hostname:ip` entries added to each Lambda container's `/etc/hosts`; `ip` may be `host-gateway`, mirroring `docker run --add-host` |
|
||||
| `FLOCI_SERVICES_LAMBDA_DOCKER_HOST_OVERRIDE` | *(unset)* | Explicit host/IP that spawned Lambda containers use to reach Floci's Runtime API, bypassing auto-detection |
|
||||
| `FLOCI_SERVICES_LAMBDA_CONTAINER_NAME_PREFIX` | `floci` | Base name prefix for spawned Lambda containers and code volumes (e.g. `acme` → `acme-<function>-<id>` containers, `acme-code-<function>-<hash>` volumes). Must be a valid Docker name segment (`[A-Za-z0-9][A-Za-z0-9_.-]*`); invalid values are ignored with a warning |
|
||||
|
||||
!!! note "Changing the container name prefix"
|
||||
Code volumes are resolved by name, and a Floci process only manages resources under its
|
||||
own prefix — deliberately, so multiple Floci processes with different prefixes can share
|
||||
one Docker daemon without touching each other's containers and volumes. Restarting with a
|
||||
different `container-name-prefix` therefore strands the code volumes (and their completion
|
||||
markers) created under the previous prefix: they are no longer reused and no longer part of
|
||||
automatic superseded-volume cleanup. They keep the prefix-independent `floci=true` label,
|
||||
so reclaim them at any time with:
|
||||
|
||||
```bash
|
||||
docker volume prune --filter label=floci=true
|
||||
```
|
||||
|
||||
### Runtime API host override
|
||||
|
||||
|
||||
@@ -1513,6 +1513,17 @@ public interface EmulatorConfig {
|
||||
/** Docker network to attach Lambda containers to. Empty = default bridge. */
|
||||
Optional<String> dockerNetwork();
|
||||
|
||||
/**
|
||||
* Base name prefix for the containers and code volumes Lambda spawns, replacing the
|
||||
* default {@code floci} (e.g. prefix {@code acme} names containers
|
||||
* {@code acme-<function>-<id>} and code volumes {@code acme-code-<function>-<hash>}).
|
||||
* Must be a valid Docker name segment ({@code [A-Za-z0-9][A-Za-z0-9_.-]*}); invalid
|
||||
* values are ignored with a warning. Unset or blank falls back to {@code floci}.
|
||||
*
|
||||
* Env var: FLOCI_SERVICES_LAMBDA_CONTAINER_NAME_PREFIX
|
||||
*/
|
||||
Optional<String> containerNamePrefix();
|
||||
|
||||
/**
|
||||
* Extra /etc/hosts entries added to every Lambda container, as "hostname:ip" pairs.
|
||||
* The ip may be the literal "host-gateway" to map to the Docker host, mirroring
|
||||
@@ -1917,5 +1928,22 @@ public interface EmulatorConfig {
|
||||
String username();
|
||||
String password();
|
||||
}
|
||||
|
||||
/**
|
||||
* Extra Docker labels applied to every container and volume Floci creates,
|
||||
* alongside the reserved {@code floci}, {@code floci_emulator} and
|
||||
* {@code floci_namespace} labels (entries using a reserved key are ignored).
|
||||
* A list of key/value entries rather than a {@code Map} so label keys with
|
||||
* characters outside SmallRye's env-var naming convention (dots, colons,
|
||||
* mixed case) survive:
|
||||
* {@code FLOCI_DOCKER_EXTRA_LABELS_0__KEY} / {@code FLOCI_DOCKER_EXTRA_LABELS_0__VALUE}.
|
||||
*/
|
||||
@WithDefault("")
|
||||
List<LabelEntry> extraLabels();
|
||||
|
||||
interface LabelEntry {
|
||||
String key();
|
||||
String value();
|
||||
}
|
||||
}
|
||||
}
|
||||
+36
@@ -52,14 +52,50 @@ public final class ContainerStorageHelper {
|
||||
return "floci-" + namespace + "-" + baseName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Like {@link #dockerName} but with a caller-supplied base prefix in place of the default
|
||||
* {@code floci}: {@code <prefix>-<rest>}, or {@code <prefix>-<namespace>-<rest>} when a
|
||||
* resource namespace is configured.
|
||||
*/
|
||||
public static String prefixedDockerName(EmulatorConfig config, String prefix, String rest) {
|
||||
String namespace = resourceNamespace(config);
|
||||
if (namespace.isBlank()) {
|
||||
return prefix + "-" + rest;
|
||||
}
|
||||
return prefix + "-" + namespace + "-" + rest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Label keys reserved for the emulator itself. {@code floci} and {@code floci_emulator}
|
||||
* drive container/volume discovery and pruning (e.g.
|
||||
* {@code docker volume prune --filter label=floci=true}); {@code floci_namespace} scopes
|
||||
* resources when multiple Floci processes share one daemon. Extra labels using these keys
|
||||
* are ignored so user configuration can never break cleanup.
|
||||
*/
|
||||
private static final java.util.Set<String> RESERVED_LABEL_KEYS =
|
||||
java.util.Set.of("floci", "floci_emulator", "floci_namespace");
|
||||
|
||||
/**
|
||||
* Labels applied to every emulator-created container and volume:
|
||||
* {@code floci=true} (umbrella across all Floci emulators),
|
||||
* {@code floci_emulator=floci-aws} (per-emulator discriminator), and
|
||||
* {@code floci_namespace} when a resource namespace is configured.
|
||||
* User-configured {@code floci.docker.extra-labels} entries are included first;
|
||||
* reserved keys always win on conflict.
|
||||
*/
|
||||
public static Map<String, String> defaultLabels(EmulatorConfig config) {
|
||||
Map<String, String> labels = new LinkedHashMap<>();
|
||||
if (config != null && config.docker() != null && config.docker().extraLabels() != null) {
|
||||
for (EmulatorConfig.DockerConfig.LabelEntry entry : config.docker().extraLabels()) {
|
||||
String key = entry.key() == null ? "" : entry.key().trim();
|
||||
if (key.isEmpty() || RESERVED_LABEL_KEYS.contains(key)) {
|
||||
LOG.warnv("Ignoring extra Docker label with {0} key: \"{1}\"",
|
||||
key.isEmpty() ? "blank" : "reserved", key);
|
||||
continue;
|
||||
}
|
||||
labels.put(key, entry.value() == null ? "" : entry.value());
|
||||
}
|
||||
}
|
||||
labels.put("floci", "true");
|
||||
labels.put("floci_emulator", "floci-" + CLOUD);
|
||||
String namespace = resourceNamespace(config);
|
||||
|
||||
+42
-6
@@ -68,6 +68,32 @@ public class ContainerLauncher {
|
||||
private static final String TASK_DIR = "/var/task";
|
||||
private static final String RUNTIME_DIR = "/var/runtime";
|
||||
|
||||
/** Default base prefix for the containers and code volumes Lambda spawns. */
|
||||
static final String DEFAULT_NAME_PREFIX = "floci";
|
||||
/** A prefix must be a legal Docker name on its own: names must start alphanumeric. */
|
||||
private static final java.util.regex.Pattern SAFE_NAME_PREFIX =
|
||||
java.util.regex.Pattern.compile("^[A-Za-z0-9][A-Za-z0-9_.-]*$");
|
||||
|
||||
/**
|
||||
* The base name prefix for Lambda containers and code volumes:
|
||||
* {@code floci.services.lambda.container-name-prefix} when set and Docker-safe,
|
||||
* otherwise the default {@code floci}.
|
||||
*/
|
||||
static String resolveContainerNamePrefix(EmulatorConfig config) {
|
||||
String configured = config.services().lambda().containerNamePrefix()
|
||||
.map(String::trim).orElse("");
|
||||
if (configured.isEmpty()) {
|
||||
return DEFAULT_NAME_PREFIX;
|
||||
}
|
||||
if (!SAFE_NAME_PREFIX.matcher(configured).matches()) {
|
||||
LOG.warnv("Ignoring floci.services.lambda.container-name-prefix \"{0}\": not a valid "
|
||||
+ "Docker name prefix ([A-Za-z0-9][A-Za-z0-9_.-]*); using \"{1}\"",
|
||||
configured, DEFAULT_NAME_PREFIX);
|
||||
return DEFAULT_NAME_PREFIX;
|
||||
}
|
||||
return configured;
|
||||
}
|
||||
|
||||
/**
|
||||
* In-container location of Floci's CA certificate, injected when TLS is enabled so the
|
||||
* container trusts Floci's self-signed HTTPS endpoint. {@code /etc} exists in every Lambda
|
||||
@@ -214,7 +240,8 @@ public class ContainerLauncher {
|
||||
|
||||
// Give the container a human-readable name (needed for log stream name below)
|
||||
String shortId = java.util.UUID.randomUUID().toString().replace("-", "").substring(0, 8);
|
||||
String containerName = ContainerStorageHelper.dockerName(config, "floci-" + fn.getFunctionName() + "-" + shortId);
|
||||
String containerName = ContainerStorageHelper.prefixedDockerName(config,
|
||||
resolveContainerNamePrefix(config), fn.getFunctionName() + "-" + shortId);
|
||||
|
||||
// CloudWatch log coordinates — computed here so they can be injected as env vars
|
||||
String cwLogGroup = "/aws/lambda/" + fn.getFunctionName();
|
||||
@@ -583,7 +610,6 @@ public class ContainerLauncher {
|
||||
// nothing under that name, silently mounting an empty /var/task into the next container.
|
||||
// ensureCodeVolume re-checks lifecycleManager.volumeExists() rather than trusting this alone.
|
||||
private static final String CODE_VOLUME_MARKER_DIR = "lambda-codevol-markers";
|
||||
private static final String CODE_VOLUME_MARKER_PREFIX = "floci-code-";
|
||||
private final java.util.Set<String> populatedCodeVolumes = java.util.concurrent.ConcurrentHashMap.newKeySet();
|
||||
// Deliberately never pruned: removing an entry while a caller elsewhere still held a reference
|
||||
// to its lock object let a third caller's computeIfAbsent create a replacement lock for the same
|
||||
@@ -652,7 +678,7 @@ public class ContainerLauncher {
|
||||
* just mounts the volume read-only, turning a ~95s per-container copy into a ~0.2s mount.
|
||||
*/
|
||||
String ensureCodeVolume(LambdaFunction fn, String image) {
|
||||
String volName = codeVolumeName(fn);
|
||||
String volName = codeVolumeName(resolveContainerNamePrefix(config), fn);
|
||||
// Held for the whole resolve-and-reconcile, not just the populate branch: this is the same
|
||||
// lock cleanupSupersededVolumes acquires before claiming a volume for deletion, so a launch
|
||||
// that resolves a volume can never race a sweep that's about to delete that exact volume out
|
||||
@@ -805,7 +831,7 @@ public class ContainerLauncher {
|
||||
// A minimal helper container (sleep) with the volume mounted read-write at /var/task; we
|
||||
// tar-copy the code into it, then discard it — the data persists in the volume.
|
||||
ContainerSpec helperSpec = containerBuilder.newContainer(image)
|
||||
.withName("floci-codevol-" + fn.getFunctionName() + "-" + shortId)
|
||||
.withName(resolveContainerNamePrefix(config) + "-codevol-" + fn.getFunctionName() + "-" + shortId)
|
||||
.withEnv(java.util.List.of())
|
||||
.withEntrypoint(java.util.List.of("sleep"))
|
||||
.withCmd(java.util.List.of("3600"))
|
||||
@@ -907,9 +933,14 @@ public class ContainerLauncher {
|
||||
if (volumeNames.isEmpty() || !Files.isDirectory(markerDir)) {
|
||||
return;
|
||||
}
|
||||
// Markers are named after their volume, so the prune filter must track the configured
|
||||
// name prefix. Markers written under a previously configured prefix are left alone —
|
||||
// an orphaned marker file is harmless, and pruning only what this configuration could
|
||||
// have written can never delete a concurrent process's live markers.
|
||||
String markerPrefix = resolveContainerNamePrefix(config) + "-code-";
|
||||
try (java.util.stream.Stream<Path> markers = Files.list(markerDir)) {
|
||||
markers.filter(path -> Files.isRegularFile(path, java.nio.file.LinkOption.NOFOLLOW_LINKS))
|
||||
.filter(path -> path.getFileName().toString().startsWith(CODE_VOLUME_MARKER_PREFIX))
|
||||
.filter(path -> path.getFileName().toString().startsWith(markerPrefix))
|
||||
.filter(path -> !volumeNames.get().contains(path.getFileName().toString()))
|
||||
.forEach(path -> {
|
||||
try {
|
||||
@@ -966,6 +997,11 @@ public class ContainerLauncher {
|
||||
* Prefers the code SHA-256; falls back to last-modified when the SHA is unavailable.
|
||||
*/
|
||||
static String codeVolumeName(LambdaFunction fn) {
|
||||
return codeVolumeName(DEFAULT_NAME_PREFIX, fn);
|
||||
}
|
||||
|
||||
/** {@link #codeVolumeName(LambdaFunction)} with a configured base prefix in place of {@code floci}. */
|
||||
static String codeVolumeName(String namePrefix, LambdaFunction fn) {
|
||||
String key = fn.getCodeSha256();
|
||||
if (key == null || key.isBlank()) {
|
||||
key = Long.toString(fn.getLastModified());
|
||||
@@ -978,7 +1014,7 @@ public class ContainerLauncher {
|
||||
h = "0";
|
||||
}
|
||||
String fname = fn.getFunctionName().replaceAll("[^a-zA-Z0-9_.-]", "-");
|
||||
return "floci-code-" + fname + "-" + h;
|
||||
return namePrefix + "-code-" + fname + "-" + h;
|
||||
}
|
||||
|
||||
static String efsVolumeName(String accessPointArn) {
|
||||
|
||||
@@ -197,6 +197,11 @@ floci:
|
||||
docker-host: unix:///var/run/docker.sock
|
||||
resource-namespace: "" # FLOCI_DOCKER_RESOURCE_NAMESPACE; scopes child container/volume names
|
||||
docker-config-path: ""
|
||||
# extra-labels: # Extra Docker labels applied to every Floci-created container and volume
|
||||
# - key: "com.example.project" # (FLOCI_DOCKER_EXTRA_LABELS_0__KEY / _0__VALUE; increment the index for more;
|
||||
# value: my-project # reserved keys floci, floci_emulator, floci_namespace are ignored)
|
||||
# - key: environment
|
||||
# value: dev
|
||||
|
||||
services:
|
||||
ssm:
|
||||
@@ -229,6 +234,7 @@ floci:
|
||||
unreserved-concurrency-min: 100
|
||||
# aws-config-path: # Host path to bind-mount (read-only) at /opt/aws-config for real credential discovery
|
||||
# extra-hosts: # Extra /etc/hosts entries for Lambda containers, "hostname:ip" ("host-gateway" allowed as ip)
|
||||
# container-name-prefix: floci # FLOCI_SERVICES_LAMBDA_CONTAINER_NAME_PREFIX — base name prefix for spawned containers and code volumes ([A-Za-z0-9][A-Za-z0-9_.-]*; invalid values fall back to "floci")
|
||||
hot-reload:
|
||||
enabled: false
|
||||
apigateway:
|
||||
|
||||
+73
@@ -62,13 +62,86 @@ class ContainerStorageHelperTest {
|
||||
ContainerStorageHelper.defaultLabels(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void prefixedDockerNameSwapsTheBasePrefix() {
|
||||
assertEquals("acme-my-fn-abc123",
|
||||
ContainerStorageHelper.prefixedDockerName(config(""), "acme", "my-fn-abc123"));
|
||||
assertEquals("acme-run-one-my-fn-abc123",
|
||||
ContainerStorageHelper.prefixedDockerName(config(" run/one "), "acme", "my-fn-abc123"));
|
||||
// The default prefix through this path matches what dockerName produces.
|
||||
assertEquals(ContainerStorageHelper.dockerName(config("run-one"), "floci-my-fn-abc123"),
|
||||
ContainerStorageHelper.prefixedDockerName(config("run-one"), "floci", "my-fn-abc123"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extraLabelsAreMergedIntoDefaultLabels() {
|
||||
// A dotted key — exactly the shape that motivates list-of-entries config over a Map,
|
||||
// whose env-var naming convention cannot express such keys.
|
||||
EmulatorConfig config = config("", java.util.List.of(
|
||||
label("com.example.project", "my-project"),
|
||||
label("environment", "dev")));
|
||||
|
||||
assertEquals(
|
||||
Map.of("floci", "true", "floci_emulator", "floci-aws",
|
||||
"com.example.project", "my-project", "environment", "dev"),
|
||||
ContainerStorageHelper.defaultLabels(config));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extraLabelsCannotOverrideReservedKeys() {
|
||||
// The reserved labels drive container/volume discovery and pruning; a user label must
|
||||
// never be able to break `docker volume prune --filter label=floci=true` cleanup.
|
||||
EmulatorConfig config = config(" run/one ", java.util.List.of(
|
||||
label("floci", "false"),
|
||||
label("floci_emulator", "spoofed"),
|
||||
label("floci_namespace", "spoofed"),
|
||||
label("kept", "yes")));
|
||||
|
||||
assertEquals(
|
||||
Map.of("floci", "true", "floci_emulator", "floci-aws",
|
||||
"floci_namespace", "run-one", "kept", "yes"),
|
||||
ContainerStorageHelper.defaultLabels(config));
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankExtraLabelKeysAreIgnored() {
|
||||
EmulatorConfig config = config("", java.util.List.of(
|
||||
label(" ", "dropped"),
|
||||
label(null, "dropped"),
|
||||
label("kept", null)));
|
||||
|
||||
assertEquals(
|
||||
Map.of("floci", "true", "floci_emulator", "floci-aws", "kept", ""),
|
||||
ContainerStorageHelper.defaultLabels(config));
|
||||
}
|
||||
|
||||
private static EmulatorConfig.DockerConfig.LabelEntry label(String key, String value) {
|
||||
return new EmulatorConfig.DockerConfig.LabelEntry() {
|
||||
@Override
|
||||
public String key() {
|
||||
return key;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String value() {
|
||||
return value;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static EmulatorConfig config(String namespace) {
|
||||
return config(namespace, java.util.List.of());
|
||||
}
|
||||
|
||||
private static EmulatorConfig config(
|
||||
String namespace, java.util.List<EmulatorConfig.DockerConfig.LabelEntry> extraLabels) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.DockerConfig docker = mock(EmulatorConfig.DockerConfig.class);
|
||||
EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);
|
||||
when(config.docker()).thenReturn(docker);
|
||||
when(config.storage()).thenReturn(storage);
|
||||
when(docker.resourceNamespace()).thenReturn(namespace.isBlank() ? Optional.empty() : Optional.of(namespace));
|
||||
when(docker.extraLabels()).thenReturn(extraLabels);
|
||||
when(storage.hostPersistentPath()).thenReturn("/tmp/floci");
|
||||
return config;
|
||||
}
|
||||
|
||||
+6
@@ -77,8 +77,14 @@ class ContainerLauncherCodeVolumeReuseTest {
|
||||
lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.LambdaServiceConfig lambda = mock(EmulatorConfig.LambdaServiceConfig.class);
|
||||
when(config.storage()).thenReturn(storage);
|
||||
when(storage.persistentPath()).thenReturn(tempDir.toString());
|
||||
// ensureCodeVolume resolves the configured container-name prefix (unset = "floci").
|
||||
when(config.services()).thenReturn(services);
|
||||
when(services.lambda()).thenReturn(lambda);
|
||||
when(lambda.containerNamePrefix()).thenReturn(Optional.empty());
|
||||
launcher = new RecordingLauncher(lifecycleManager, config);
|
||||
}
|
||||
|
||||
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package io.github.hectorvent.floci.services.lambda.launcher;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Tests for the configurable Lambda container/code-volume name prefix
|
||||
* ({@code floci.services.lambda.container-name-prefix}). Plain {@code mock()} rather than the
|
||||
* Mockito extension, for the same strict-stubbing reason as
|
||||
* {@link ContainerLauncherVolumeNamingTest}.
|
||||
*/
|
||||
class ContainerLauncherNamePrefixTest {
|
||||
|
||||
private static final Pattern DOCKER_NAME = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9_.-]*$");
|
||||
|
||||
@Test
|
||||
void fallsBackToFlociWhenPrefixUnsetOrBlank() {
|
||||
assertEquals("floci", ContainerLauncher.resolveContainerNamePrefix(config(null)));
|
||||
assertEquals("floci", ContainerLauncher.resolveContainerNamePrefix(config(" ")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void usesConfiguredPrefixWhenDockerSafe() {
|
||||
assertEquals("acme", ContainerLauncher.resolveContainerNamePrefix(config("acme")));
|
||||
assertEquals("acme_v1.0", ContainerLauncher.resolveContainerNamePrefix(config(" acme_v1.0 ")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackToFlociWhenPrefixIsNotDockerSafe() {
|
||||
// Docker names must start alphanumeric and allow only [A-Za-z0-9_.-] after that.
|
||||
assertEquals("floci", ContainerLauncher.resolveContainerNamePrefix(config("-leading-dash")));
|
||||
assertEquals("floci", ContainerLauncher.resolveContainerNamePrefix(config("has space")));
|
||||
assertEquals("floci", ContainerLauncher.resolveContainerNamePrefix(config("has:colon")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void codeVolumeNameHonorsConfiguredPrefix() {
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setFunctionName("my-fn");
|
||||
fn.setCodeSha256("abc123def456");
|
||||
|
||||
String name = ContainerLauncher.codeVolumeName("acme", fn);
|
||||
|
||||
assertTrue(name.startsWith("acme-code-my-fn-"),
|
||||
"should be <prefix>-code-<functionName>-<hash> shaped, was: " + name);
|
||||
assertTrue(DOCKER_NAME.matcher(name).matches(),
|
||||
"must be a docker-volume-safe name, was: " + name);
|
||||
// The one-arg overload stays on the default prefix (used by pre-existing callers/tests).
|
||||
assertEquals(ContainerLauncher.codeVolumeName(fn),
|
||||
ContainerLauncher.codeVolumeName("floci", fn));
|
||||
}
|
||||
|
||||
private static EmulatorConfig config(String prefix) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.LambdaServiceConfig lambda = mock(EmulatorConfig.LambdaServiceConfig.class);
|
||||
when(config.services()).thenReturn(services);
|
||||
when(services.lambda()).thenReturn(lambda);
|
||||
when(lambda.containerNamePrefix()).thenReturn(Optional.ofNullable(prefix));
|
||||
return config;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user