Skip to content

Multiple attach should be supported #3570

Open

Description

@apostasie

Description

In terminal 1:

nerdctl run --rm -ti --detach-keys=ctrl-a,ctrl-b --name what debian

Do not detach

Then in terminal 2:

nerdctl attach what

Start typing in terminal 2.

Notice that some characters are displayed on terminal 1, others on terminal 2.

Do the same with docker: it works.

There is something broken either in nerdctl, or maybe in containerd/console.

Steps to reproduce the issue

No response

Describe the results you received and expected

na

What version of nerdctl are you using?

main

Are you using a variant of nerdctl? (e.g., Rancher Desktop)

None

Host information

No response

Activity

  1. apostasie commented on Feb 22, 2025

    @apostasie
    ContributorAuthor

    Note this was actually explicitly mentioned as a limitation in the original PR introducing attach: #2108

  2. changed the title [-]attach on a container with tty seems broken[/-] [+]Multiple attach should be supported[/+] on Jun 25, 2025
  3. apostasie commented on Jun 25, 2025

    @apostasie
    ContributorAuthor

    @AkihiroSuda + feature

  4. added
    bug
    enhancement
    and removed
    kind/unconfirmed-bug-claim
    bug
    on Jun 26, 2025
  5. ChengyuZhu6 commented on Jul 2, 2025

    @ChengyuZhu6
    Member

    @apostasie @AkihiroSuda I‘d like to take it on.

  6. ekalinin commented on Aug 31, 2026

    @ekalinin
    Contributor

    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.

                        containerd-shim
                        pty master / pipes
                                |
                  binary:// (spawn + fd 3,4)
                                v
       +------------------------------------------+
       |  nerdctl _NERDCTL_INTERNAL_LOGGING        |
       |  +------------+      +----------------+   |
       |  | log driver |<-----|  raw tee       |   |
       |  +------------+      |  (fan-out)     |   |
       |                      +-------+--------+   |
       |  stdin.fifo <-- fan-in <-----+            |
       |                                           |
       +---------------- attach.sock --+-----------+
                  ^            ^            ^
          nerdctl run -it   attach #1    attach #2
    

    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.

    Invariants

    Each of these is a bug today:

    1. The container never blocks on a session. Bounded queue and a writer goroutine per session; one that falls behind is disconnected. This is the structural fix for the deadlock class in nerdctl run with 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.
    2. 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.
    3. No replay buffer. run and start -a connect before task.Start(), so nothing is produced with nobody attached. attach shows no history, matching Docker.
    4. 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.
    5. 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:

    1. pkg/attachmux: broker, client, framing. New package, no existing file touched, unit tested without containerd. Roughly two thirds of the diff.
    2. Broker inside the logging process, stable stdin.fifo. No user-visible change yet.
    3. attach follows the task's IO configuration to the socket or to the FIFOs. This is where TestAttachMultipleSessions starts passing and nerdctl attach freezes the terminal sessions randomly. #4374 closes.
    4. run -it / start -a become socket clients; the branches in taskutil.NewTask collapse.
    5. Docs, and the caveat comes out of the attach help text.

    Questions before I start

    1. Is the logging process the right home for the broker? It has the right lifetime, but it is also code that has been sensitive lately (gomodjail CI failing (TestLogs*) #5006, nerdctl run with 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.
    2. --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?
    3. Socket location. <dataStore>/attach/<digest>.sock, for the reason in constraint 2. Is there a convention you would prefer that still satisfies it?
    4. 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?
    5. Fix foreground stdio deadlock when the internal logging process stops consuming #5151 is open and touches the same code (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.

  7. ekalinin commented on Sep 2, 2026

    @ekalinin
    Contributor

    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.

  8. ekalinin commented on Sep 2, 2026

    @ekalinin
    Contributor

    And a process question:

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

enhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions