Skip to content

fix(dockerutil): stop hijacking the exec stream in Exec(), avoids a hang on socktainer - #8660

Closed
rfay wants to merge 2 commits into
ddev:mainfrom
rfay:20260802_rfay_dockerutil_exec_no_hijack
Closed

rfay wants to merge 2 commits into
ddev:mainfrom
rfay:20260802_rfay_dockerutil_exec_no_hijack

Conversation

@rfay

@rfay rfay commented Aug 3, 2026

Copy link
Copy Markdown
Member

The Issue

dockerutil.Exec() hangs indefinitely against socktainer (the
Docker-compatible API in front of Apple Container), even for a trivial
echo hi — while docker exec on the same container returns in well
under a second. This affects, among other callers, GetRouterConfigErrors().

Traced at the raw HTTP/socket level: ExecAttach() (used internally by
Exec()) always upgrades the connection to a hijacked raw stream and
relies on the daemon closing that connection once the exec process exits,
which is what lets stdcopy.StdCopy see EOF and return. Real dockerd
does this; socktainer delivers the command's output correctly over the
hijacked stream (confirmed byte-for-byte, correct multiplexed-stream
framing) but never closes the connection afterward, so stdcopy.StdCopy
blocks forever waiting for a close that never comes.

This is arguably a socktainer bug (RFC-wise, a daemon should close a
hijacked exec stream on process exit), but dockerutil.Exec() never
attaches stdin and doesn't need the hijacked/bidirectional stream at all —
it only needs to capture output — so avoiding the hijack path entirely is
a reasonable hardening on the DDEV side regardless of which daemon is on
the other end.

How This PR Solves The Issue

Replaced the ExecAttach() + stdcopy.StdCopy call with
execStartAndCapture(), which POSTs to /exec/{id}/start as a plain
(non-upgraded) request instead of requesting the hijack, reusing the
existing client's Dialer()/ClientVersion() so it still goes through
whatever transport the client was configured with, then demuxes the
chunked response body the same way stdcopy.StdCopy always has.
ExecCreate() and ExecInspect() are untouched — only the start+capture
step changes.

Manual Testing Instructions

Confirmed against the real API on both providers, including multi-frame
output large enough to need several chunks:

  • socktainer: echo hi went from hanging (2+ min, killed) to 787ms;
    stdout/stderr separation, non-zero exit codes, and 5000 lines of output
    (23893 bytes) all came back correct and fast.
  • OrbStack: identical behavior and timing for the same three cases — this
    isn't a socktainer-only code path, it's how Exec() always starts execs
    now.

Automated Testing Overview

No new test file — the existing TestDockerExec in
pkg/dockerutil/containers_test.go already exercises both the
success and error-output cases through the public Exec() function and
needed no changes; it passed against both providers. Also ran the full
pkg/dockerutil suite against OrbStack (clean pass) to check for
regressions beyond Exec() itself.

Release/Deployment Notes

None. Pure pkg/dockerutil change, no image dependency.

…ang on socktainer

While fixing GetExistingDBType() for ddev#7372, its new fast path (exec into an
already-running db container instead of re-mounting its volume) hung
indefinitely on socktainer (the Docker-compatible API in front of Apple
Container). Isolating it down: dockerutil.Exec() itself hangs there, even
for a trivial `echo hi` - while `docker exec` on the same container
returns in well under a second.

Traced it to the raw byte level against socktainer's Unix socket.
ExecAttach() (used internally by Exec()) always upgrades the connection to
a hijacked raw stream - its own doc comment says so - and relies on the
daemon closing that connection once the exec process exits, which is what
lets stdcopy.StdCopy see EOF and return. Real dockerd does this. socktainer
doesn't: the hijacked connection delivers the command's actual output
correctly (confirmed byte-for-byte, correct multiplexed-stream framing)
and then just sits open indefinitely, so stdcopy.StdCopy blocks forever
waiting for a close that never comes, well after the command has already
finished and all its output has already arrived.

Also traced (still via raw bytes) that POSTing to the same
`/exec/{id}/start` endpoint *without* requesting the hijack upgrade gets a
normal HTTP response instead: `Transfer-Encoding: chunked`,
`Content-Type: application/vnd.docker.multiplexed-stream`, same frame
format, and it terminates correctly - dockerd (and socktainer) close out
the chunked body on process exit even though socktainer won't close the
raw hijacked connection. This is the same request shape used whenever a
client doesn't attach stdin, which is always true for dockerutil.Exec() -
it has no stdin parameter.

Replaced the ExecAttach()+stdcopy.StdCopy call with execStartAndCapture(),
which POSTs to /exec/{id}/start as a plain (non-upgraded) request - reusing
the existing client's Dialer()/ClientVersion() so it still goes through
whatever transport (unix socket, TCP, TLS) the client was configured with -
and demuxes the chunked response body the same way. ExecCreate() and
ExecInspect() are untouched; only the start+capture step changes.

Confirmed against the actual API on both providers (not just via the
public Exec() test), including multi-frame output large enough to need
several chunks:
  - socktainer: `echo hi` went from hanging (2+ min, killed) to 787ms;
    stdout/stderr separation, non-zero exit codes, and 5000 lines of
    output (23893 bytes) all came back correct and fast.
  - OrbStack: identical behavior and timing for the same three cases -
    this is not a socktainer-only code path, it's how Exec() always
    starts execs now.
Also ran the full pkg/dockerutil suite against OrbStack (clean pass) to
check for regressions beyond Exec() itself.

TestDockerExec (existing, exercises both the success and error-output
cases through the public Exec() function) needed no changes and passed
against both providers.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@github-actions github-actions Bot added the bugfix label Aug 3, 2026
@github-actions

github-actions Bot commented Aug 3, 2026 •

Copy link
Copy Markdown

…ort, fixes goroutine leak

execStartAndCapture() (added in 7c892a9 to stop hijacking the exec
stream) builds a brand-new *http.Transport for every dockerutil.Exec()
call and then discards it. With keep-alives left on and IdleConnTimeout
at its zero-value default (no limit), the connection goes back into
that Transport's idle pool after the response is read - but nothing
ever reuses or closes it, so its readLoop/writeLoop goroutines are
parked forever.

Confirmed against PR ddev#8660's buildkite/ddev-macos-arm64-mutagen
failure (goroutines=15/17 vs the CheckGoroutineOutput limit of 10,
in TestCmdSnapshotRestore and TestCmdStart): that job is the one
macOS run configured with DOCKER_TYPE=docker-desktop
(.buildkite/macos-docker-desktop-arm64.yml), while macos-orbstack,
macos-lima, and macos-colima-vz all passed. Docker Desktop's proxied
socket apparently holds the keep-alive connection open, so the leaked
goroutines accumulate; OrbStack/Lima/Colima close it fast enough that
they don't. Reproduced locally: 100 Exec() calls against OrbStack
leaked 0 goroutines even pre-fix, matching macos-orbstack passing -
this is backend-dependent, not proof the leak was OrbStack-specific.

The race-detection GitHub Actions job (real dockerd on Linux) also
runs this same goroutine-count assertion and passed - go test -race
only catches data races, not idle goroutines, so it was never able to
catch this class of bug regardless of platform.

Setting DisableKeepAlives on the per-call Transport makes the client
close its own connection right after reading the response instead of
relying on the daemon/proxy to do it, removing the backend-dependent
timing entirely.
@rfay

rfay commented Aug 11, 2026

Copy link
Copy Markdown
Member Author

Closing this for now. Re-checking it against the actual Docker Engine API spec and the moby daemon source, the rationale in the code comment doesn't hold up, and the change turns out to be a no-op against real Docker.

What the daemon actually does

daemon/server/router/container/exec.go, postContainerExecStart:

if !options.Detach {
    inStream, outStream, err = httputils.HijackConnection(w)   // hijacks either way
    defer httputils.CloseStreams(inStream, outStream)
    if _, ok := r.Header["Upgrade"]; ok {
        ... "HTTP/1.1 101 UPGRADED\r\nContent-Type: "+contentType+"\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n"
    } else {
        ... "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n"
    }
    ...
    if options.Tty { stdout = outStream } else { stderr/stdout = stdcopymux.NewStdWriter(...) }
}

dockerd hijacks the connection whenever Detach is false, regardless of the Upgrade header. The non-upgrade branch is a hand-written status line with no Content-Length and no Transfer-Encoding: chunked — identity-framed, terminated only by the daemon closing the connection, exactly like the hijacked path. swagger.yaml agrees: produces: application/vnd.docker.raw-stream / application/vnd.docker.multiplexed-stream, 200/404/409, nothing about chunking.

So two things in the PR are wrong:

  • "dockerd (and socktainer) then respond with a normal chunked HTTP response" — not for dockerd.
  • The claim that this stops relying on the daemon closing the connection — it doesn't. On dockerd, EOF still comes from the close.

Against real Docker/OrbStack this changes nine bytes of status line and nothing else, which is exactly consistent with the OrbStack timings in the PR description being identical before and after.

Also worth noting for anyone revisiting: the non-upgrade branch advertises raw-stream even when the payload is multiplexed (the content-type negotiation only exists in the Upgrade branch), so nothing on this path may switch on the response Content-Type.

Why it nevertheless sped up socktainer

The asymmetry is client-side, not daemon-side:

  • ExecAttach → postHijacked returns a raw net.Conn. stdcopy.StdCopy reads that socket directly, with no HTTP framing in play, so the only possible EOF is a close or a read error. If the peer never closes, it hangs forever — there is no timeout on that path.
  • The replacement reads through net/http's response body, which terminates on a chunked terminator, a satisfied Content-Length, or a close.

If socktainer serves the non-upgrade branch through its normal HTTP response machinery (framed) rather than a raw socket handler, net/http ends the body without needing the close socktainer never sends. That would explain 2+ min → 787ms. It's plausible but unverified — it needs a byte capture of what socktainer returns on the non-upgrade start. If the response turns out to be identity-framed and ended by a close, then socktainer just happens to close on one path and not the other, and this fix rests on an implementation accident that could regress on any socktainer update.

Separately, the hand-built request drops client behavior

Bypassing Client.buildRequest/getAPIPath loses things that matter in edge configurations:

  • basePath — getAPIPath does path.Join(cli.basePath, "/v"+version, p). With DOCKER_HOST=tcp://host:2375/prefix, ExecCreate/ExecInspect hit /prefix/v1.5x/… while exec-start hits /v1.5x/exec/…/start → 404.
  • Headers — NewAPIClientFromFlags installs configFile.HTTPHeaders, DOCKER_CUSTOM_HEADERS, and WithUserAgent(UserAgent()). We set version.Version = "ddev-" + DdevVersion in docker_manager.go specifically for that User-Agent. Behind a header-auth proxy, everything works except dockerutil.Exec, which gets 401.
  • req.Host is hardcoded docker where the client uses client.DummyHost for unix/npipe; CheckRedirect isn't set; typed errdefs errors are lost with checkResponseErr.

And the type assertion to *client.Client is unnecessary — ClientVersion(), Dialer() and DaemonHost() are all on client.APIClient. Its justifying comment is also wrong: APIClient has no unexported methods, so an embedding wrapper compiles fine and would then fail at runtime on every Exec.

Where this leaves it

If the goal is "Exec() must not hang regardless of what's on the other end," the mechanism that delivers that is a read deadline, which works on both paths and against any daemon, and can be done on top of ExecAttach (resp.Conn.SetReadDeadline) without rebuilding the request. That needs a policy call on what timeout is safe for Exec()'s callers.

The socktainer behavior — leaving a hijacked exec stream open after the process exits, when dockerd closes it — is worth reporting upstream to socktainer regardless. Related: #7372.

@rfay rfay closed this Aug 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant