mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(lambda): reconcile code volumes against real Docker state and clean up superseded ones (#2208)
* fix(lambda): reconcile code volumes against real Docker state and clean up superseded ones Fixes #2164 Three problems in ContainerLauncher's per-function-version code volume management, all stemming from the same root cause: the "populated" bookkeeping was purely in-memory, never checked against or reconciled with Docker's actual state. - Stale volumes were never cleaned up on redeploy, only ever reclaimed by a user manually running docker volume prune. Now tracks each function's current volume and queues the superseded one for cleanup. - The in-memory "already populated" flag was trusted without ever re-checking Docker, so a volume removed out of band (manual docker volume rm, or an out-of-band prune) would silently mount an empty /var/task into the next container. ensureCodeVolume now also checks lifecycleManager.volumeExists() before trusting the flag. - Both of the above are really the same problem: no reconciliation against real Docker state. Fixed together by the same change. Cleanup is deferred rather than immediate: Docker auto-creates an empty named volume for a container mount that doesn't reference an existing one rather than failing, so a launch that resolved the old volume name just before a redeploy, but hasn't created its container yet, could be handed an empty /var/task by an immediate delete. A 60-second grace period, swept by a scheduled background task, crosses that window safely; removeVolume() also no-ops if the volume is still genuinely in use by then. * fix(lambda): rescue rolled-back code volumes and retry failed cleanup Addresses two review findings on the volume reconciliation fix: - The fast-path early return in ensureCodeVolume skipped the bookkeeping update entirely, so rolling back to a previous code version (v1 -> v2 -> v1) resolved v1's already-populated volume without pulling it back out of the pending-cleanup queue or marking it current again. The next sweep would delete the volume the function was actively using again. The bookkeeping reconciliation now always runs, whether or not the volume needed repopulating. - cleanupSupersededVolumes discarded a pending-cleanup entry unconditionally before attempting deletion, so a volume that Docker refused to remove (still in use by a slow-draining container that outlived the grace period) was silently dropped with no later sweep ever retrying it, permanently orphaning it. Now re-checks volumeExists after the delete attempt and re-queues with a fresh timestamp if the volume is still there. * fix(lambda): close the cleanup-vs-rollback race on code volumes Addresses a review finding: ensureCodeVolume's bookkeeping reconciliation and cleanupSupersededVolumes' claim-and-delete both touched volumesPendingCleanup with no mutual exclusion between them. If cleanup atomically claimed a superseded volume's entry a moment before a concurrent rollback resolved that same volume, the rollback would mark it current and hand it to a new container while cleanup proceeded to delete the real Docker volume out from under that launch - the exact empty /var/task failure mode the grace period exists to prevent, reached through the rescue path instead. Both methods now synchronize on the same per-volume-name lock (codeVolumeLocks) for their full resolve-or-claim-and-reconcile section, not just the expensive populate step. Whichever side wins the race, the other reliably observes the result under the lock rather than acting on stale state. Added a deterministic concurrency test using latches to force cleanup to block mid-deletion while still holding the lock, and assert a concurrent rollback blocks too rather than racing past it. Confirmed it fails against the previous commit (rollback completes immediately, racing past cleanup) and passes with this fix. * fix(lambda): stop pruning code-volume locks, closing a lock-identity race Addresses a review finding on the mutual-exclusion fix: pruning a volume's entry from codeVolumeLocks while a waiter elsewhere still held a reference to the removed entry's lock object let a third caller's computeIfAbsent create a replacement lock object for the same volume name. The original waiter (once granted the old lock) and that third caller (holding the new one) could then run their supposedly mutually-exclusive sections concurrently, reintroducing the exact cleanup-vs-rescue race the previous commit closed. The map is now never pruned. Each entry is a single Object keyed by volume name, bounded by the number of distinct function+code-version combinations ever launched, and negligible next to the disk space the rest of this fix reclaims - not worth the correctness risk of trying to bound it. Added a direct test verifying the actual invariant this depends on: a volume's lock entry survives a full populate-then-cleanup-delete cycle unchanged. The real interleaving that triggers this race needs precise JVM thread-scheduling control that isn't reliably forceable in a test, so this proves the fix by construction instead - confirmed it fails (both by compile error, since the accessor is new, and by a genuine runtime assertion failure when the removal is surgically reintroduced) without the fix and passes with it. * fix(lambda): give removeVolume a definitive success signal for cleanup retry Addresses a review finding: cleanupSupersededVolumes decided whether a deletion actually succeeded by making a second, separate call to volumeExists() afterward. That call's own exception handling treats a transient Docker API failure (a network blip, the daemon momentarily busy) the same as "confirmed does not exist", so a transient failure during that specific verification call, following an in-use no-op from removeVolume, would make cleanup wrongly conclude the volume was gone and drop it from the retry queue for good - the same permanent-loss bug fixed two commits ago, reachable through a different trigger. ContainerLifecycleManager.removeVolume now returns whether the volume is confirmed gone (removed, or already absent) rather than void. cleanupSupersededVolumes uses that return value directly instead of a second ambiguous check, so the failure mode described above can no longer happen: any removal attempt that isn't positively confirmed successful, for any reason, correctly retries on the next sweep. The other three real callers (EksClusterManager, MwaaEnvironmentManager, ContainerStorageHelper) all treat the call as fire-and-forget and don't need any changes; a void-to-boolean change doesn't break callers that ignore the return value. Verified with the full lambda and core.common.docker packages (550 tests, only the same pre-existing unrelated failures) plus the eks/mwaa/rds packages that call the other real usages of this method (one pre-existing, unrelated failure in RdsContainerManagerTest, confirmed identical against an unmodified upstream/main baseline in a throwaway worktree). * fix(lambda): protect in-flight code volumes from premature cleanup A launch that resolves its code volume name (ensureCodeVolume returns and releases the volume's lock) but hasn't yet called lifecycleManager.create() has no real Docker container-to-volume reference for removeVolume()'s own in-use check to protect. The fixed grace period isn't a safe upper bound on that gap either: create() itself has no proven bound on its duration (this file's own history notes it observed taking ~80s under daemon load, longer than the default 60s grace period). If a redeploy supersedes that volume and the grace period elapses while the original launch is still stuck before create(), a sweep can delete the volume out from under it, handing the container an empty /var/task once create() finally runs (Docker auto-creates an empty volume for a mount referencing a name that no longer exists rather than failing). Adds true in-flight reference counting instead of relying on elapsed time: ensureCodeVolume increments a per-volume counter before returning (still under the volume's lock, so a concurrent sweep that acquires the same lock next is guaranteed to observe it), and the caller releases it in launch() once create() succeeds - or in the existing catch-all failure handler if it never gets that far. cleanupSupersededVolumes re-queues rather than deletes any volume whose count is still nonzero, regardless of how long it's been queued. Verified: new test forces a second launch of an already-populated volume to block right before create() while a redeploy supersedes it and the grace period is made to elapse instantly; cleanup must skip it while the count is nonzero and only remove it once the delayed launch completes and releases its reference. Confirmed the test fails (cleanup deletes the volume mid-flight) with the guard temporarily disabled, and passes with it restored. Full lambda.launcher and core.common.docker package regression (174 tests) is green. * fix(lambda): serialize the current-volume transition per function pgermosen's review on this PR pointed out that functionCurrentVolume and volumesPendingCleanup are reconciled under the per-volume lock only. Two code versions of the same function resolve to two different volume names, so they acquire two different codeVolumeLocks entries and can run that reconciliation concurrently - which is fine for the populate work each guards, but not for this transition. Without a shared lock, a rapid back-to-back redeploy (v2 then v3) can have the two functionCurrentVolume.put() calls land out of order: whichever one happens to execute last wins as "current" regardless of which redeploy was actually latest, and the volume it displaces gets queued for cleanup using a "previous" value each thread captured locally right before its own put() - so if v2's full transition runs after v3's, v3 (briefly and correctly current) ends up queued for deletion while stale v2 is left recorded as current. Adds a per-function lock (functionVolumeTransitionLocks, keyed by function name rather than volume name) around just this transition. It doesn't and can't guarantee which redeploy "wins" when two race genuinely concurrently - that would need ordering information this method isn't given - but it does guarantee the bookkeeping itself stays self-consistent: whichever volume ends up current is never also left in the pending-cleanup set, and whatever it displaced is queued exactly once. Verified: the transition's three statements are plain map operations with no interception point inside them, so forcing the exact bad interleaving isn't reliably doable in a test. Instead added a test proving the fix's actual mechanism - a concurrent launch for a second code version of the same function blocks on the same per-function lock object while another launch holds it - the same style already used for the per-volume lock in cleanupAndAConcurrentRollback_areMutuallyExclusiveForTheSameVolume. Confirmed the test fails when the lock is swapped for an unshared one and passes with the real lock restored. Full lambda.launcher and core.common.docker package regression (175 tests) is green.
This commit is contained in:
1 parent
6344852540
commit
a5daab6fb7
3 files changed
+695
-30
No files matched your search
+459
-1
@@ -48,6 +48,7 @@ import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
@@ -592,7 +593,9 @@ class ContainerLauncherTest {
|
||||
verify(lifecycleManager, times(2)).create(any());
|
||||
verify(lifecycleManager, atLeastOnce()).ensureVolume(any());
|
||||
verify(lifecycleManager, times(1)).stopAndRemove(any(), any()); // the helper only
|
||||
// Old code-version volumes are NOT eagerly deleted (race fix); they are label-pruned instead.
|
||||
// A superseded code-version volume is never deleted synchronously within a single launch
|
||||
// (see the cleanupSupersededVolumes tests below for the deferred sweep; this fn has no
|
||||
// prior volume to supersede, since it's the fn's first deploy here).
|
||||
verify(lifecycleManager, never()).removeVolume(any());
|
||||
}
|
||||
|
||||
@@ -631,6 +634,461 @@ class ContainerLauncherTest {
|
||||
verify(lifecycleManager, never()).startCreated(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchFunction_reprovisionsCodeVolume_whenDockerHasNoRecordOfIt() throws Exception {
|
||||
// Regression for #2164: the "populated" bookkeeping is only ever an in-memory cache of
|
||||
// Docker's state, so a volume removed out of band (manual `docker volume rm`, or a stale
|
||||
// in-memory flag left over from a process restart racing a prune) must not be trusted.
|
||||
Path codePath = Files.createDirectory(tempDir.resolve("revalidate-code"));
|
||||
Files.write(codePath.resolve("bundle.bin"), new byte[8 * 1024]); // 8 KiB
|
||||
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setFunctionName("revalidate-fn");
|
||||
fn.setRuntime("nodejs20.x");
|
||||
fn.setHandler("index.handler");
|
||||
fn.setCodeLocalPath(codePath.toString());
|
||||
fn.setCodeSha256("revalidate-fn-sha-v1");
|
||||
|
||||
// Docker never reports this volume as existing, simulating it being gone every time
|
||||
// ensureCodeVolume checks, regardless of what the in-memory flag says.
|
||||
when(lifecycleManager.volumeExists(anyString())).thenReturn(false);
|
||||
|
||||
long original = ContainerLauncher.CODE_VOLUME_MIN_BYTES;
|
||||
try {
|
||||
ContainerLauncher.CODE_VOLUME_MIN_BYTES = 4 * 1024;
|
||||
launcher.launch(fn);
|
||||
launcher.launch(fn);
|
||||
} finally {
|
||||
ContainerLauncher.CODE_VOLUME_MIN_BYTES = original;
|
||||
}
|
||||
|
||||
// Populated twice, once per launch, because the bookkeeping alone is never trusted.
|
||||
assertEquals(2, capturedRemotePaths.stream().filter("/var/task"::equals).count(),
|
||||
"each launch should repopulate since Docker never confirms the volume exists");
|
||||
}
|
||||
|
||||
@Test
|
||||
void cleanupSupersededVolumes_removesPreviousVersionVolume_onceGracePeriodElapses() throws Exception {
|
||||
Path codePath = Files.createDirectory(tempDir.resolve("cleanup-code"));
|
||||
Files.write(codePath.resolve("bundle.bin"), new byte[8 * 1024]); // 8 KiB
|
||||
// No volumeExists stub needed: v1 and v2 are each a first-ever population of their own
|
||||
// distinct volume name, so populatedCodeVolumes.contains(volName) is false both times
|
||||
// ensureCodeVolume checks it, short-circuiting the volumeExists call away entirely.
|
||||
|
||||
LambdaFunction v1 = new LambdaFunction();
|
||||
v1.setFunctionName("cleanup-fn");
|
||||
v1.setRuntime("nodejs20.x");
|
||||
v1.setHandler("index.handler");
|
||||
v1.setCodeLocalPath(codePath.toString());
|
||||
v1.setCodeSha256("cleanup-fn-sha-v1");
|
||||
String volumeV1 = ContainerLauncher.codeVolumeName(v1);
|
||||
|
||||
LambdaFunction v2 = new LambdaFunction();
|
||||
v2.setFunctionName("cleanup-fn");
|
||||
v2.setRuntime("nodejs20.x");
|
||||
v2.setHandler("index.handler");
|
||||
v2.setCodeLocalPath(codePath.toString());
|
||||
v2.setCodeSha256("cleanup-fn-sha-v2");
|
||||
String volumeV2 = ContainerLauncher.codeVolumeName(v2);
|
||||
|
||||
long originalBytes = ContainerLauncher.CODE_VOLUME_MIN_BYTES;
|
||||
long originalGrace = ContainerLauncher.VOLUME_CLEANUP_GRACE_MS;
|
||||
try {
|
||||
ContainerLauncher.CODE_VOLUME_MIN_BYTES = 4 * 1024;
|
||||
launcher.launch(v1);
|
||||
launcher.launch(v2);
|
||||
|
||||
// The v1 volume is superseded but not yet cleaned up: the grace period hasn't elapsed.
|
||||
launcher.cleanupSupersededVolumes();
|
||||
verify(lifecycleManager, never()).removeVolume(volumeV1);
|
||||
|
||||
// Once the grace period has (trivially) elapsed, the sweep removes exactly the
|
||||
// superseded v1 volume, not the current v2 one.
|
||||
ContainerLauncher.VOLUME_CLEANUP_GRACE_MS = -1;
|
||||
launcher.cleanupSupersededVolumes();
|
||||
verify(lifecycleManager, times(1)).removeVolume(volumeV1);
|
||||
verify(lifecycleManager, never()).removeVolume(volumeV2);
|
||||
} finally {
|
||||
ContainerLauncher.CODE_VOLUME_MIN_BYTES = originalBytes;
|
||||
ContainerLauncher.VOLUME_CLEANUP_GRACE_MS = originalGrace;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollingBackToAPreviousCodeVersion_rescuesItsVolumeFromCleanup() throws Exception {
|
||||
// Regression: v1 -> v2 -> back to v1 (e.g. a CloudFormation rollback) resolves v1's volume
|
||||
// name again, which is already populated - a fast-path hit in ensureCodeVolume. Without
|
||||
// reconciling functionCurrentVolume/volumesPendingCleanup on that path too, v1 would stay
|
||||
// queued as superseded from the v1 -> v2 step and the next sweep would delete the volume
|
||||
// this function is actively using again.
|
||||
Path codePath = Files.createDirectory(tempDir.resolve("rollback-code"));
|
||||
Files.write(codePath.resolve("bundle.bin"), new byte[8 * 1024]); // 8 KiB
|
||||
|
||||
LambdaFunction v1 = new LambdaFunction();
|
||||
v1.setFunctionName("rollback-fn");
|
||||
v1.setRuntime("nodejs20.x");
|
||||
v1.setHandler("index.handler");
|
||||
v1.setCodeLocalPath(codePath.toString());
|
||||
v1.setCodeSha256("rollback-fn-sha-v1");
|
||||
String volumeV1 = ContainerLauncher.codeVolumeName(v1);
|
||||
|
||||
LambdaFunction v2 = new LambdaFunction();
|
||||
v2.setFunctionName("rollback-fn");
|
||||
v2.setRuntime("nodejs20.x");
|
||||
v2.setHandler("index.handler");
|
||||
v2.setCodeLocalPath(codePath.toString());
|
||||
v2.setCodeSha256("rollback-fn-sha-v2");
|
||||
String volumeV2 = ContainerLauncher.codeVolumeName(v2);
|
||||
|
||||
// Needed for the rollback launch below: v1's volume is already populated by then, so its
|
||||
// fast path actually evaluates volumeExists instead of short-circuiting past it.
|
||||
when(lifecycleManager.volumeExists(volumeV1)).thenReturn(true);
|
||||
|
||||
long originalBytes = ContainerLauncher.CODE_VOLUME_MIN_BYTES;
|
||||
long originalGrace = ContainerLauncher.VOLUME_CLEANUP_GRACE_MS;
|
||||
try {
|
||||
ContainerLauncher.CODE_VOLUME_MIN_BYTES = 4 * 1024;
|
||||
launcher.launch(v1);
|
||||
launcher.launch(v2);
|
||||
launcher.launch(v1); // roll back
|
||||
|
||||
ContainerLauncher.VOLUME_CLEANUP_GRACE_MS = -1;
|
||||
launcher.cleanupSupersededVolumes();
|
||||
verify(lifecycleManager, never()).removeVolume(volumeV1);
|
||||
verify(lifecycleManager, times(1)).removeVolume(volumeV2);
|
||||
} 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
|
||||
// still in use (e.g. a slow-draining in-flight container outliving the grace period). The
|
||||
// pending-cleanup entry must not be discarded in that case, or the volume is orphaned until
|
||||
// someone manually runs `docker volume prune`- the exact problem this fix exists to avoid.
|
||||
Path codePath = Files.createDirectory(tempDir.resolve("retry-code"));
|
||||
Files.write(codePath.resolve("bundle.bin"), new byte[8 * 1024]); // 8 KiB
|
||||
|
||||
LambdaFunction v1 = new LambdaFunction();
|
||||
v1.setFunctionName("retry-fn");
|
||||
v1.setRuntime("nodejs20.x");
|
||||
v1.setHandler("index.handler");
|
||||
v1.setCodeLocalPath(codePath.toString());
|
||||
v1.setCodeSha256("retry-fn-sha-v1");
|
||||
String volumeV1 = ContainerLauncher.codeVolumeName(v1);
|
||||
|
||||
LambdaFunction v2 = new LambdaFunction();
|
||||
v2.setFunctionName("retry-fn");
|
||||
v2.setRuntime("nodejs20.x");
|
||||
v2.setHandler("index.handler");
|
||||
v2.setCodeLocalPath(codePath.toString());
|
||||
v2.setCodeSha256("retry-fn-sha-v2");
|
||||
|
||||
// v1's volume persists (still in use) no matter how many times removal is attempted.
|
||||
when(lifecycleManager.removeVolume(volumeV1)).thenReturn(false);
|
||||
|
||||
long originalBytes = ContainerLauncher.CODE_VOLUME_MIN_BYTES;
|
||||
long originalGrace = ContainerLauncher.VOLUME_CLEANUP_GRACE_MS;
|
||||
try {
|
||||
ContainerLauncher.CODE_VOLUME_MIN_BYTES = 4 * 1024;
|
||||
launcher.launch(v1);
|
||||
launcher.launch(v2);
|
||||
|
||||
ContainerLauncher.VOLUME_CLEANUP_GRACE_MS = -1;
|
||||
launcher.cleanupSupersededVolumes();
|
||||
verify(lifecycleManager, times(1)).removeVolume(volumeV1);
|
||||
|
||||
// A later sweep must still retry it, not have silently dropped it after the first
|
||||
// no-op'd attempt.
|
||||
launcher.cleanupSupersededVolumes();
|
||||
verify(lifecycleManager, times(2)).removeVolume(volumeV1);
|
||||
} finally {
|
||||
ContainerLauncher.CODE_VOLUME_MIN_BYTES = originalBytes;
|
||||
ContainerLauncher.VOLUME_CLEANUP_GRACE_MS = originalGrace;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void cleanupAndAConcurrentRollback_areMutuallyExclusiveForTheSameVolume() throws Exception {
|
||||
// Regression: without a shared per-volume lock, a sweep that has already claimed a
|
||||
// superseded volume (removed its pending-cleanup entry) could race a concurrent rollback
|
||||
// that resolves the same volume name, marks it current, and hands it to a new container -
|
||||
// while the sweep proceeds to actually delete it underneath that launch. Proving this
|
||||
// requires real concurrency: this test forces cleanupSupersededVolumes to block mid-deletion
|
||||
// (still holding the volume's lock) and asserts a concurrent rollback blocks too, rather than
|
||||
// racing past it.
|
||||
Path codePath = Files.createDirectory(tempDir.resolve("race-code"));
|
||||
Files.write(codePath.resolve("bundle.bin"), new byte[8 * 1024]); // 8 KiB
|
||||
|
||||
LambdaFunction v1 = new LambdaFunction();
|
||||
v1.setFunctionName("race-fn");
|
||||
v1.setRuntime("nodejs20.x");
|
||||
v1.setHandler("index.handler");
|
||||
v1.setCodeLocalPath(codePath.toString());
|
||||
v1.setCodeSha256("race-fn-sha-v1");
|
||||
String volumeV1 = ContainerLauncher.codeVolumeName(v1);
|
||||
|
||||
LambdaFunction v2 = new LambdaFunction();
|
||||
v2.setFunctionName("race-fn");
|
||||
v2.setRuntime("nodejs20.x");
|
||||
v2.setHandler("index.handler");
|
||||
v2.setCodeLocalPath(codePath.toString());
|
||||
v2.setCodeSha256("race-fn-sha-v2");
|
||||
|
||||
when(lifecycleManager.volumeExists(volumeV1)).thenReturn(true);
|
||||
|
||||
java.util.concurrent.CountDownLatch cleanupHoldingLock = new java.util.concurrent.CountDownLatch(1);
|
||||
java.util.concurrent.CountDownLatch releaseCleanup = new java.util.concurrent.CountDownLatch(1);
|
||||
doAnswer(inv -> {
|
||||
cleanupHoldingLock.countDown();
|
||||
// Blocks here while still holding volumeV1's per-volume lock, simulating a slow delete.
|
||||
assertTrue(releaseCleanup.await(5, java.util.concurrent.TimeUnit.SECONDS),
|
||||
"test did not release cleanup in time");
|
||||
return null;
|
||||
}).when(lifecycleManager).removeVolume(volumeV1);
|
||||
|
||||
long originalBytes = ContainerLauncher.CODE_VOLUME_MIN_BYTES;
|
||||
long originalGrace = ContainerLauncher.VOLUME_CLEANUP_GRACE_MS;
|
||||
try {
|
||||
ContainerLauncher.CODE_VOLUME_MIN_BYTES = 4 * 1024;
|
||||
launcher.launch(v1);
|
||||
launcher.launch(v2);
|
||||
ContainerLauncher.VOLUME_CLEANUP_GRACE_MS = -1;
|
||||
|
||||
Thread cleanupThread = new Thread(launcher::cleanupSupersededVolumes);
|
||||
cleanupThread.start();
|
||||
assertTrue(cleanupHoldingLock.await(5, java.util.concurrent.TimeUnit.SECONDS),
|
||||
"cleanup never reached removeVolume");
|
||||
|
||||
java.util.concurrent.atomic.AtomicBoolean rollbackReturned =
|
||||
new java.util.concurrent.atomic.AtomicBoolean(false);
|
||||
Thread rollbackThread = new Thread(() -> {
|
||||
launcher.launch(v1);
|
||||
rollbackReturned.set(true);
|
||||
});
|
||||
rollbackThread.start();
|
||||
|
||||
// Give the rollback every chance to (wrongly) proceed if the lock weren't shared.
|
||||
Thread.sleep(200);
|
||||
assertFalse(rollbackReturned.get(),
|
||||
"rollback must block while cleanup holds the volume's lock, not race past it");
|
||||
|
||||
releaseCleanup.countDown();
|
||||
cleanupThread.join(5000);
|
||||
rollbackThread.join(5000);
|
||||
assertTrue(rollbackReturned.get(), "rollback should complete once cleanup releases the lock");
|
||||
} finally {
|
||||
ContainerLauncher.CODE_VOLUME_MIN_BYTES = originalBytes;
|
||||
ContainerLauncher.VOLUME_CLEANUP_GRACE_MS = originalGrace;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void cleanupSkipsAVolumeStillInFlight_evenPastItsGracePeriod() throws Exception {
|
||||
// Regression: a launch that has resolved its code volume (ensureCodeVolume returned, its
|
||||
// per-volume lock released) but hasn't yet reached lifecycleManager.create() has no real
|
||||
// Docker container-to-volume reference for removeVolume's own in-use check to protect - and
|
||||
// create() itself has no proven upper bound (observed ~80s under daemon load, longer than
|
||||
// the default 60s grace period). This forces a second launch of v1 to block right before
|
||||
// create() while a redeploy to v2 supersedes its volume and the grace period is made to
|
||||
// elapse instantly, then asserts cleanup does NOT delete v1's volume while that launch is
|
||||
// still in flight - only once it completes and releases its reference.
|
||||
Path codePath = Files.createDirectory(tempDir.resolve("inflight-code"));
|
||||
Files.write(codePath.resolve("bundle.bin"), new byte[8 * 1024]); // 8 KiB
|
||||
|
||||
LambdaFunction v1 = new LambdaFunction();
|
||||
v1.setFunctionName("inflight-fn");
|
||||
v1.setRuntime("nodejs20.x");
|
||||
v1.setHandler("index.handler");
|
||||
v1.setCodeLocalPath(codePath.toString());
|
||||
v1.setCodeSha256("inflight-fn-sha-v1");
|
||||
String volumeV1 = ContainerLauncher.codeVolumeName(v1);
|
||||
|
||||
LambdaFunction v2 = new LambdaFunction();
|
||||
v2.setFunctionName("inflight-fn");
|
||||
v2.setRuntime("nodejs20.x");
|
||||
v2.setHandler("index.handler");
|
||||
v2.setCodeLocalPath(codePath.toString());
|
||||
v2.setCodeSha256("inflight-fn-sha-v2");
|
||||
|
||||
// Needed for the delayed re-launch below: v1's volume is already populated by then, so its
|
||||
// fast path actually evaluates volumeExists instead of short-circuiting past it.
|
||||
when(lifecycleManager.volumeExists(volumeV1)).thenReturn(true);
|
||||
|
||||
long originalBytes = ContainerLauncher.CODE_VOLUME_MIN_BYTES;
|
||||
long originalGrace = ContainerLauncher.VOLUME_CLEANUP_GRACE_MS;
|
||||
try {
|
||||
ContainerLauncher.CODE_VOLUME_MIN_BYTES = 4 * 1024;
|
||||
|
||||
// Pre-populate v1's volume with an ordinary launch, before installing the create()
|
||||
// blocking stub below - otherwise that stub would catch populateCodeVolume's own
|
||||
// helper-container create() call instead of the real container's.
|
||||
launcher.launch(v1);
|
||||
|
||||
java.util.concurrent.CountDownLatch launchReachedCreate = new java.util.concurrent.CountDownLatch(1);
|
||||
java.util.concurrent.CountDownLatch releaseLaunch = new java.util.concurrent.CountDownLatch(1);
|
||||
java.util.concurrent.atomic.AtomicBoolean blockedOnce = new java.util.concurrent.atomic.AtomicBoolean(false);
|
||||
doAnswer(inv -> {
|
||||
if (blockedOnce.compareAndSet(false, true)) {
|
||||
// Only the delayed re-launch of v1 (the first caller after this stub is
|
||||
// installed) blocks here; v2's later launch below must not, or the test would
|
||||
// deadlock itself waiting on its own main thread to release the latch.
|
||||
launchReachedCreate.countDown();
|
||||
assertTrue(releaseLaunch.await(5, java.util.concurrent.TimeUnit.SECONDS),
|
||||
"test did not release the delayed launch in time");
|
||||
}
|
||||
return "container-123";
|
||||
}).when(lifecycleManager).create(any());
|
||||
|
||||
Thread launchThread = new Thread(() -> launcher.launch(v1));
|
||||
launchThread.start();
|
||||
assertTrue(launchReachedCreate.await(5, java.util.concurrent.TimeUnit.SECONDS),
|
||||
"v1's delayed re-launch never reached create()");
|
||||
|
||||
assertEquals(1, launcher.inFlightCount(volumeV1),
|
||||
"ensureCodeVolume must mark the volume in-flight before create() confirms it");
|
||||
|
||||
// A redeploy resolves v2 and supersedes v1's volume while v1's own launch is still stuck.
|
||||
launcher.launch(v2);
|
||||
ContainerLauncher.VOLUME_CLEANUP_GRACE_MS = -1; // grace period elapses instantly
|
||||
|
||||
launcher.cleanupSupersededVolumes();
|
||||
verify(lifecycleManager, never()).removeVolume(volumeV1);
|
||||
|
||||
// Let the delayed launch finish; it releases its in-flight reference on success.
|
||||
releaseLaunch.countDown();
|
||||
launchThread.join(5000);
|
||||
assertEquals(0, launcher.inFlightCount(volumeV1),
|
||||
"in-flight count must be released once create() succeeds");
|
||||
|
||||
// Nothing is in flight anymore, so a later sweep is free to actually delete it.
|
||||
launcher.cleanupSupersededVolumes();
|
||||
verify(lifecycleManager, times(1)).removeVolume(volumeV1);
|
||||
} finally {
|
||||
ContainerLauncher.CODE_VOLUME_MIN_BYTES = originalBytes;
|
||||
ContainerLauncher.VOLUME_CLEANUP_GRACE_MS = originalGrace;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentRedeploysOfTheSameFunction_serializeTheCurrentVolumeTransition() throws Exception {
|
||||
// Regression: functionCurrentVolume/volumesPendingCleanup reconciliation ran under the
|
||||
// per-volume lock only, but two code versions of the same function resolve to two different
|
||||
// volume names and so hold two different per-volume locks - meaning that reconciliation
|
||||
// could interleave across a rapid back-to-back redeploy (v2 then v3), leaving the actually-
|
||||
// current v3 volume mistakenly queued for cleanup while stale v2 stayed recorded as current.
|
||||
// The three statements involved (remove pending-cleanup entry, swap in the new current
|
||||
// volume, queue whatever was displaced) are plain map operations with no interception point
|
||||
// inside them, so forcing that exact interleaving isn't reliably doable in a test. This
|
||||
// instead verifies the fix's actual mechanism directly - a concurrent launch for a second
|
||||
// code version of the same function must block on the same per-function lock object while
|
||||
// another is still transitioning - the same style cleanupAndAConcurrentRollback... already
|
||||
// uses to prove the per-volume lock.
|
||||
Path codePath = Files.createDirectory(tempDir.resolve("xfn-code"));
|
||||
Files.write(codePath.resolve("bundle.bin"), new byte[8 * 1024]); // 8 KiB
|
||||
|
||||
LambdaFunction v1 = new LambdaFunction();
|
||||
v1.setFunctionName("xfn");
|
||||
v1.setRuntime("nodejs20.x");
|
||||
v1.setHandler("index.handler");
|
||||
v1.setCodeLocalPath(codePath.toString());
|
||||
v1.setCodeSha256("xfn-sha-v1");
|
||||
|
||||
long originalBytes = ContainerLauncher.CODE_VOLUME_MIN_BYTES;
|
||||
try {
|
||||
ContainerLauncher.CODE_VOLUME_MIN_BYTES = 4 * 1024;
|
||||
|
||||
Object functionLock = launcher.functionVolumeTransitionLockFor("xfn");
|
||||
java.util.concurrent.CountDownLatch testHoldingLock = new java.util.concurrent.CountDownLatch(1);
|
||||
java.util.concurrent.CountDownLatch releaseLock = new java.util.concurrent.CountDownLatch(1);
|
||||
Thread holderThread = new Thread(() -> {
|
||||
synchronized (functionLock) {
|
||||
testHoldingLock.countDown();
|
||||
try {
|
||||
assertTrue(releaseLock.await(5, java.util.concurrent.TimeUnit.SECONDS),
|
||||
"test did not release the function lock in time");
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
});
|
||||
holderThread.start();
|
||||
assertTrue(testHoldingLock.await(5, java.util.concurrent.TimeUnit.SECONDS),
|
||||
"test thread never acquired the function lock");
|
||||
|
||||
AtomicBoolean launchReturned = new AtomicBoolean(false);
|
||||
Thread launchThread = new Thread(() -> {
|
||||
launcher.launch(v1);
|
||||
launchReturned.set(true);
|
||||
});
|
||||
launchThread.start();
|
||||
|
||||
// Give the launch every chance to (wrongly) proceed if the transition weren't guarded
|
||||
// by this same lock.
|
||||
Thread.sleep(200);
|
||||
assertFalse(launchReturned.get(),
|
||||
"launch must block on the function lock while another holder has it, not race past it");
|
||||
|
||||
releaseLock.countDown();
|
||||
holderThread.join(5000);
|
||||
launchThread.join(5000);
|
||||
assertTrue(launchReturned.get(), "launch should complete once the function lock is released");
|
||||
} finally {
|
||||
ContainerLauncher.CODE_VOLUME_MIN_BYTES = originalBytes;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void codeVolumeLocks_isNeverPruned_evenAfterCleanupDeletesTheVolume() throws Exception {
|
||||
// Regression: pruning a volume's lock entry while a waiter still held a reference to the
|
||||
// removed entry's lock object let a third caller's computeIfAbsent create a *different* lock
|
||||
// object for the same volume name, so the waiter (once granted the old lock) and that third
|
||||
// caller (holding the new one) could run their supposedly mutually-exclusive sections
|
||||
// concurrently - defeating the whole point. The actual JVM interleaving needed to trigger
|
||||
// that is timing-dependent and not reliably forceable in a test, so this instead verifies the
|
||||
// fix's real invariant directly: the lock entry must survive a full populate-then-delete
|
||||
// cycle unchanged, which is what actually guarantees computeIfAbsent always returns the same
|
||||
// object for a given volume name for the life of the process.
|
||||
Path codePath = Files.createDirectory(tempDir.resolve("lock-persist-code"));
|
||||
Files.write(codePath.resolve("bundle.bin"), new byte[8 * 1024]); // 8 KiB
|
||||
|
||||
LambdaFunction v1 = new LambdaFunction();
|
||||
v1.setFunctionName("lock-persist-fn");
|
||||
v1.setRuntime("nodejs20.x");
|
||||
v1.setHandler("index.handler");
|
||||
v1.setCodeLocalPath(codePath.toString());
|
||||
v1.setCodeSha256("lock-persist-fn-sha-v1");
|
||||
String volumeV1 = ContainerLauncher.codeVolumeName(v1);
|
||||
|
||||
LambdaFunction v2 = new LambdaFunction();
|
||||
v2.setFunctionName("lock-persist-fn");
|
||||
v2.setRuntime("nodejs20.x");
|
||||
v2.setHandler("index.handler");
|
||||
v2.setCodeLocalPath(codePath.toString());
|
||||
v2.setCodeSha256("lock-persist-fn-sha-v2");
|
||||
|
||||
long originalBytes = ContainerLauncher.CODE_VOLUME_MIN_BYTES;
|
||||
long originalGrace = ContainerLauncher.VOLUME_CLEANUP_GRACE_MS;
|
||||
try {
|
||||
ContainerLauncher.CODE_VOLUME_MIN_BYTES = 4 * 1024;
|
||||
launcher.launch(v1);
|
||||
assertTrue(launcher.hasCodeVolumeLock(volumeV1), "lock must exist right after populate");
|
||||
|
||||
launcher.launch(v2); // supersedes v1's volume, queues it for cleanup
|
||||
ContainerLauncher.VOLUME_CLEANUP_GRACE_MS = -1;
|
||||
launcher.cleanupSupersededVolumes(); // deletes v1's volume for real
|
||||
|
||||
assertTrue(launcher.hasCodeVolumeLock(volumeV1),
|
||||
"lock must still exist even after the volume itself was deleted - "
|
||||
+ "pruning it here is exactly the bug this test guards against");
|
||||
} finally {
|
||||
ContainerLauncher.CODE_VOLUME_MIN_BYTES = originalBytes;
|
||||
ContainerLauncher.VOLUME_CLEANUP_GRACE_MS = originalGrace;
|
||||
}
|
||||
}
|
||||
|
||||
/** Builds a tar archive matching what {@code docker cp}/{@code copyArchiveFromContainerCmd}
|
||||
* returns for a directory: the directory itself as a leading entry, then each name as a direct
|
||||
* child, executable. */
|
||||
|
||||
Reference in new issue
Block a user