You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I would like to work on this. It is invasive enough that I would rather agree on the design first.
@ChengyuZhu6 you volunteered for this one (and for #4374) a while back. If you have something in progress I am happy to review instead, or to split the work.
Diagnosis
To answer the open question in the description: it is not containerd/console, it is the FIFOs.
pkg/cmd/container/attach.go attaches with container.Task(ctx, cio.NewAttach(opt)), which re-opens the same stdio FIFOs the first session already holds. A FIFO has one queue, so with two readers the kernel hands each chunk to exactly one of them: the container's output is split at random, and one terminal appears to freeze while the other prints characters it never asked for. Two writers on the stdin FIFO interleave the same way, which is the "some characters on terminal 1, others on terminal 2" above. #4374 is the same thing with a video of it.
This was called out as a limitation in #2108, the PR that introduced attach, and is still documented as a caveat in the help text.
Proposal
Give each container a single owner of its stdio, and make every CLI session a client of it over a unix socket. The owner would be the process nerdctl already runs for the lifetime of every container: the internal logging process (_NERDCTL_INTERNAL_LOGGING, pkg/logging). It gains a socket, a fan-out of the container's raw output tapped before the log driver's line splitting, and the write end of a stdin FIFO at a stable path.
The shape is not new. podman and CRI-O put the same thing in conmon: a per-container process that owns the pty and serves an attach socket with a stream-tagged framing. containerd solves it too, in its own CRI plugin, where internal/cri/io/container_io.go fans the container's output out to every kubectl attach through cioutil.WriterGroup. That works because the plugin lives in a daemon; a daemonless CLI has to put the owner somewhere else. (One difference worth noting: WriterGroup drops a writer that errors, but writes to all of them synchronously under a mutex, so a slow consumer still blocks the container. The design below uses a bounded queue per session instead.)
Choosing the logging process rather than a helper of our own: containerd spawns it from the container's log URI, so it comes back on its own when the restart monitor recreates a task. A separate helper would not, since the restart monitor only knows the log URI, and it would need its own daemonization plus a second process per container. Doing this in the shim would be cleaner still, but that is an upstream change and would not close this issue.
Three constraints from the containerd source
These are the non-obvious ones, and they are why the design looks the way it does.
1. Who owns the stdio has to be read from containerd, not recorded by nerdctl.plugins/restart/change.go recreates a task straight from the stored log URI with no nerdctl process involved, so a container with FIFO stdio can come back with binary:// stdio between two invocations, and no marker nerdctl writes can keep up. containerd already has the answer: container.Task hands the task's Stdin/Stdout/Stderr to the cio.Attach callback. A URI in Stdout means the logging process owns the stdio, a path means FIFOs, and attach classifies and builds its IO in that one callback so nothing can change underneath. This matters anyway, because cio.NewAttach passes Stdout straight to fifo.OpenFifo as a path.
2. The socket has to live under the data store. In cmd/containerd-shim-runc-v2/process/io_util.go, NewBinaryCmd appends CONTAINER_ID and CONTAINER_NAMESPACE to a nil cmd.Env, so the logging process runs with exactly those two variables. There is no XDG_RUNTIME_DIR there and rootlessutil.XDGRuntimeDir() returns an error, so a rootless broker would have resolved /run/nerdctl/attach, failed to bind, and never served a session while its clients looked elsewhere. So it is <dataStore>/attach/<sha256(ns, id)[:16]>.sock: the data store arrives in that process's argv, and clients read it back out of the task's stdout URI rather than resolving it again. It is a flat hashed directory because sun_path is 108 bytes.
3. Stdin exists only for terminal containers, and has to be probed. For a terminal container the shim opens and drains the stdin FIFO independently of the stdout scheme (runc/platform.go, CopyConsole), so {Terminal: true, Stdin: <fifo>, Stdout: "binary://..."} works. For a non-terminal one the binary scheme sets pio.copy = false and binaryIO.Stdin() returns nil (process/io.go, createIO), which is why run -d without -t has no stdin today. Whether a running task actually has stdin is decided by opening the FIFO, not by the file existing: the file outlives the task, and O_WRONLY|O_NONBLOCK returns ENXIO while nothing holds the read end. github.com/containerd/fifo cannot answer this, since with O_NONBLOCK it strips the flag and opens in a goroutine.
I checked the terminal / non-terminal split on a live containerd (v2.2.4, runc 1.3.5, linux/arm64) with a throwaway program playing the broker. With Terminal: true the injected input reached the shell and the task exited 0; with false zero bytes reached the logging process and the shell saw EOF immediately. The scope boundary below is measured, not assumed.
With no sessions attached, the broker keeps draining. Today, after a detach nobody reads the stdout FIFO and the container stalls once the pipe buffer fills.
No replay buffer.run and start -a connect before task.Start(), so nothing is produced with nobody attached. attach shows no history, matching Docker.
A session is told the container exited only when containerd has said so. The owner's own stdio reaching EOF is not evidence: the same happens when the logging process is shut down while the container runs, and a client treats the message as proof.
An unexpected disconnect is an error, not a detach. Otherwise a dead broker looks like the user pressing the detach keys and the command exits 0.
Detach keys, resize, signal forwarding and the exit code stay client side and unchanged; the exit code always comes from task.Wait.
Scope and compatibility
Full multiplexing for TTY containers, foreground and detached. Attaching to nerdctl run -d starts working with and without -t, since non-TTY output already goes through cio.LogURI; stdin from a session does not, because of pio.copy = false above, and would be a follow-up.
A container whose task has FIFO stdio keeps today's single-session behaviour, which covers containers created before the change. One whose output went to a logging process nerdctl cannot reach, a custom --log-driver binary:// or a detached container on a platform without the transport, says so instead of failing inside fifo.OpenFifo; that path fails today too, only the message is new. The broker builds for linux and freebsd; Windows keeps current behaviour until the transport is done over named pipes.
One known gap: after a restart-monitor restart the sessions are output only, because cio.TerminalLogURI carries no Stdin. Not a regression, since such a container has no stdin today either, but closing it needs the restart monitor to preserve the whole IO config. Happy to raise that upstream separately.
Staging
Five separately mergeable PRs:
pkg/attachmux: broker, client, framing. New package, no existing file touched, unit tested without containerd. Roughly two thirds of the diff.
Broker inside the logging process, stable stdin.fifo. No user-visible change yet.
--log-driver none would now still spawn the internal logging process, since that is where the broker lives. none is already a registered no-op, so nothing is written, but it is one more process per container. Acceptable?
Socket location.<dataStore>/attach/<digest>.sock, for the reason in constraint 2. Is there a convention you would prefer that still satisfies it?
Step 4 changes the foreground run -it stdio path, which is well trodden. Same release as the rest, or behind the current path for a cycle?
One thing I should have covered in the proposal above: how to back this out.
There is no rollback once a task exists. Its Stdout is a binary:// URI, and cio.NewAttach opens that value as a FIFO path, so a container already running under the broker cannot be moved back. The choice therefore has to be made when the task is created, and an operator has to be able to make it.
So step 2 adds disable_attach_broker, reaching the same switch through --disable-attach-broker, NERDCTL_DISABLE_ATTACH_BROKER and nerdctl.toml, via the same AddPersistentBoolFlag helper the other global options use. Off by default.
The name is negative on purpose. This is not a feature switch but a way to back the change out in the field without a downgrade, and I would expect it to be removed once the broker has proven itself. disable_hc_systemd seemed like the closest precedent.
It needs no new code paths: it leaves the data store empty at task creation, which every branch already handles, because that is also what a container with a foreign log driver looks like. The fallbacks were already there and tested; this just lets an operator take them deliberately.
It also answers question 2 above. With the switch on, --log-driver none short-circuits the way it does today, so a container that asked for no logs runs with no logging process at all, and the extra process per container is opt-out rather than unconditional.
The limitation worth stating plainly: containers already running are unaffected, since their stdio is bound. Backing the change out means switching it off and restarting them. That is in the flag's help text and in docs/config.md.
Step 1 is up as #5168 - the pkg/attachmux package on its own, no existing file touched. Step 2 is ready behind it.
GitHub will not let me stack these against this repo, since a pull request's base branch has to live here rather than in my fork, so each step has to wait for the previous one to merge. That is five round trips for something that is one change.
Would you rather have it that way, or fewer, larger pull requests with the commits kept separate? I split it because step 1 is two thirds of the diff and needs no containerd at all to review, while step 4 is the one that touches the well trodden foreground run -it path. But if reviewing five in sequence is worse for you than reviewing one with a readable history, say so and I will collapse it. This is related to question 4 above, but not the same: that one was about which release the foreground change lands in.
Activity
apostasie commentedon Feb 22, 2025
Note this was actually explicitly mentioned as a limitation in the original PR introducing attach: #2108
[-]attach on a container with tty seems broken[/-][+]Multiple attach should be supported[/+]apostasie commentedon Jun 25, 2025
@AkihiroSuda + feature
ChengyuZhu6 commentedon Jul 2, 2025
@apostasie @AkihiroSuda I‘d like to take it on.
ekalinin commentedon Aug 31, 2026
I would like to work on this. It is invasive enough that I would rather agree on the design first.
@ChengyuZhu6 you volunteered for this one (and for #4374) a while back. If you have something in progress I am happy to review instead, or to split the work.
Diagnosis
To answer the open question in the description: it is not
containerd/console, it is the FIFOs.pkg/cmd/container/attach.goattaches withcontainer.Task(ctx, cio.NewAttach(opt)), which re-opens the same stdio FIFOs the first session already holds. A FIFO has one queue, so with two readers the kernel hands each chunk to exactly one of them: the container's output is split at random, and one terminal appears to freeze while the other prints characters it never asked for. Two writers on the stdin FIFO interleave the same way, which is the "some characters on terminal 1, others on terminal 2" above. #4374 is the same thing with a video of it.This was called out as a limitation in #2108, the PR that introduced
attach, and is still documented as a caveat in the help text.Proposal
Give each container a single owner of its stdio, and make every CLI session a client of it over a unix socket. The owner would be the process nerdctl already runs for the lifetime of every container: the internal logging process (
_NERDCTL_INTERNAL_LOGGING,pkg/logging). It gains a socket, a fan-out of the container's raw output tapped before the log driver's line splitting, and the write end of a stdin FIFO at a stable path.The shape is not new. podman and CRI-O put the same thing in
conmon: a per-container process that owns the pty and serves an attach socket with a stream-tagged framing. containerd solves it too, in its own CRI plugin, whereinternal/cri/io/container_io.gofans the container's output out to everykubectl attachthroughcioutil.WriterGroup. That works because the plugin lives in a daemon; a daemonless CLI has to put the owner somewhere else. (One difference worth noting:WriterGroupdrops a writer that errors, but writes to all of them synchronously under a mutex, so a slow consumer still blocks the container. The design below uses a bounded queue per session instead.)Choosing the logging process rather than a helper of our own: containerd spawns it from the container's log URI, so it comes back on its own when the restart monitor recreates a task. A separate helper would not, since the restart monitor only knows the log URI, and it would need its own daemonization plus a second process per container. Doing this in the shim would be cleaner still, but that is an upstream change and would not close this issue.
Three constraints from the containerd source
These are the non-obvious ones, and they are why the design looks the way it does.
1. Who owns the stdio has to be read from containerd, not recorded by nerdctl.
plugins/restart/change.gorecreates a task straight from the stored log URI with no nerdctl process involved, so a container with FIFO stdio can come back withbinary://stdio between two invocations, and no marker nerdctl writes can keep up. containerd already has the answer:container.Taskhands the task'sStdin/Stdout/Stderrto thecio.Attachcallback. A URI inStdoutmeans the logging process owns the stdio, a path means FIFOs, andattachclassifies and builds its IO in that one callback so nothing can change underneath. This matters anyway, becausecio.NewAttachpassesStdoutstraight tofifo.OpenFifoas a path.2. The socket has to live under the data store. In
cmd/containerd-shim-runc-v2/process/io_util.go,NewBinaryCmdappendsCONTAINER_IDandCONTAINER_NAMESPACEto a nilcmd.Env, so the logging process runs with exactly those two variables. There is noXDG_RUNTIME_DIRthere androotlessutil.XDGRuntimeDir()returns an error, so a rootless broker would have resolved/run/nerdctl/attach, failed to bind, and never served a session while its clients looked elsewhere. So it is<dataStore>/attach/<sha256(ns, id)[:16]>.sock: the data store arrives in that process's argv, and clients read it back out of the task's stdout URI rather than resolving it again. It is a flat hashed directory becausesun_pathis 108 bytes.3. Stdin exists only for terminal containers, and has to be probed. For a terminal container the shim opens and drains the stdin FIFO independently of the stdout scheme (
runc/platform.go,CopyConsole), so{Terminal: true, Stdin: <fifo>, Stdout: "binary://..."}works. For a non-terminal one thebinaryscheme setspio.copy = falseandbinaryIO.Stdin()returns nil (process/io.go,createIO), which is whyrun -dwithout-thas no stdin today. Whether a running task actually has stdin is decided by opening the FIFO, not by the file existing: the file outlives the task, andO_WRONLY|O_NONBLOCKreturnsENXIOwhile nothing holds the read end.github.com/containerd/fifocannot answer this, since withO_NONBLOCKit strips the flag and opens in a goroutine.I checked the terminal / non-terminal split on a live containerd (v2.2.4, runc 1.3.5, linux/arm64) with a throwaway program playing the broker. With
Terminal: truethe injected input reached the shell and the task exited 0; withfalsezero bytes reached the logging process and the shell saw EOF immediately. The scope boundary below is measured, not assumed.Invariants
Each of these is a bug today:
nerdctl runwith attached stdio stops draining container stdout at ~72 KiB, deadlocking the container (nerdctl 2.3.5, containerd 2.3.3, Kata runtime-rs) #5137 / Fix foreground stdio deadlock when the internal logging process stops consuming #5151.runandstart -aconnect beforetask.Start(), so nothing is produced with nobody attached.attachshows no history, matching Docker.Detach keys, resize, signal forwarding and the exit code stay client side and unchanged; the exit code always comes from
task.Wait.Scope and compatibility
Full multiplexing for TTY containers, foreground and detached. Attaching to
nerdctl run -dstarts working with and without-t, since non-TTY output already goes throughcio.LogURI; stdin from a session does not, because ofpio.copy = falseabove, and would be a follow-up.A container whose task has FIFO stdio keeps today's single-session behaviour, which covers containers created before the change. One whose output went to a logging process nerdctl cannot reach, a custom
--log-driver binary://or a detached container on a platform without the transport, says so instead of failing insidefifo.OpenFifo; that path fails today too, only the message is new. The broker builds for linux and freebsd; Windows keeps current behaviour until the transport is done over named pipes.One known gap: after a restart-monitor restart the sessions are output only, because
cio.TerminalLogURIcarries noStdin. Not a regression, since such a container has no stdin today either, but closing it needs the restart monitor to preserve the whole IO config. Happy to raise that upstream separately.Staging
Five separately mergeable PRs:
pkg/attachmux: broker, client, framing. New package, no existing file touched, unit tested without containerd. Roughly two thirds of the diff.stdin.fifo. No user-visible change yet.attachfollows the task's IO configuration to the socket or to the FIFOs. This is whereTestAttachMultipleSessionsstarts passing andnerdctl attachfreezes the terminal sessions randomly. #4374 closes.run -it/start -abecome socket clients; the branches intaskutil.NewTaskcollapse.attachhelp text.Questions before I start
TestLogs*) #5006,nerdctl runwith attached stdio stops draining container stdout at ~72 KiB, deadlocking the container (nerdctl 2.3.5, containerd 2.3.3, Kata runtime-rs) #5137). If you would rather keep logging and stdio ownership separate, that changes the design substantially.--log-driver nonewould now still spawn the internal logging process, since that is where the broker lives.noneis already a registered no-op, so nothing is written, but it is one more process per container. Acceptable?<dataStore>/attach/<digest>.sock, for the reason in constraint 2. Is there a convention you would prefer that still satisfies it?run -itstdio path, which is well trodden. Same release as the rest, or behind the current path for a cycle?pkg/cioutil,pkg/logging). I would rather rebase on top of it than conflict. Is it close to merging?Happy to open a draft PR for step 1 so the framing and the broker can be reviewed in isolation before anything touches the container paths.
ekalinin commentedon Sep 2, 2026
One thing I should have covered in the proposal above: how to back this out.
There is no rollback once a task exists. Its
Stdoutis abinary://URI, andcio.NewAttachopens that value as a FIFO path, so a container already running under the broker cannot be moved back. The choice therefore has to be made when the task is created, and an operator has to be able to make it.So step 2 adds
disable_attach_broker, reaching the same switch through--disable-attach-broker,NERDCTL_DISABLE_ATTACH_BROKERandnerdctl.toml, via the sameAddPersistentBoolFlaghelper the other global options use. Off by default.The name is negative on purpose. This is not a feature switch but a way to back the change out in the field without a downgrade, and I would expect it to be removed once the broker has proven itself.
disable_hc_systemdseemed like the closest precedent.It needs no new code paths: it leaves the data store empty at task creation, which every branch already handles, because that is also what a container with a foreign log driver looks like. The fallbacks were already there and tested; this just lets an operator take them deliberately.
It also answers question 2 above. With the switch on,
--log-driver noneshort-circuits the way it does today, so a container that asked for no logs runs with no logging process at all, and the extra process per container is opt-out rather than unconditional.The limitation worth stating plainly: containers already running are unaffected, since their stdio is bound. Backing the change out means switching it off and restarting them. That is in the flag's help text and in
docs/config.md.ekalinin commentedon Sep 2, 2026
And a process question:
Step 1 is up as #5168 - the
pkg/attachmuxpackage on its own, no existing file touched. Step 2 is ready behind it.GitHub will not let me stack these against this repo, since a pull request's base branch has to live here rather than in my fork, so each step has to wait for the previous one to merge. That is five round trips for something that is one change.
Would you rather have it that way, or fewer, larger pull requests with the commits kept separate? I split it because step 1 is two thirds of the diff and needs no containerd at all to review, while step 4 is the one that touches the well trodden foreground
run -itpath. But if reviewing five in sequence is worse for you than reviewing one with a readable history, say so and I will collapse it. This is related to question 4 above, but not the same: that one was about which release the foreground change lands in.