Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(lambda): tar archives not being accesses in layers
Nahuel990dc1f2b732303
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex f5ae3891..32d1d306 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -1399,6 +1399,9 @@ def _delete_function(name: str, query_params: dict):else:del _functions[name]invalidate_worker(name)+ # Docker pool too — otherwise the function's pooled containers leak+ # until _WARM_CONTAINER_TTL eviction.+ _pool_kill_function(get_account_id(), name)return 204, {}, b""@@ -1451,6 +1454,10 @@ def _update_code(name: str, data: dict):# Invalidate only the old $LATEST worker — published version workers stay aliveinvalidate_worker(name, qualifier="$LATEST")+ # Docker pool: the new CodeSha256 changes the pool key so new invokes+ # spawn fresh containers anyway, but the old containers under the old key+ # would linger until _WARM_CONTAINER_TTL. Reap them now.+ _pool_kill_function(get_account_id(), name)_schedule_state_transition(name, _LAMBDA_STATE_TRANSITION_DELAY)if data.get("Publish"):@@ -1534,6 +1541,13 @@ def _update_config(name: str, data: dict):}if any(k in data for k in _WORKER_AFFECTING):invalidate_worker(name, qualifier="$LATEST")+ # Also invalidate the docker warm-container pool: its key is+ # account:func:zip:CodeSha256, so config-only changes (Layers,+ # Environment, MemorySize, etc.) wouldn't otherwise displace a stale+ # pooled container. Without this, LAMBDA_EXECUTOR=docker users hit the+ # same "old container, no new layer mounted" failure mode that the+ # in-process warm worker recycle solved for Python/Node.+ _pool_kill_function(get_account_id(), name)_schedule_state_transition(name, _LAMBDA_STATE_TRANSITION_DELAY)return json_response(config)@@ -1937,6 +1951,29 @@ def _pool_clear_all() -> None:_kill_pool_entry(e)+def _pool_kill_function(account: str, func_name: str) -> None:+ """Kill every pooled docker container for a function across all qualifiers.++ The pool key is ``{account}:{func_name}:zip:{CodeSha256}`` (or+ ``:image:{ImageUri}``). UpdateFunctionConfiguration changes attributes that+ don't show up in the key (Layers / Environment / MemorySize / VpcConfig /+ Architectures / FileSystemConfigs / Runtime / Handler), so the same key+ would otherwise hand back a stale container that was spawned before the+ config change. Issue #816 docker-executor follow-up: a layer attached+ after the first invoke was never mounted on the reused warm container,+ so handler imports from the layer kept failing even after the layer's+ extracted dir was correct.+ """+ prefix = f"{account}:{func_name}:"+ to_kill = []+ with _warm_pool_lock:+ for key in list(_warm_pool.keys()):+ if key.startswith(prefix):+ to_kill.extend(_warm_pool.pop(key))+ for e in to_kill:+ _kill_pool_entry(e)++def _ensure_reaper_thread() -> None:global _reaper_startedwith _reaper_lock:@@ -2236,12 +2273,20 @@ def _throttle_response(reason_code: str, msg: str, retry_after: int = 1) -> dict}-def _docker_cp_dir(container, src_dir: str, dest_dir: str):- """Copy a local directory into a Docker container using a tar archive."""+def _docker_cp_dir(container, src_dir: str, dest_dir: str, arcname: str = "."):+ """Copy a local directory into a Docker container using a tar archive.++ Docker's ``put_archive`` requires ``dest_dir`` to already exist in the+ container. For paths the base image owns (``/var/task``, ``/var/runtime``,+ ``/opt``) this is fine. For paths we want to create (``/opt/layer_N``),+ extract into the existing parent and pass the new subdir via ``arcname``+ so the tar carries ``./layer_N/...`` entries — the put_archive call+ materialises the subdir as part of extraction.+ """import tarfilebuf = io.BytesIO()with tarfile.open(fileobj=buf, mode="w") as tar:- tar.add(src_dir, arcname=".")+ tar.add(src_dir, arcname=arcname)buf.seek(0)container.put_archive(dest_dir, buf)@@ -2596,7 +2641,10 @@ def _spawn_lambda_container(config: dict, code_zip: bytes | None):if is_provided:_docker_cp_dir(container, code_dir, "/var/runtime")for idx, ld in enumerate(layers_dirs):- _docker_cp_dir(container, ld, f"/opt/layer_{idx}")+ # /opt/layer_{idx} doesn't exist in the base RIE image — extract+ # into /opt with the layer dir baked into the arcname (issue #816+ # follow-up: docker executor 404 on archive path).+ _docker_cp_dir(container, ld, "/opt", arcname=f"layer_{idx}")container.start()else:container = client.containers.run(**run_kwargs)diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex 2804cd81..4da978ef 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -1485,6 +1485,90 @@ def test_lambda_function_with_layer(lam):assert layer_arn in fn["Configuration"]["Layers"][0]["Arn"]+def test_lambda_docker_cp_dir_arcname_creates_subdir_in_existing_parent():+ """Docker's put_archive requires dest_dir to exist. For /opt/layer_N+ (which doesn't exist in the base RIE image), the fix is to extract into+ the existing /opt with the layer dir baked into the arcname so the tar+ materialises the subdir. Regression for issue #816 docker-executor 404."""+ import io as _io+ import tarfile as _tarfile+ import tempfile++ from ministack.services.lambda_svc import _docker_cp_dir++ captured = {}++ class _FakeContainer:+ def put_archive(self, path, data):+ captured["path"] = path+ captured["data"] = data.read() if hasattr(data, "read") else data++ with tempfile.TemporaryDirectory() as src_dir:+ os.makedirs(os.path.join(src_dir, "python"))+ with open(os.path.join(src_dir, "python", "mod.py"), "w") as f:+ f.write("X = 1\n")++ _docker_cp_dir(_FakeContainer(), src_dir, "/opt", arcname="layer_0")++ assert captured["path"] == "/opt"+ tar_bytes = captured["data"]+ with _tarfile.open(fileobj=_io.BytesIO(tar_bytes), mode="r") as tar:+ names = tar.getnames()+ # Entries must be rooted at "layer_0/..." so extraction into /opt produces /opt/layer_0/...+ assert any(n.startswith("layer_0/python") or n == "layer_0/python/mod.py" for n in names), names+ assert "layer_0" in names or any(n.startswith("layer_0/") for n in names)+++def test_lambda_pool_kill_function_reaps_all_qualifiers():+ """_pool_kill_function must remove every pooled docker container for a+ function across all qualifiers (the pool key includes CodeSha256, so+ config-only updates leave stale entries unless explicitly reaped). Issue+ #816 docker-executor follow-up. Wired into _update_config / _delete_function+ so layer attach via UpdateFunctionConfiguration displaces the pre-attach+ container before the next invoke."""+ from ministack.services import lambda_svc as _svc++ class _StubContainer:+ def __init__(self):+ self.stopped = False+ self.removed = False+ def stop(self, timeout=2):+ self.stopped = True+ def remove(self, force=False):+ self.removed = True++ stubs = [_StubContainer() for _ in range(3)]+ keys = [+ "111122223333:fn-A:zip:sha-v1",+ "111122223333:fn-A:zip:sha-v2",+ "111122223333:fn-B:zip:sha-v1", # different function — must NOT be touched+ ]+ with _svc._warm_pool_lock:+ for k, s in zip(keys, stubs):+ _svc._warm_pool.setdefault(k, []).append(+ {"container": s, "tmpdir": None, "in_use": False,+ "last_used": 0, "created": 0}+ )++ try:+ _svc._pool_kill_function("111122223333", "fn-A")++ with _svc._warm_pool_lock:+ assert _svc._warm_pool.get("111122223333:fn-A:zip:sha-v1", []) == []+ assert _svc._warm_pool.get("111122223333:fn-A:zip:sha-v2", []) == []+ # fn-B must be untouched+ assert len(_svc._warm_pool.get("111122223333:fn-B:zip:sha-v1", [])) == 1++ assert stubs[0].stopped and stubs[0].removed, "fn-A v1 container not killed"+ assert stubs[1].stopped and stubs[1].removed, "fn-A v2 container not killed"+ assert not stubs[2].stopped, "fn-B container was killed (should be untouched)"+ finally:+ # Clean up any leftover stub entries so this test doesn't pollute siblings.+ with _svc._warm_pool_lock:+ for k in keys:+ _svc._warm_pool.pop(k, None)++def test_lambda_function_with_layer_reports_real_code_size(lam):"""GetFunctionConfiguration.Layers[*].CodeSize must mirror the layer'sactual zip size, not hardcoded 0 (issue #816)."""