Repository navigation
fix(local): make port publishing usable when SAM CLI runs in a container - #9290
Conversation
10ea681 to
f6e2baa
Compare
f6e2baa to
c80ffa8
Compare
c80ffa8 to
5d5b540
Compare
5d5b540 to
4a01860
Compare
4a01860 to
7a4afbc
Compare
7a4afbc to
c74ff48
Compare
c74ff48 to
06c8300
Compare
🧪 Hands-on test: No problems observed in 8 scenariosCommit Scenarios
Runner's notes in full
🤖 Automated hands-on test — not a review approval · model claude-opus-5.5 · Kiro kiro-cli 2.33.1 · build History (9)
|
There was a problem hiding this comment.
🧪 Hands-on test reproduced 2 new problems on commit 06c8300. Commands and evidence are in the hands-on comment.
- [REGRESSION] Unavailable --container-host-interface now ends in a raw docker APIError traceback and bug-report prompt instead of a clean 'Error:' line · medium · samcli/local/docker/container.py:456
- [BUG] Daemon-side port collision on the unprobed port escapes as docker.errors.APIError, not PortAlreadyInUse · medium · samcli/local/docker/utils.py:87
🤖 Automated hands-on test — not a review approval
06c8300 to
16faedb
Compare
There was a problem hiding this comment.
🧪 Hands-on test reproduced 2 new problems on commit 16faedb. Commands and evidence are in the hands-on comment.
- [UX] Non-existent --container-host-interface now ends in a raw docker APIError traceback and 'unexpected error' bug-report prompt instead of a clean error · low · samcli/local/docker/container.py:456
- [REGRESSION] find_free_port lets UnicodeError escape for an un-encodable interface (64-char label); CLI now shows an 'unexpected error' traceback where base gave a one-line error · low · samcli/local/docker/utils.py:118
🤖 Automated hands-on test — not a review approval
There was a problem hiding this comment.
🧪 Hands-on test reproduced 2 new problems on commit 4ecd895. Commands and evidence are in the hands-on comment.
- [BUG] Non-local --container-host-interface now ends in a raw docker APIError traceback instead of a clean error · medium · samcli/local/docker/container.py:456
- [REGRESSION] find_free_port('') no longer probes all interfaces; it returns an unprobed port with a misleading 'address does not exist' warning · low · samcli/local/docker/utils.py:117
🤖 Automated hands-on test — not a review approval
There was a problem hiding this comment.
🧪 Hands-on test reproduced 1 new problem on commit 93d81de. Commands and evidence are in the hands-on comment.
- [UX] Unprobed --container-host-interface that the daemon cannot bind now ends in a raw docker APIError traceback and an 'unexpected error' bug-report prompt instead of a clean Error line · medium · samcli/local/docker/container.py:455
🤖 Automated hands-on test — not a review approval
When SAM CLI itself runs in a container, the Lambda RIE port is published by the Docker daemon on the daemon's host, which is a different network namespace from the one SAM CLI binds and resolves addresses in. Three problems follow, all of them reported in aws#2837: * find_free_port() probed the requested interface inside SAM CLI's own network namespace. An interface that does not exist locally (for example the docker bridge gateway) failed every candidate with EADDRNOTAVAIL and raised NoFreePortsError, reporting 4000 ports busy when none of them were. That interface cannot be probed from here at all, so it now returns a port unprobed and says so, and the daemon's own bind decides whether the port is really free. This makes --container-host-interface <bridge gateway> work as the narrow alternative to 0.0.0.0. Both numbers the condition arrives under are matched: POSIX EADDRNOTAVAIL and Winsock WSAEADDRNOTAVAIL (10049), which is what errno carries on Windows. * A non-loopback --container-host combined with the default --container-host-interface 127.0.0.1 publishes the port where the given container host cannot reach it. The invoke then failed 20 seconds later with a connection timeout that named neither flag and suggested raising the timeout. SAM CLI now warns at startup, naming both flags and what to pass. * --docker-network host was accepted and silently ignored: the value is special-cased to skip the network attach, and nothing applies host networking, so containers stay on the default bridge. SAM CLI now warns that the flag has no effect. Both startup checks warn rather than fail: neither combination is broken on every Docker setup, and working configurations that pass these flags today keep running unchanged. The free-port probe resolves the requested address before binding it, so an IPv6 value is probed on an IPv6 socket rather than failing address resolution on an AF_INET one, and an IPv6 scope id (fe80::1%eth0) survives into the bind. Resolving once instead of per candidate also means a value that does not resolve here is reported unprobed immediately rather than after a full scan. The unprobeable-interface warning does not promise a named port-allocation error: mapping the engine's refusal to PortAlreadyInUse lives in Container.start, which this change does not touch. Both new warnings and the find_free_port docstring are worded for "the container engine" rather than for Docker, since SAM CLI drives Docker or Finch through get_validated_container_client and either can be the engine publishing the port.
getaddrinfo idna-encodes the name before resolving it and raises UnicodeError for a label over 63 characters. UnicodeError is a ValueError, not an OSError, so switching the probe to getaddrinfo let a mistyped --container-host-interface escape find_free_port as a traceback where it used to be a one-line error. The same defect was fixed in _resolves_to_loopback earlier in this change; this is the sibling path. The test uses a real 64-character label rather than a mock, because the exception type is the whole point and a mock cannot show it. Found by the hands-on runner on 16faedb.
…erface
An empty interface means "all interfaces", and the old bind(("", port)) probed
it for real. socket.getaddrinfo("") raises gaierror even with AI_PASSIVE, so
moving the probe to getaddrinfo sent the wildcard down the unprobeable path and
warned that an empty address "does not exist on this machine".
Converting an empty value to None with AI_PASSIVE resolves to the wildcard, so
the wildcard is probed again as it was before. AI_PASSIVE is ignored for any
non-empty host, and binding 0.0.0.0, 127.0.0.1, localhost and ::1 is unchanged.
Found by the hands-on runner on 4ecd895.
93d81de to
0b8b890
Compare
|
Rebased onto The conflict was #9294 landing. Both PRs added a test class at the same point in Two things this changes for reviewers:
Gates on the rebased head: 9796 unit tests passing, coverage 94.10% against the 94% floor, |
… certainty The warning fired for the configuration --container-host's own help suggests for macOS (host.docker.internal with the interface left at 127.0.0.1) and told those users invocations "will time out". Whether a loopback-bound port is reachable through the given container host depends on the engine: it is not on a Linux engine, which is where the reproduction matrix was measured, but that combination can work on Docker Desktop. The diagnosis and the remedy are unchanged; only the certainty is dropped. The message now leads with "if invocations time out while connecting to the container, this is the likely cause", so it no longer pushes a working macOS setup towards 0.0.0.0 and its all-interfaces exposure for no reason. A test asserts the message does not promise a timeout.
…y resolves first
getaddrinfo(None, AI_PASSIVE) returns both wildcards and their ORDER IS
PLATFORM-DEPENDENT: IPv4 first on Linux, IPv6 first on macOS. Taking the first
entry therefore probed a different family per platform. On macOS, whose stacks
are separate by default (ip6.v6only=1), a bind on the IPv6 wildcard succeeds
while the IPv4 wildcard is already taken, so the probe reported free a port the
engine then could not publish. Linux hid this because bindv6only=0 makes the
IPv6 wildcard bind fail when the IPv4 one is held.
An empty interface is now probed on AF_INET with bind(("", port)) and nothing is
resolved for it, which is exactly what this function did before it resolved
anything. getaddrinfo is kept for named and literal addresses, where picking the
family and carrying an IPv6 scope id is the whole point.
EAFNOSUPPORT joins the errnos that short the scan: creating an AF_INET6 socket
raises it on a host booted with IPv6 disabled, and like EADDRNOTAVAIL the answer
is the same for every candidate port, so scanning 1000 of them to end in
NoFreePortsError was wrong.
The probe socket is closed with `with` on the failing path too. It leaked before
on every candidate that did not bind, which surfaced as ResourceWarnings; the
suite now passes under -W error::ResourceWarning.
Tests: the empty-interface test no longer pins a candidate port, so it does not
fail on a machine already holding 3093 (reproduced, and it did). A second test
asserts the family and bind address through a mock, so the platform-ordering
regression is caught on every platform rather than only on macOS.
Reported by a macOS reviewer; items 1, 2 and 3 of that review.
… not loopback _resolves_to_loopback(container_host) ran before the interface check, so every sam local run paid a DNS lookup just to decide whether to warn. The interface is normally an IP literal and costs a parse, so checking it first short-circuits the lookup away for every run that cannot produce the warning. Item 7 of the macOS review.
EAFNOSUPPORT joined the unprobeable errnos, but the warning still said the address "does not exist on this machine, probably because the container engine runs elsewhere". For an IPv6 --container-host-interface on a host booted with IPv6 off, both halves are wrong: the address does exist, and the engine is local. The warning now says the address cannot be probed from this machine and offers both causes as possibilities rather than one as a likelihood. Also adds the case that was missing: EAFNOSUPPORT is raised when the AF_INET6 socket is CREATED, so it never reaches bind, and no test covered that path.
… on Windows EAFNOSUPPORT was added to UNPROBEABLE_ERRNOS by errno constant only, which is the same gap WSAEADDRNOTAVAIL already covers for the other code. CPython's winerror_to_errno returns a Winsock code unchanged apart from six low-numbered ones, so a socket error on Windows carries 10047, never errno.EAFNOSUPPORT (102 there). A Windows host with IPv6 off and an IPv6 --container-host-interface therefore fell through to the full scan and ended in NoFreePortsError. The new test case is parameterized over both spellings, so the Winsock value is pinned on every platform rather than only where it can be reproduced.
There was a problem hiding this comment.
Thanks for working on this, and for splitting out #9294.
Optional: ports returned unprobed aren't tracked, so two containers started in the same process (warm containers, several functions) can draw the same port and the second publish fails. Remembering the ones already handed out and redrawing would avoid that.
Nit: .partition("%")[0] in _resolves_to_loopback is redundant, since ipaddress has accepted scope ids since Python 3.9.
Which issue(s) does this change fix?
#2837
Why is this change necessary?
When SAM CLI runs inside a container (the docker-out-of-docker setup people use with Compose), the Lambda RIE port is published by the container engine (Docker or Finch) on that engine's host, while SAM CLI binds and resolves addresses in its own network namespace. Those are different machines as far as addresses are concerned, and three separate things go wrong because of it. I reproduced all of them on 1.166.2 and posted the full matrix in #2837:
--docker-network--container-host--container-host-interfacehost.docker.internal127.0.0.1)host.docker.internal0.0.0.0localhost)0.0.0.0hosthost.docker.internalhost.docker.internal240.10.0.1(bridge gateway)NoFreePortsErrorArm H —
find_free_port()probes the requested interface with a localbind(). A daemon-host address that does not exist inside SAM CLI's container fails withEADDRNOTAVAILfor every candidate, so all 4000 ports are reported busy when none of them are:This is what forces
--container-host-interface 0.0.0.0as the only working value, which publishes the RIE invoke endpoint on every interface of the machine running the container engine.Arms A, D, F — a non-loopback
--container-hostwith the default--container-host-interface 127.0.0.1is self-contradictory: the port is published where the named container host cannot reach it. The failure arrives 20 s later asTimed out while attempting to establish a connection to the container… increase this timeout by setting SAM_CLI_CONTAINER_CONNECTION_TIMEOUT, which names neither flag and points at a timeout that cannot help.Arms F and G —
--docker-network hostis accepted and does nothing.Container.create()special-cases the value to skip the attach, andnetwork_modeappears nowhere insamcli/, so containers are created on the default bridge:Users pass it expecting host networking, and conclusions in the issue thread were drawn from changing a flag that has no effect.
How does it address the issue?
samcli/local/docker/utils.py— an interface that does not exist in this network namespace cannot be probed from here, and a bind against local interfaces would say nothing about the daemon host anyway. So on "address not available" the probe stops instead of widening: it returns the candidate port unprobed and warns that it did, and the daemon's own bind decides whether the port is free. That warning deliberately asks for nothing — for a remote daemon no interface is both bindable here and publishable where--container-hostcan reach it, so telling the user to change the flag would contradict the other new warning.EADDRINUSEstill scans the range as before. A named or literal address is resolved throughsocket.getaddrinfobefore binding, so an IPv6 value is probed on an IPv6 socket instead of failing resolution on anAF_INETone and a scope id (fe80::1%eth0) survives into the bind; a value that does not resolve here is returned unprobed rather than costing a full scan. The empty interface ("all interfaces") is probed onAF_INETwithbind(("", port))and is not resolved at all:getaddrinfo(None, AI_PASSIVE)returns both wildcards and their order is platform-dependent (IPv4 first on Linux, IPv6 first on macOS), and on macOS — whose stacks are separate by default — an IPv6 wildcard bind succeeds while the IPv4 wildcard is taken, reporting free a port the engine then cannot publish. The short-circuit coversEADDRNOTAVAIL, its Winsock spellingWSAEADDRNOTAVAIL(10049, which is whaterrnocarries on Windows because CPython'swinerror_to_errnopasses Winsock codes through unchanged), andEAFNOSUPPORT, which creating anAF_INET6socket raises on a host booted with IPv6 disabled.samcli/commands/local/cli_common/invoke_context.py— two startup warnings in__enter__(alongside the existing--no-watchprecedent): one when--container-hostdoes not resolve to loopback while--container-host-interfacedoes, naming both flags and what to pass; one when--docker-network hostis supplied, saying it is ignored.Handing back an unprobed port means a daemon-side collision is now possible where the local probe used to catch it, and
Container.startused to mistranslate two of the three ways an engine reports one. That was fixed separately in #9294, which has now merged (1eee817), so the mapping this change depends on is ondevelopalready. It was split out of this PR during review so that an error-taxonomy change to a handler everysam localcommand shares got reviewed on its own, and it had to land first: with this change alone, an interface that exists neither locally nor on the engine's host (a stale192.0.2.1, say) stopped failing asError: No free ports on the host machine from 5000 to 9000and instead reached the engine, whosecannot assign requested addressrefusal escaped the unmapped handler as a rawdocker.errors.APIErrortraceback. That ordering requirement is now satisfied, and the hands-on finding about that traceback is resolved bydeveloprather than by anything in this PR.Verified against the original reproduction with the patched files mounted over an installed 1.166.2:
arm H:
NoFreePortsError→ HTTP 200, preceded byCannot check whether ports are free on 240.10.0.1: that address does not exist on this machine….--container-host-interface <bridge gateway>is now a working, non-exposing alternative to0.0.0.0.arm A: still 502 on this Linux engine, where a loopback-bound port genuinely is unreachable through
host.docker.internal, but now preceded by--container-host is host.docker.internal while the Lambda container's port is published on 127.0.0.1, a loopback address of the machine running the container engine. If invocations time out while connecting to the container, this is the likely cause… Passing --container-host-interface with an address reachable from host.docker.internal, such as the bridge gateway, resolves it. 0.0.0.0 works too but publishes the container's unauthenticated invoke endpoint on every interface of the machine running the container engine.The message states a likely cause rather than a certain outcome, because whether a loopback-bound port is reachable through the given container host depends on the engine.
--container-host's own help suggestshost.docker.internalfor running SAM CLI in a container on macOS, and that combination can work on Docker Desktop, which is not covered by this matrix — so promising a timeout would be wrong there and would push those users to0.0.0.0for no reason.Both new warnings and the
find_free_portdocstring are worded for "the container engine" rather than for Docker: SAM CLI drives Docker or Finch throughget_validated_container_client, and either can be the engine publishing the port. A test asserts the warning names no single engine.arm F: 200, preceded by
--docker-network host has no effect and is ignored…What side effects does this change have?
--docker-network hostis inert rather than harmful, so configurations that pass these flags today keep working exactly as they do now. Nothing becomes an error.socket.getaddrinfo, so IPv4 and IPv6 alike) and treats a name as loopback when any resolved address is, so a container host that legitimately points at loopback produces no warning. An unresolvable hostname is treated as non-loopback and warns, which is the right call — it is not reachable either.find_free_portbehaviour is unchanged when the interface exists locally, which is every host install. Only the errnos meaning "this address cannot be probed here at all" short-circuit —EADDRNOTAVAIL, its Winsock spelling, andEAFNOSUPPORT;EADDRINUSEscans the range as it always did. In the short-circuit case the returned port is unverified by design, and the warning says so: it states that the engine refuses the publish and the command fails naming that port. With fix(local): report a taken host port instead of a raw APIError #9294 ondevelop, that refusal is now mapped to a namedPortAlreadyInUseorContainerNotStartableExceptionrather than a rawAPIError.--docker-network hoststill does not give host networking. Honouring it would mean every Lambda container sharing the host namespace and competing for RIE's fixed 8080, so warning is the safe half of the fix; if we want to support it, that deserves its own change.Mandatory Checklist
make prpassesmake update-reproducible-reqsif dependencies were changed — no dependency changesBy submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.