sessions

package
v0.6.12 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package sessions implements long-running command sessions inside a sandbox container: PTY or pipes, in-memory replay buffer, fan-out to multiple attached clients, and asciinema recording. Designed to live in toolboxd (PID 1 of the container) and be reachable via the toolbox HTTP/WS API.

Index

Constants

This section is empty.

Variables

View Source
var ErrNoShell = errors.New("this sandbox's image has no shell: neither bash nor sh is installed")

ErrNoShell is returned for a shell or a command string in an image with neither bash nor sh (distroless, scratch). Without it the session fails later as "fork/exec /bin/sh: no such file or directory", which reads as a toolboxd fault rather than a property of the image.

View Source
var ErrNotFound = errors.New("session not found")

ErrNotFound is returned when a session ID isn't tracked.

Functions

func SetWinsize added in v0.6.12

func SetWinsize(master *os.File, cols, rows uint16) error

SetWinsize sets a terminal's window size through the raw descriptor. pty.Setsize calls Fd, which would put the master back in blocking mode.

func StartPTY added in v0.6.12

func StartPTY(cmd *exec.Cmd, cols, rows uint16) (*os.File, error)

StartPTY starts cmd on a new terminal of the given size, like pty.StartWithSize, and returns a master that Close can interrupt.

creack/pty (v1.1.24) reads the terminal number, unlocks it and sets its size through File.Fd(), and Fd switches a file to blocking mode and takes it out of Go's poller. Close on such a file cannot wake a Read already in progress, so the descriptor stays open until that Read returns: an output pump waiting on an idle shell keeps the master open, the kernel never hangs up the terminal and the shell never gets SIGHUP. Every Hangup that came after the shell's first output did nothing (10 of 10 in a forced test). The master is swapped for a non-blocking duplicate, which os.NewFile registers with the poller.

Types

type Config

type Config struct {
	// SandboxID is recorded in metadata and used as a recordings subdirectory.
	SandboxID string
	// RecordingDir is where asciinema cast files land. Required.
	RecordingDir string
	// RecordingRetention prunes cast files older than this. Zero = never.
	RecordingRetention time.Duration
	// SweepInterval drives the retention sweeper. Default 1 h.
	SweepInterval time.Duration
	// BufferBytes is the per-session replay buffer size. Default 1 MiB.
	BufferBytes int
	// StartProcess starts a session's command (start is cmd.Start, or a PTY
	// start that calls it) and returns how to wait for its exit. toolboxd is
	// PID 1 and reaps orphans with wait4(-1), which can take a session's own
	// exit status before cmd.Wait does; it passes its child table here so
	// the status reaches the session instead of reading as exit 0. Nil means
	// start, then cmd.Wait: right for a parent that reaps nothing. The
	// Manager starts real processes wherever it runs, so it belongs inside a
	// sandbox (toolboxd), never in sandboxd: the WASM tool host stopped using
	// it for that reason (internal/runtime/wasm/toolhost/sessions.go).
	StartProcess func(cmd *exec.Cmd, start func() error) (wait func() (code int, signal string), err error)
	// BaseEnv returns the environment a session starts from, before the
	// request's own env is laid on top. Nil means os.Environ(). toolboxd
	// sets it so sessions, terminals and envd processes see the sandbox env
	// a Firecracker host pushed over vsock (cmd/toolboxd/sandboxenv), which
	// is not in toolboxd's own process environment.
	BaseEnv func() []string
}

Config controls Manager behavior. Defaults are sensible for an in-container daemon; everything is overridable via toolboxd env vars.

type Frame

type Frame struct {
	Stream Stream
	Data   []byte
}

Frame is a unit of session output observed by an attached client.

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager owns every Session running in the container.

func New

func New(logger *slog.Logger, cfg Config) (*Manager, error)

New constructs a Manager and starts its retention sweeper.

func (*Manager) Close

func (m *Manager) Close()

Close kills every running session and stops the sweeper. Best-effort.

func (*Manager) Create

Create starts a new session. Always assigns a fresh ID.

func (*Manager) Delete

func (m *Manager) Delete(id string) error

func (*Manager) FlushRecording added in v0.4.1

func (m *Manager) FlushRecording(id string) error

FlushRecording best-effort fsyncs the asciinema cast file for the given session id. Called from the in-guest vsock handler's OnPreSnapshot (Phase 3 PR-B) so a clone resumed from the snapshot observes a session recording that ends cleanly at the freeze point rather than missing the trailing few-hundred bytes. Returns nil for sessions without an attached recording (the common case for template captures), unknown IDs (caller iterates List() and a session can finish between the two calls), and recorders that have already been Close()d.

func (*Manager) Get

func (m *Manager) Get(id string) (*Session, error)

Get fetches a session by ID. Returns ErrNotFound if missing.

func (*Manager) GetByName added in v0.1.7

func (m *Manager) GetByName(name string) (*Session, error)

GetByName fetches a running session by its stable name. Exited sessions are not returned because the byName map is cleared when a session finishes.

func (*Manager) GetOrCreate

func (m *Manager) GetOrCreate(ctx context.Context, req models.CreateSessionRequest) (*Session, bool, error)

GetOrCreate returns the running session with the given Name (creating it from req if absent). Used by SSH attach so `ssh sandbox+default@host` idempotently lands on a single shared shell. created is true for exactly one of any number of concurrent callers for the same name: the others wait for that caller's session instead of starting their own.

func (*Manager) List

func (m *Manager) List() []models.Session

List returns metadata for every session currently tracked, ordered by CreatedAt ascending.

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session is one long-running process plus the fan-out hub that distributes its output to attached clients. Methods are safe for concurrent use.

func (*Session) CloseStdin

func (s *Session) CloseStdin() error

CloseStdin half-closes stdin so the process sees EOF.

func (*Session) Done

func (s *Session) Done() <-chan struct{}

Done returns a channel that closes when the underlying process exits.

func (*Session) ExitInfo

func (s *Session) ExitInfo() (int, string)

ExitInfo returns the exit code and signal name (empty if not signaled). If the session is still running, returns -1, "".

func (*Session) Exited added in v0.6.12

func (s *Session) Exited() bool

Exited reports whether the process has exited. It turns true before the subscriber streams close, while Done closes only after the recorder and the terminal are shut, so a client that saw its stream end and then asks about the session must be answered from Exited, not Done.

func (*Session) Hangup added in v0.6.12

func (s *Session) Hangup()

Hangup closes a PTY session's terminal the way closing a terminal window does: the kernel sends SIGHUP to the shell, which passes it on to its jobs before it exits. It also ends the output pump even when a job that ignores SIGHUP still holds the terminal open, so the session can finish and free its memory; Signal and Manager.Delete reach only the shell's own process group, and an interactive shell puts each job in a group of its own. A no-op for pipe sessions and after exit.

func (*Session) ID

func (s *Session) ID() string

ID returns the session's stable identifier.

func (*Session) IsPTY

func (s *Session) IsPTY() bool

IsPTY reports whether the session was started in PTY mode.

func (*Session) KillTerminal added in v0.6.12

func (s *Session) KillTerminal() int

KillTerminal SIGKILLs every process that holds this PTY session's terminal open: the shell and every job it started under job control. Such jobs sit in process groups of their own, which a kill of the shell's group misses, and once the shell is gone they have no controlling terminal either; while one holds the terminal open, the output pump never sees end-of-file and the session never finishes. Call it before Hangup: while the session holds the master, the terminal's number cannot be handed to another terminal, so only this session's holders match. It returns how many processes it signalled; a pipe session, a session already hung up, or a system without /proc signals none.

func (*Session) Name

func (s *Session) Name() string

Name returns the human-friendly session name.

func (*Session) PID added in v0.1.7

func (s *Session) PID() int

PID returns the OS process identifier for the session, or 0 when the session has not started successfully.

func (*Session) RecordingPath

func (s *Session) RecordingPath() string

RecordingPath returns the absolute path to the session's asciinema cast file, or "" if recording is disabled.

func (*Session) ReleaseReplay added in v0.6.12

func (s *Session) ReleaseReplay() bool

ReleaseReplay frees the replay buffer of a session that has exited and reports whether it did. The exit status, metadata and recording stay, so an attacher afterwards gets the exit but no replayed output. Sessions keep their buffer for as long as they are tracked; only toolboxd's Daytona terminals call this, after a short retention, so a sandbox that churns terminals does not hold a buffer for every finished one (plan E8, R11). A running session keeps its buffer: its pumps still write to it.

func (*Session) Replay

func (s *Session) Replay() []byte

Replay returns the current contents of the replay buffer (oldest→newest).

func (*Session) Resize

func (s *Session) Resize(cols, rows int) error

Resize updates the PTY window size. No-op in pipe mode or after exit.

func (*Session) Signal

func (s *Session) Signal(name string) error

Signal sends a signal to the session's process group. Accepts INT, TERM, KILL, HUP, QUIT (with or without SIG prefix).

func (*Session) Size added in v0.6.12

func (s *Session) Size() (cols, rows int)

Size returns the window size the session's terminal has now: the create size, or the last successful Resize.

func (*Session) Snapshot

func (s *Session) Snapshot() models.Session

Snapshot returns the metadata view of the session.

func (*Session) Subscribe

func (s *Session) Subscribe() (<-chan Frame, func())

Subscribe registers a new attacher. The returned channel first receives a replay frame containing the current buffer contents (merged as stdout), then live output frames in order until the session ends or the caller calls the cancel function. Channel buffer size is 64; slow consumers drop older frames.

func (*Session) Write

func (s *Session) Write(p []byte) (int, error)

Write forwards bytes to the session's stdin (PTY in PTY mode, pipe stdin otherwise). Returns an error if the session has exited or stdin is closed.

type Stream

type Stream uint8

Stream identifies which output stream a chunk of bytes belongs to. Pipe mode uses both; PTY mode only uses Stdout.

const (
	StreamStdout Stream = 1
	StreamStderr Stream = 2
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL