supervisor

package
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 30 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package supervisor runs dev servers in pseudo-terminals and tracks their lifecycle: start (with dependencies), readiness, graceful stop, crash handling with restart policies, resource usage and scrollback.

Index

Constants

View Source
const ExposureInterval = IdleSampleInterval

ExposureInterval is how often the listening addresses of running servers are read again; a server that becomes ready is read at once.

View Source
const IdleSampleInterval = 30 * time.Second

IdleSampleInterval is how often usage is sampled while no client shows it.

View Source
const PruneInterval = 10 * time.Second

PruneInterval is how often temporary servers are checked for a checkout that no longer exists.

View Source
const ReadyTimeout = 90 * time.Second

ReadyTimeout is how long ensure and restart wait for readiness when the caller gives no timeout.

View Source
const SampleInterval = 2 * time.Second

SampleInterval is how often usage is sampled while a client shows it, and how often ports are checked; histories hold historyLen samples at this spacing.

View Source
const TemporarySeparator = "--"

TemporarySeparator joins a configured server's name and a worktree label in a temporary server's name; it keeps the name a valid host label.

Variables

View Source
var ErrPortBusy = errors.New("port is in use by another process")

ErrPortBusy means the server's port is held by a process Portside did not start.

Functions

func IconPath

func IconPath(dir, explicit string) string

IconPath returns the icon file for a server directory, preferring an explicitly configured one. Results are cached for a minute.

func IsContainerRuntime

func IsContainerRuntime(command string) bool

IsContainerRuntime reports whether a process name belongs to a container engine that publishes container ports on the host.

func KeepOnExec

func KeepOnExec(f *os.File, keep bool) (int, error)

KeepOnExec keeps f open across exec, or lets exec close it again, and returns its descriptor number. Unlike f.Fd() it leaves the blocking mode alone: that mode belongs to the open file, which a listener or terminal still in use shares. Any process started while f is kept open inherits it, so callers hold syscall.ForkLock until the exec.

func KeepTerminalsOnExec

func KeepTerminalsOnExec(hs []Handoff, keep bool) error

KeepTerminalsOnExec keeps the terminals of hs open across exec and records their descriptor numbers, or (keep false) lets exec close them again. It takes no supervisor lock, so a caller holding syscall.ForkLock can use it.

func LoginShellEnv

func LoginShellEnv() []string

LoginShellEnv reads the account's login-shell environment once, for commands outside the daemon (such as the app's helper, which starts with a minimal PATH). It returns nil when the shell cannot be read.

func NetworkWarning added in v0.4.0

func NetworkWarning(e ports.Exposure, lan bool) bool

NetworkWarning reports whether a listener with exposure e should be pointed out: it is reachable from the network and its server does not set `lan = true`. Tailnet-only and loopback listeners are not.

func Notify

func Notify(title, msg string)

Notify shows a desktop notification. Text travels as arguments, never as script source, so server names cannot inject AppleScript.

func PlainLine

func PlainLine(l string) string

PlainLine turns one raw line into readable text: escape sequences removed, a carriage-return redraw (progress bar) collapsed to its final state, and other control characters dropped.

func PlainLines

func PlainLines(raw []byte, n int) []string

PlainLines converts raw terminal output to readable lines.

func SavedTemporaryPorts

func SavedTemporaryPorts(stateDir string) func(port int) bool

SavedTemporaryPorts is TemporaryPorts for the temporary servers saved in stateDir, for use before a supervisor exists.

func ServerLookPath

func ServerLookPath(name string, prepend []string) string

ServerLookPath finds name the way LookPath does for a process without a daemon (the CLI): the caller's PATH first, then prepend and the login shell's PATH, read only when needed. It returns "" when nothing matches.

func StripANSI

func StripANSI(s string) string

StripANSI removes terminal escape sequences.

func Terminate

func Terminate(pgid int, done <-chan struct{}, grace time.Duration)

Terminate signals a process group and escalates until the leader and every other member have exited, so a restart never finds the port taken by a child that was still shutting down.

Types

type Handoff

type Handoff struct {
	Name     string `json:"name"`
	PID      int    `json:"pid"`
	PIDStart string `json:"pidStart"`
	// PTY is the descriptor number of the terminal's controlling side.
	PTY int `json:"pty"`

	Config      config.Server `json:"config"` // what the process was started with
	Env         []string      `json:"env"`
	Shell       string        `json:"shell"`
	Tool        string        `json:"tool,omitempty"`   // version manager the process runs under
	Launch      *launchInputs `json:"launch,omitempty"` // what Env was built from
	Status      Status        `json:"status"`
	Note        string        `json:"note,omitempty"`
	Want        bool          `json:"want"`
	Retries     int           `json:"retries"`
	StartedAt   time.Time     `json:"startedAt"`
	ReadyAt     time.Time     `json:"readyAt"`
	ListenHost  string        `json:"listenHost,omitempty"`
	ListenPorts []int         `json:"listenPorts,omitempty"`
	// LogReady says whether a line already matched the server's ready_log
	// (nil from a daemon before it), and LogLine is the unfinished line the
	// match continues with.
	LogReady *bool  `json:"logReady,omitempty"`
	LogLine  []byte `json:"logLine,omitempty"`
	// MissingSince is when a running server stopped answering, so its lost
	// readiness stays reported.
	MissingSince time.Time `json:"missingSince,omitzero"`
	Cols         uint16    `json:"cols"`
	Rows         uint16    `json:"rows"`
	// contains filtered or unexported fields
}

Handoff describes a live server that a daemon passes to the binary it re-executes in its own process. The server keeps running: the process stays this daemon's child and its terminal's descriptor stays open across the exec, so the new daemon only has to take both over.

type Health added in v0.7.0

type Health struct {
	Expected bool
	Ready    bool
	Reason   string
}

Health is whether a server should run and whether it is ready (running and still answering), the rule behind monitoring checks. A server should run when it crashed, when it exited although its restart policy is always (the policy gave up), and while it is wanted (started and not stopped by the user). Reason explains a server that should run and is not ready: its note, else its status.

func (Health) Degraded added in v0.7.0

func (h Health) Degraded() bool

Degraded reports a server that should run and is not ready.

type Line

type Line struct {
	At   time.Time
	Text string
}

Line is one line of plain output and when it began; At is zero when unknown.

type LogBuffer

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

LogBuffer keeps a server's raw terminal output: a bounded in-memory tail for replay into terminals, an on-disk copy, and fan-out to live subscribers.

func NewMemoryLog

func NewMemoryLog() *LogBuffer

NewMemoryLog returns a buffer that is kept only in memory.

func (*LogBuffer) Clear

func (lb *LogBuffer) Clear()

Clear empties the scrollback (the on-disk log is kept).

func (*LogBuffer) Close

func (lb *LogBuffer) Close()

Close releases the log file.

func (*LogBuffer) Lines

func (lb *LogBuffer) Lines(n int) []string

Lines returns the last n lines as plain text, with escape sequences removed and carriage-return redraws (progress bars) collapsed to their final state.

func (*LogBuffer) Locked added in v0.7.1

func (lb *LogBuffer) Locked(f func())

Locked runs f under the buffer's lock, as WatchLines functions run.

func (*LogBuffer) Path added in v0.6.0

func (lb *LogBuffer) Path() string

Path is the on-disk log file, "" for a log kept only in memory.

func (*LogBuffer) Raw

func (lb *LogBuffer) Raw() []byte

Raw returns a copy of the scrollback.

func (*LogBuffer) Subscribe

func (lb *LogBuffer) Subscribe() ([]byte, chan []byte)

Subscribe returns the current scrollback and a channel of new output.

func (*LogBuffer) Tail

func (lb *LogBuffer) Tail(n, max int) []string

Tail returns the last n non-empty plain lines, each cut to max runes. It only looks at the end of the scrollback, so it is cheap enough to call on every state broadcast.

func (*LogBuffer) TimedLines

func (lb *LogBuffer) TimedLines() []Line

TimedLines returns the scrollback as plain lines with their times.

func (*LogBuffer) Unsubscribe

func (lb *LogBuffer) Unsubscribe(ch chan []byte)

Unsubscribe stops delivery to ch.

func (*LogBuffer) WatchLines added in v0.7.1

func (lb *LogBuffer) WatchLines(fn func(chunk []byte) bool)

WatchLines calls fn with every chunk written from now on, under the buffer's lock so that, unlike a subscription, it misses no output; it stops once fn returns true or another WatchLines (nil for none) replaces it.

func (*LogBuffer) Write

func (lb *LogBuffer) Write(p []byte) (int, error)

Write appends output and notifies subscribers. Slow subscribers drop chunks rather than stall the process being supervised.

type ShellRead

type ShellRead struct {
	Shell string // the account's login shell
	Used  string // the shell that was read: Shell, or bash or zsh in place of a non-POSIX one
	Err   string // why the read failed; servers then get the daemon's own environment
	Path  string // PATH from the read
}

ShellRead describes one read of the login-shell environment.

func ReadLoginShell

func ReadLoginShell() (ShellRead, []string)

ReadLoginShell reads the environment of the account's login shell. The environment is nil when the read fails.

func (ShellRead) Describe

func (r ShellRead) Describe() string

Describe is a one-line summary for logs.

func (ShellRead) Fallback

func (r ShellRead) Fallback() bool

Fallback reports whether another shell was read in place of the login shell.

type StartOptions

type StartOptions struct {
	// Takeover stops a foreign process holding the port before starting.
	Takeover bool
}

StartOptions tune Start.

type Status

type Status string

Status is the lifecycle state of a server.

const (
	Stopped  Status = "stopped"  // not running
	Starting Status = "starting" // process alive, not yet accepting connections
	Running  Status = "running"  // process alive and ready
	Stopping Status = "stopping" // stop requested, waiting for exit
	Crashed  Status = "crashed"  // exited with an error
	Exited   Status = "exited"   // exited cleanly on its own
	Blocked  Status = "blocked"  // could not start: port taken by another process
)

type Supervisor

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

Supervisor owns all managed processes.

func New

func New(cfg *config.Config, stateDir string) *Supervisor

New creates a supervisor for cfg. Logs and state go below stateDir.

func (*Supervisor) ActiveAddress

func (s *Supervisor) ActiveAddress(name string) (string, bool)

ActiveAddress is the loopback endpoint used for health, links and proxying.

func (*Supervisor) ActivePort

func (s *Supervisor) ActivePort(name string) (int, bool)

ActivePort is the port a server's live process uses, which can differ from the configured one until a restart applies an edit.

func (*Supervisor) AddDesktopClient

func (s *Supervisor) AddDesktopClient() func()

AddDesktopClient registers a client that notifies the user itself and returns a function that unregisters it.

func (*Supervisor) Adopt

func (s *Supervisor) Adopt(hs []Handoff) []string

Adopt takes over servers handed off by the daemon this process replaced. Call it before Recover, which saves the state and stops adopted servers that are no longer configured. A server whose process is gone or whose terminal descriptor is not usable is skipped; Recover then ends its process group and restores it as after a crash. It returns the names it adopted.

func (*Supervisor) Apply

func (s *Supervisor) Apply(cfg *config.Config)

Apply swaps in a new configuration. Running servers keep running; if their definition changed they are flagged as stale until restarted. Servers that disappeared from the file are stopped.

func (*Supervisor) ApplyRenamed

func (s *Supervisor) ApplyRenamed(cfg *config.Config, old, name string)

ApplyRenamed preserves a live process and its logs when an edit renames it.

func (*Supervisor) CancelHandoff

func (s *Supervisor) CancelHandoff()

CancelHandoff resumes normal operation after a failed exec.

func (*Supervisor) ClearLogs

func (s *Supervisor) ClearLogs(name string)

ClearLogs empties a server's scrollback.

func (*Supervisor) Config

func (s *Supervisor) Config() *config.Config

Config returns the configuration currently applied.

func (*Supervisor) Definitions

func (s *Supervisor) Definitions() []config.Server

Definitions returns the definitions of configured and temporary servers, each temporary server after its origin.

func (*Supervisor) Dismiss

func (s *Supervisor) Dismiss(name string) error

Dismiss stops a server on request. A temporary server is removed as well, with its log files.

func (*Supervisor) Environ

func (s *Supervisor) Environ() []string

Environ is the login-shell environment with the configured path entries, for helper commands the daemon runs on the user's behalf.

func (*Supervisor) ForCheckout

func (s *Supervisor) ForCheckout(name, dir string) (string, error)

ForCheckout returns the server that runs name in the checkout containing dir: name itself for its own checkout, otherwise a temporary copy, created on first use with a free port. dir must be a checkout of the repository name runs from.

func (*Supervisor) Input

func (s *Supervisor) Input(name string, data []byte) error

Input writes keystrokes to a server's terminal.

func (*Supervisor) IsManagedPID

func (s *Supervisor) IsManagedPID(pid int) (string, bool)

IsManagedPID reports whether pid belongs to a process tree Portside runs.

func (*Supervisor) IsTemporary

func (s *Supervisor) IsTemporary(name string) bool

IsTemporary reports whether name is a temporary server.

func (*Supervisor) KillListener

func (s *Supervisor) KillListener(l ports.Listener) error

KillListener ends a foreign process that holds a port.

func (*Supervisor) Killable

func (s *Supervisor) Killable(l ports.Listener) string

Killable reports why a foreign listener may not be killed, or "" if it may.

func (*Supervisor) Logs

func (s *Supervisor) Logs(name string) (*LogBuffer, bool)

Logs returns the server's log buffer.

func (*Supervisor) LookPath

func (s *Supervisor) LookPath(name string) string

LookPath finds an executable on the user's login-shell PATH plus the configured path entries. It returns "" when nothing matches.

func (*Supervisor) Lookup

func (s *Supervisor) Lookup(name string) (config.Server, bool)

Lookup returns the definition of any server the supervisor knows, configured or temporary.

func (*Supervisor) NotifyUser added in v0.4.0

func (s *Supervisor) NotifyUser(title, message string)

NotifyUser shows a desktop notification other than a crash (a container problem, a device pairing or connecting) under the same notify setting and desktop-client guard as crashes: while the app is connected it notifies from the state itself.

func (*Supervisor) PrepareHandoff

func (s *Supervisor) PrepareHandoff() ([]Handoff, error)

PrepareHandoff refuses new launches and returns every live server. A server that is being stopped blocks the handoff, since its stop must finish in one place. KeepTerminalsOnExec then keeps the terminals open across exec; CancelHandoff resumes launches when the exec fails.

func (*Supervisor) Recover

func (s *Supervisor) Recover(restore bool)

Recover ends process groups orphaned by a daemon that died without cleaning up, then starts the servers that were running before (if the config asks for it and restore is set). Servers taken over by Adopt are left running. Call once, before serving requests.

func (*Supervisor) Resize

func (s *Supervisor) Resize(name string, cols, rows uint16)

Resize changes a server's terminal size; new processes inherit it too.

func (*Supervisor) Restart

func (s *Supervisor) Restart(name string, opt StartOptions) error

Restart stops a server (if running) and starts it again.

func (*Supervisor) Run

func (s *Supervisor) Run(ctx context.Context)

Run performs periodic bookkeeping until ctx ends: resource sampling, listening checks and detection of foreign processes on configured ports.

func (*Supervisor) SetForwarded

func (s *Supervisor) SetForwarded(fn func(port int) (string, bool))

SetForwarded registers fn, which reports a port forwarded to another computer. Such a port is not probed for a stopped server (a connection would reach the other computer) and is shown as forwarded instead.

func (*Supervisor) SetPortRelease

func (s *Supervisor) SetPortRelease(fn func(port int))

SetPortRelease registers fn, called with a server's port before it starts.

func (*Supervisor) SetPublishedPorts

func (s *Supervisor) SetPublishedPorts(fn func(server string, port int) bool)

SetPublishedPorts registers fn, which reports whether a running container of a server's compose project publishes a port.

func (*Supervisor) SetTailnet added in v0.4.2

func (s *Supervisor) SetTailnet(own ports.TailnetAddrs)

SetTailnet sets how checkExposure learns this machine's Tailscale addresses, so a listener on one of them counts as tailnet; without it such listeners count as reachable from the network.

func (*Supervisor) Shutdown

func (s *Supervisor) Shutdown()

Shutdown stops every server. The set of servers the user wanted running is persisted first so that the next daemon start can restore it.

func (*Supervisor) Snapshot

func (s *Supervisor) Snapshot(daemonPort int) []View

Snapshot returns all servers in configuration order. daemonPort is used to build *.localhost alias URLs served by the daemon's proxy.

func (*Supervisor) Start

func (s *Supervisor) Start(name string, opt StartOptions) error

Start launches a server and, first, every server it depends on. It returns once the launch has been initiated; readiness is reported through status.

func (*Supervisor) Stop

func (s *Supervisor) Stop(name string) error

Stop ends a server gracefully: Ctrl-C to its process group, then SIGTERM, then SIGKILL. It returns when the process has exited.

func (*Supervisor) Subscribe

func (s *Supervisor) Subscribe() chan struct{}

Subscribe returns a channel that receives a signal whenever state changes.

func (*Supervisor) TemporaryPorts

func (s *Supervisor) TemporaryPorts() func(port int) bool

TemporaryPorts reports the ports temporary servers are assigned or run on, which automatic ports in the config must skip.

func (*Supervisor) Unsubscribe

func (s *Supervisor) Unsubscribe(ch chan struct{})

Unsubscribe stops change signals to ch.

func (*Supervisor) WaitReady

func (s *Supervisor) WaitReady(ctx context.Context, name string, timeout time.Duration) error

WaitReady checks the live listener, including servers already marked running.

func (*Supervisor) WantsPort

func (s *Supervisor) WantsPort(port int) bool

WantsPort reports whether a server here is starting or running on port. It takes no lock, so code holding its own lock while the supervisor calls into it (such as the port forwarding) can ask.

func (*Supervisor) WatchUsage added in v0.3.0

func (s *Supervisor) WatchUsage() func()

WatchUsage registers a client that shows resource usage now, such as an open dashboard, and returns a function that unregisters it. While any is registered usage is sampled every SampleInterval; the first one gets a sample at once.

type View

type View struct {
	Name       string `json:"name"`
	Group      string `json:"group,omitempty"`
	Dir        string `json:"dir"`
	DirDisplay string `json:"dirDisplay"`
	Cmd        string `json:"cmd"`
	Port       int    `json:"port"`
	PortAuto   bool   `json:"portAuto,omitempty"`
	URL        string `json:"url,omitempty"`
	Alias      string `json:"alias,omitempty"`
	Status     Status `json:"status"`
	// Unready marks a running server whose port or health check has failed
	// for listenerLossDelay; it is not restarted, and its note says why.
	Unready        bool            `json:"unready,omitempty"`
	Note           string          `json:"note,omitempty"`
	PID            int             `json:"pid,omitempty"`
	StartedAt      *time.Time      `json:"startedAt,omitempty"`
	ReadyAt        *time.Time      `json:"readyAt,omitempty"`
	ExitedAt       *time.Time      `json:"exitedAt,omitempty"`
	ExitCode       *int            `json:"exitCode,omitempty"`
	RestartPending bool            `json:"restartPending"`
	ListenPorts    []int           `json:"listenPorts,omitempty"`
	Listening      bool            `json:"listening"`
	External       *ports.Listener `json:"external,omitempty"`
	Stale          bool            `json:"stale,omitempty"`
	Removed        bool            `json:"removed,omitempty"`
	Enabled        bool            `json:"enabled"`
	DependsOn      []string        `json:"dependsOn,omitempty"`
	Restart        string          `json:"restart"`
	Restarts       int             `json:"restarts,omitempty"`
	CPU            float64         `json:"cpu"`
	Mem            int64           `json:"mem"`
	CPUHistory     []float64       `json:"cpuHistory,omitempty"`
	MemHistory     []int64         `json:"memHistory,omitempty"`
	HasIcon        bool            `json:"hasIcon"`
	Tail           []string        `json:"tail"` // last few plain output lines
	Wanted         bool            `json:"wanted"`
	// Tool is the environment tool the live process runs under, such as
	// direnv or mise ("custom" for a configured wrap).
	Tool string `json:"tool,omitempty"`

	// Temporary marks a copy of the configured server Origin that runs in
	// the checkout at Worktree; it is not in the config file.
	Temporary bool   `json:"temporary,omitempty"`
	Origin    string `json:"origin,omitempty"`
	Worktree  string `json:"worktree,omitempty"`

	// ForwardedFrom names the connected computer whose server answers on
	// this stopped server's port, forwarded here.
	ForwardedFrom string `json:"forwardedFrom,omitempty"`

	// Exposure is where the running server's listeners can be reached from
	// (loopback, tailnet or network); absent until read. NetworkWarning
	// marks one reachable from the network whose config does not set
	// `lan = true`, which LAN reports. Kind names the tool the command
	// starts (see discover.CommandKind) while NetworkWarning is set, for the
	// dashboard's fix.
	Exposure       ports.Exposure `json:"exposure,omitempty"`
	NetworkWarning bool           `json:"networkWarning,omitempty"`
	LAN            bool           `json:"lan,omitempty"`
	Kind           string         `json:"kind,omitempty"`
}

View is the public, JSON-serialisable state of one server.

func (View) Health added in v0.7.0

func (v View) Health(required bool) Health

Health classifies the server for monitoring; a required server should run whatever its state, also after a stop.

Jump to

Keyboard shortcuts

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