mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(lambda): include the resource namespace in code volume names (#4872)
* fix(lambda): include the resource namespace in code volume names Code volumes, their completion markers and the populate helper container are named through prefixedDockerName, so FLOCI_DOCKER_RESOURCE_NAMESPACE follows the container name prefix as it already does for Lambda containers. Two namespaced instances on one daemon no longer share a code volume, and one's superseded-volume cleanup can no longer remove the other's. Names are unchanged without a namespace. * fix(lambda): keep two resource namespaces from sharing a code volume Greptile and pgermosen on #4872: a namespace and a function name may both contain dashes, so namespace ci with function foo-code-bar and namespace ci-code-foo with function bar spelled the same volume name for the same code, and the superseded sweep, which works from a per-process map of names, could remove the other instance's volume. A namespaced code volume name now ends with a short hash of the namespace (names without a namespace are unchanged), and the sweep checks the volume's floci_namespace label before deleting, so a volume of another namespace is left alone however its name parses. Also imports the Mockito types in ContainerLauncherCodeVolumeReuseTest instead of qualifying them inline.
This commit is contained in:
1 parent
24c655050f
commit
2170c89d88
7 files changed
+278
-12
No files matched your search
@@ -301,4 +301,4 @@ What each setting does and why it is needed:
|
||||
| `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) |
|
||||
| `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; with `FLOCI_DOCKER_RESOURCE_NAMESPACE` set, the namespace follows the prefix and a short hash of it ends the volume name, e.g. `acme-<namespace>-code-<function>-<hash>-<namespace hash>`). 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) |
|
||||
@@ -383,7 +383,7 @@ These AWS Lambda operations have no handler in Floci. Calls will return `404` or
|
||||
| `FLOCI_SERVICES_LAMBDA_DOCKER_FLAGS` | *(unset)* | Additional Docker flags applied to Lambda containers, including `--env`, `--volume`, `--publish`, `--add-host`, `--dns`, `--label`, `--network`, `--user`, `--privileged`, and `--platform`. Published ports support `host:container` and `127.0.0.1:host:container` forms |
|
||||
| `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 |
|
||||
| `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; with `FLOCI_DOCKER_RESOURCE_NAMESPACE` set, the namespace follows the prefix and a short hash of it ends the volume name, e.g. `acme-<namespace>-code-<function>-<hash>-<namespace hash>`). Must be a valid Docker name segment (`[A-Za-z0-9][A-Za-z0-9_.-]*`); invalid values are ignored with a warning |
|
||||
| `FLOCI_SERVICES_LAMBDA_CODE_VOLUME_POPULATE_CONCURRENCY` | `max(2, cpus/2)` | Maximum concurrent first-time code-volume populates. See the note below |
|
||||
| `FLOCI_SERVICES_LAMBDA_EXECUTOR` | `docker` | Execution backend: `docker` (containers) or `kubernetes` (pods) |
|
||||
| `FLOCI_SERVICES_LAMBDA_KUBERNETES_NAMESPACE` | `default` | Namespace Lambda pods are created in |
|
||||
|
||||
+17
@@ -939,6 +939,23 @@ public class ContainerLifecycleManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The labels on a named volume, or empty when it does not exist or the runtime cannot be
|
||||
* queried, so a caller deciding whether a volume is its own can fail closed.
|
||||
*/
|
||||
public Optional<Map<String, String>> tryVolumeLabels(String name) {
|
||||
try {
|
||||
Map<String, String> labels = dockerClient.inspectVolumeCmd(name).exec().getLabels();
|
||||
return Optional.of(labels == null ? Map.of() : labels);
|
||||
} catch (NotFoundException e) {
|
||||
LOG.debugv("Volume ''{0}'' not found while reading its labels", name);
|
||||
return Optional.empty();
|
||||
} catch (DockerException e) {
|
||||
LOG.warnv("Failed to read labels of volume ''{0}'': {1}", name, e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to take an authoritative snapshot of all named volumes in the container runtime.
|
||||
* An empty optional means the runtime could not be queried; it is intentionally distinct from
|
||||
|
||||
+60
-7
@@ -48,6 +48,7 @@ import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
@@ -730,6 +731,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
// 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 NAMESPACE_LABEL = "floci_namespace";
|
||||
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
|
||||
@@ -798,7 +800,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
* 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(resolveContainerNamePrefix(config), fn);
|
||||
String volName = codeVolumeName(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
|
||||
@@ -873,6 +875,19 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
volumesInFlight.computeIfPresent(volName, (k, count) -> count.decrementAndGet() > 0 ? count : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a code volume carries this process's {@code floci_namespace} label (none when no
|
||||
* namespace is set). The superseded sweep works from this process's own map of names, so it
|
||||
* checks the label before deleting rather than trusting that a name it tracked is still its
|
||||
* own. A volume whose labels cannot be read is left to {@code removeVolume}'s own checks.
|
||||
*/
|
||||
private boolean inThisResourceNamespace(String volName) {
|
||||
return lifecycleManager.tryVolumeLabels(volName)
|
||||
.map(labels -> Objects.equals(labels.get(NAMESPACE_LABEL),
|
||||
ContainerStorageHelper.defaultLabels(config).get(NAMESPACE_LABEL)))
|
||||
.orElse(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes superseded code volumes whose grace period has elapsed. Scheduled at the same
|
||||
* interval as the grace period itself, so a volume is deleted within roughly one to two
|
||||
@@ -909,6 +924,11 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
continue;
|
||||
}
|
||||
volumesPendingCleanup.remove(volName, stillQueuedAt);
|
||||
if (!inThisResourceNamespace(volName)) {
|
||||
LOG.debugv("Left superseded code volume {0} alone: it belongs to another resource namespace",
|
||||
volName);
|
||||
continue;
|
||||
}
|
||||
if (lifecycleManager.removeVolume(volName)) {
|
||||
populatedCodeVolumes.remove(volName);
|
||||
LOG.debugv("Removed superseded code volume {0}", volName);
|
||||
@@ -951,7 +971,8 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
// 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.
|
||||
ContainerBuilder.Builder helperBuilder = containerBuilder.newContainer(image)
|
||||
.withName(resolveContainerNamePrefix(config) + "-codevol-" + fn.getFunctionName() + "-" + shortId)
|
||||
.withName(ContainerStorageHelper.prefixedDockerName(config, resolveContainerNamePrefix(config),
|
||||
"codevol-" + fn.getFunctionName() + "-" + shortId))
|
||||
.withEnv(java.util.List.of())
|
||||
.withEntrypoint(java.util.List.of("sleep"))
|
||||
.withCmd(java.util.List.of("3600"))
|
||||
@@ -1054,10 +1075,11 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
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-";
|
||||
// name prefix and resource namespace. Markers written under a previously configured
|
||||
// prefix or namespace 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 = codeVolumeNamePrefix(config);
|
||||
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(markerPrefix))
|
||||
@@ -1122,6 +1144,37 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
|
||||
/** {@link #codeVolumeName(LambdaFunction)} with a configured base prefix in place of {@code floci}. */
|
||||
static String codeVolumeName(String namePrefix, LambdaFunction fn) {
|
||||
return namePrefix + "-code-" + codeVolumeSuffix(fn);
|
||||
}
|
||||
|
||||
/**
|
||||
* The code volume name this configuration uses: the configured base prefix plus the resource
|
||||
* namespace when one is set ({@code <prefix>-<namespace>-code-<function>-<hash>-<namespace hash>}),
|
||||
* matching the Lambda container names. Without a namespace it equals
|
||||
* {@link #codeVolumeName(String, LambdaFunction)} with the resolved prefix.
|
||||
*/
|
||||
static String codeVolumeName(EmulatorConfig config, LambdaFunction fn) {
|
||||
return codeVolumeNamePrefix(config) + codeVolumeSuffix(fn) + namespaceDisambiguator(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* A namespace and a function name may both contain dashes, so namespace {@code ci} with function
|
||||
* {@code foo-code-bar} and namespace {@code ci-code-foo} with function {@code bar} would spell
|
||||
* the same volume name for the same code. A short hash of the namespace keeps their volumes
|
||||
* apart. Empty without a namespace, so those names are unchanged.
|
||||
*/
|
||||
private static String namespaceDisambiguator(EmulatorConfig config) {
|
||||
String namespace = config.docker() == null || config.docker().resourceNamespace() == null
|
||||
? "" : config.docker().resourceNamespace().orElse("").trim();
|
||||
return namespace.isEmpty() ? "" : "-" + sha256Hex(namespace).substring(0, 12);
|
||||
}
|
||||
|
||||
/** Leading part shared by every code volume (and completion marker) this configuration names. */
|
||||
static String codeVolumeNamePrefix(EmulatorConfig config) {
|
||||
return ContainerStorageHelper.prefixedDockerName(config, resolveContainerNamePrefix(config), "code-");
|
||||
}
|
||||
|
||||
private static String codeVolumeSuffix(LambdaFunction fn) {
|
||||
String key = fn.getCodeSha256();
|
||||
if (key == null || key.isBlank()) {
|
||||
key = Long.toString(fn.getLastModified());
|
||||
@@ -1134,7 +1187,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
h = "0";
|
||||
}
|
||||
String fname = fn.getFunctionName().replaceAll("[^a-zA-Z0-9_.-]", "-");
|
||||
return namePrefix + "-code-" + fname + "-" + h;
|
||||
return fname + "-" + h;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+75
-3
@@ -15,6 +15,8 @@ import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServerFactor
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.Answers;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
@@ -28,7 +30,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
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.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
@@ -75,6 +80,11 @@ class ContainerLauncherCodeVolumeReuseTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
launcher = new RecordingLauncher(lifecycleManager, config(null));
|
||||
}
|
||||
|
||||
/** Config with the container-name prefix unset and an optional resource namespace. */
|
||||
private EmulatorConfig config(String namespace) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
@@ -85,7 +95,12 @@ class ContainerLauncherCodeVolumeReuseTest {
|
||||
when(config.services()).thenReturn(services);
|
||||
when(services.lambda()).thenReturn(lambda);
|
||||
when(lambda.containerNamePrefix()).thenReturn(Optional.empty());
|
||||
launcher = new RecordingLauncher(lifecycleManager, config);
|
||||
if (namespace != null) {
|
||||
EmulatorConfig.DockerConfig docker = mock(EmulatorConfig.DockerConfig.class);
|
||||
when(config.docker()).thenReturn(docker);
|
||||
when(docker.resourceNamespace()).thenReturn(Optional.of(namespace));
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
private static LambdaFunction fn(String sha) {
|
||||
@@ -219,6 +234,63 @@ class ContainerLauncherCodeVolumeReuseTest {
|
||||
"marker cleanup must not delete files outside Floci's code-volume namespace");
|
||||
}
|
||||
|
||||
@Test
|
||||
void namespacedPopulationUsesNamespacedVolumeAndPrunesOnlyItsOwnMarkers() throws Exception {
|
||||
EmulatorConfig config = config("ci1");
|
||||
launcher = new RecordingLauncher(lifecycleManager, config);
|
||||
LambdaFunction fn = fn("sha-v1-abcdef0123456789");
|
||||
String vol = ContainerLauncher.codeVolumeName(config, fn);
|
||||
assertEquals("floci-aws-ci1-code-orders-shav1abcdef012345678-490320b73797", vol);
|
||||
String orphan = "floci-aws-ci1-code-orphan";
|
||||
String otherNamespace = "floci-aws-ci2-code-orders-shav1abcdef012345678-becd7a27094d";
|
||||
String unnamespaced = "floci-aws-code-orders-shav1abcdef012345678";
|
||||
writeMarker(orphan);
|
||||
writeMarker(otherNamespace);
|
||||
writeMarker(unnamespaced);
|
||||
when(lifecycleManager.tryListVolumeNames()).thenReturn(Optional.of(Set.of(vol)));
|
||||
|
||||
launcher.ensureCodeVolume(fn, "img");
|
||||
|
||||
assertEquals(List.of(vol), launcher.populated);
|
||||
Path markerDir = tempDir.resolve("lambda-codevol-markers");
|
||||
assertTrue(Files.isRegularFile(markerDir.resolve(vol)));
|
||||
assertFalse(Files.exists(markerDir.resolve(orphan)),
|
||||
"orphan markers under this namespace should be pruned");
|
||||
assertTrue(Files.isRegularFile(markerDir.resolve(otherNamespace)),
|
||||
"another namespace's markers must be left alone");
|
||||
assertTrue(Files.isRegularFile(markerDir.resolve(unnamespaced)),
|
||||
"un-namespaced markers must be left alone");
|
||||
}
|
||||
|
||||
@Test
|
||||
void populateHelperContainerNameIncludesNamespace() {
|
||||
assertEquals("floci-aws-ci1-codevol-orders-", populateHelperNamePrefix(config("ci1")));
|
||||
assertEquals("floci-aws-codevol-orders-", populateHelperNamePrefix(config(null)));
|
||||
}
|
||||
|
||||
/** Runs the real populateCodeVolume up to the helper spec build and returns the helper name minus its random id. */
|
||||
private String populateHelperNamePrefix(EmulatorConfig config) {
|
||||
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
|
||||
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class,
|
||||
Answers.RETURNS_SELF);
|
||||
when(containerBuilder.newContainer("img")).thenReturn(builder);
|
||||
when(builder.build()).thenThrow(new IllegalStateException("stop before Docker"));
|
||||
ContainerLauncher real = new ContainerLauncher(containerBuilder, lifecycleManager,
|
||||
mock(ContainerLogStreamer.class), mock(ImageResolver.class),
|
||||
mock(RuntimeApiServerFactory.class), mock(DockerHostResolver.class), config,
|
||||
mock(EcrRegistryManager.class), mock(LambdaLayerService.class),
|
||||
mock(LaunchedContainerAwsEnv.class), mock(LambdaExecutionRoleCredentials.class));
|
||||
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> real.populateCodeVolume("vol", fn("sha"), "img"));
|
||||
|
||||
ArgumentCaptor<String> name = ArgumentCaptor.forClass(String.class);
|
||||
verify(builder).withName(name.capture());
|
||||
String helperName = name.getValue();
|
||||
assertTrue(helperName.matches(".*-[0-9a-f]{8}"), helperName);
|
||||
return helperName.substring(0, helperName.length() - 8);
|
||||
}
|
||||
|
||||
@Test
|
||||
void successfulPopulationReplacesSymlinkMarkerWithoutFollowingIt() throws Exception {
|
||||
LambdaFunction fn = fn("sha-v1-abcdef0123456789");
|
||||
@@ -247,12 +319,12 @@ class ContainerLauncherCodeVolumeReuseTest {
|
||||
java.io.InputStream[] capturedInput = {null};
|
||||
when(dockerClient.copyArchiveToContainerCmd("container-123")).thenReturn(copyCommand);
|
||||
when(copyCommand.withRemotePath("/var/task")).thenReturn(copyCommand);
|
||||
when(copyCommand.withTarInputStream(org.mockito.ArgumentMatchers.any()))
|
||||
when(copyCommand.withTarInputStream(any()))
|
||||
.thenAnswer(invocation -> {
|
||||
capturedInput[0] = invocation.getArgument(0);
|
||||
return copyCommand;
|
||||
});
|
||||
org.mockito.Mockito.doAnswer(invocation -> {
|
||||
doAnswer(invocation -> {
|
||||
capturedInput[0].transferTo(java.io.OutputStream.nullOutputStream());
|
||||
return null;
|
||||
}).when(copyCommand).exec();
|
||||
|
||||
+81
@@ -8,6 +8,8 @@ import java.util.Optional;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -59,6 +61,77 @@ class ContainerLauncherNamePrefixTest {
|
||||
ContainerLauncher.codeVolumeName(ContainerLauncher.DEFAULT_NAME_PREFIX, fn));
|
||||
}
|
||||
|
||||
@Test
|
||||
void configCodeVolumeNameIsUnchangedWithoutNamespace() {
|
||||
LambdaFunction fn = fn();
|
||||
|
||||
assertEquals(ContainerLauncher.codeVolumeName(fn),
|
||||
ContainerLauncher.codeVolumeName(config(null, null), fn));
|
||||
assertEquals("floci-aws-code-my-fn-abc123def456",
|
||||
ContainerLauncher.codeVolumeName(config(null, " "), fn));
|
||||
assertEquals(ContainerLauncher.codeVolumeName("acme", fn),
|
||||
ContainerLauncher.codeVolumeName(config("acme", null), fn));
|
||||
assertEquals("floci-aws-code-", ContainerLauncher.codeVolumeNamePrefix(config(null, null)));
|
||||
assertEquals("acme-code-", ContainerLauncher.codeVolumeNamePrefix(config("acme", null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void codeVolumeNameIncludesResourceNamespace() {
|
||||
LambdaFunction fn = fn();
|
||||
|
||||
String name = ContainerLauncher.codeVolumeName(config(null, "ci1"), fn);
|
||||
|
||||
assertEquals("floci-aws-ci1-code-my-fn-abc123def456-490320b73797", name);
|
||||
assertTrue(DOCKER_NAME.matcher(name).matches(),
|
||||
"must be a docker-volume-safe name, was: " + name);
|
||||
assertEquals("floci-aws-ci1-code-", ContainerLauncher.codeVolumeNamePrefix(config(null, "ci1")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void codeVolumeNameCombinesCustomPrefixAndNamespace() {
|
||||
LambdaFunction fn = fn();
|
||||
|
||||
assertEquals("acme-ci1-code-my-fn-abc123def456-490320b73797",
|
||||
ContainerLauncher.codeVolumeName(config("acme", "ci1"), fn));
|
||||
assertEquals("acme-ci1-code-", ContainerLauncher.codeVolumeNamePrefix(config("acme", "ci1")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void codeVolumeNameDiffersAcrossNamespacesForSameCode() {
|
||||
LambdaFunction fn = fn();
|
||||
|
||||
String a = ContainerLauncher.codeVolumeName(config(null, "ci1"), fn);
|
||||
String b = ContainerLauncher.codeVolumeName(config(null, "ci2"), fn);
|
||||
|
||||
assertNotEquals(a, b, "two namespaced instances must not share a code volume");
|
||||
assertFalse(b.startsWith(ContainerLauncher.codeVolumeNamePrefix(config(null, "ci1"))),
|
||||
"one namespace's marker prefix must not match another namespace's volumes");
|
||||
}
|
||||
|
||||
/**
|
||||
* Namespaces and function names may both contain dashes, so the prefix and suffix alone can
|
||||
* spell one name for two namespaces; the namespace hash keeps them apart.
|
||||
*/
|
||||
@Test
|
||||
void codeVolumeNameKeepsDashedNamespacesAndFunctionNamesApart() {
|
||||
LambdaFunction fooCodeBar = fn();
|
||||
fooCodeBar.setFunctionName("foo-code-bar");
|
||||
LambdaFunction bar = fn();
|
||||
bar.setFunctionName("bar");
|
||||
|
||||
String a = ContainerLauncher.codeVolumeName(config(null, "ci"), fooCodeBar);
|
||||
String b = ContainerLauncher.codeVolumeName(config(null, "ci-code-foo"), bar);
|
||||
|
||||
assertNotEquals(a, b, "two namespaces must never spell the same code volume name");
|
||||
}
|
||||
|
||||
private static LambdaFunction fn() {
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setFunctionName("my-fn");
|
||||
fn.setCodeSha256("abc123def456");
|
||||
return fn;
|
||||
}
|
||||
|
||||
private static EmulatorConfig config(String prefix) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
@@ -68,4 +141,12 @@ class ContainerLauncherNamePrefixTest {
|
||||
when(lambda.containerNamePrefix()).thenReturn(Optional.ofNullable(prefix));
|
||||
return config;
|
||||
}
|
||||
|
||||
private static EmulatorConfig config(String prefix, String namespace) {
|
||||
EmulatorConfig config = config(prefix);
|
||||
EmulatorConfig.DockerConfig docker = mock(EmulatorConfig.DockerConfig.class);
|
||||
when(config.docker()).thenReturn(docker);
|
||||
when(docker.resourceNamespace()).thenReturn(Optional.ofNullable(namespace));
|
||||
return config;
|
||||
}
|
||||
}
|
||||
+43
@@ -1153,6 +1153,49 @@ class ContainerLauncherTest {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The sweep works from this process's own map of names, so a name it tracked can belong to
|
||||
* another resource namespace sharing the daemon: that volume is left alone, not requeued.
|
||||
*/
|
||||
@Test
|
||||
void cleanupSupersededVolumes_leavesAVolumeOfAnotherResourceNamespaceAlone() throws Exception {
|
||||
Path codePath = Files.createDirectory(tempDir.resolve("cleanup-ns-code"));
|
||||
Files.write(codePath.resolve("bundle.bin"), new byte[8 * 1024]);
|
||||
LambdaFunction v1 = new LambdaFunction();
|
||||
v1.setFunctionName("cleanup-ns-fn");
|
||||
v1.setRuntime("nodejs20.x");
|
||||
v1.setHandler("index.handler");
|
||||
v1.setCodeLocalPath(codePath.toString());
|
||||
v1.setCodeSha256("cleanup-ns-fn-sha-v1");
|
||||
String volumeV1 = ContainerLauncher.codeVolumeName(v1);
|
||||
LambdaFunction v2 = new LambdaFunction();
|
||||
v2.setFunctionName("cleanup-ns-fn");
|
||||
v2.setRuntime("nodejs20.x");
|
||||
v2.setHandler("index.handler");
|
||||
v2.setCodeLocalPath(codePath.toString());
|
||||
v2.setCodeSha256("cleanup-ns-fn-sha-v2");
|
||||
when(lifecycleManager.tryVolumeLabels(volumeV1))
|
||||
.thenReturn(Optional.of(Map.of("floci_namespace", "someone-else")));
|
||||
|
||||
long originalBytes = ContainerLauncher.CODE_VOLUME_MIN_BYTES;
|
||||
long originalGrace = ContainerLauncher.VOLUME_CLEANUP_GRACE_MS;
|
||||
try {
|
||||
ContainerLauncher.CODE_VOLUME_MIN_BYTES = 4 * 1024;
|
||||
ContainerLauncher.VOLUME_CLEANUP_GRACE_MS = -1;
|
||||
launcher.launch(v1);
|
||||
launcher.launch(v2);
|
||||
|
||||
launcher.cleanupSupersededVolumes();
|
||||
launcher.cleanupSupersededVolumes();
|
||||
|
||||
verify(lifecycleManager, never()).removeVolume(volumeV1);
|
||||
verify(lifecycleManager, times(1)).tryVolumeLabels(volumeV1);
|
||||
} finally {
|
||||
ContainerLauncher.CODE_VOLUME_MIN_BYTES = originalBytes;
|
||||
ContainerLauncher.VOLUME_CLEANUP_GRACE_MS = originalGrace;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void cleanupSupersededVolumes_retriesOnALaterSweep_whenTheVolumeIsStillInUse() throws Exception {
|
||||
// Regression: removeVolume() silently no-ops when Docker refuses because the volume is
|
||||
|
||||
Reference in new issue
Block a user