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
- Variables
- func IconPath(dir, explicit string) string
- func IsContainerRuntime(command string) bool
- func KeepOnExec(f *os.File, keep bool) (int, error)
- func KeepTerminalsOnExec(hs []Handoff, keep bool) error
- func LoginShellEnv() []string
- func Notify(title, msg string)
- func PlainLine(l string) string
- func PlainLines(raw []byte, n int) []string
- func SavedTemporaryPorts(stateDir string) func(port int) bool
- func ServerLookPath(name string, prepend []string) string
- func StripANSI(s string) string
- func Terminate(pgid int, done <-chan struct{}, grace time.Duration)
- type Handoff
- type Line
- type LogBuffer
- func (lb *LogBuffer) Clear()
- func (lb *LogBuffer) Close()
- func (lb *LogBuffer) Lines(n int) []string
- func (lb *LogBuffer) Raw() []byte
- func (lb *LogBuffer) Subscribe() ([]byte, chan []byte)
- func (lb *LogBuffer) Tail(n, max int) []string
- func (lb *LogBuffer) TimedLines() []Line
- func (lb *LogBuffer) Unsubscribe(ch chan []byte)
- func (lb *LogBuffer) Write(p []byte) (int, error)
- type ShellRead
- type StartOptions
- type Status
- type Supervisor
- func (s *Supervisor) ActiveAddress(name string) (string, bool)
- func (s *Supervisor) ActivePort(name string) (int, bool)
- func (s *Supervisor) AddDesktopClient() func()
- func (s *Supervisor) Adopt(hs []Handoff) []string
- func (s *Supervisor) Apply(cfg *config.Config)
- func (s *Supervisor) ApplyRenamed(cfg *config.Config, old, name string)
- func (s *Supervisor) CancelHandoff()
- func (s *Supervisor) ClearLogs(name string)
- func (s *Supervisor) Config() *config.Config
- func (s *Supervisor) Definitions() []config.Server
- func (s *Supervisor) Dismiss(name string) error
- func (s *Supervisor) Environ() []string
- func (s *Supervisor) ForCheckout(name, dir string) (string, error)
- func (s *Supervisor) Input(name string, data []byte) error
- func (s *Supervisor) IsManagedPID(pid int) (string, bool)
- func (s *Supervisor) IsTemporary(name string) bool
- func (s *Supervisor) KillListener(l ports.Listener) error
- func (s *Supervisor) Killable(l ports.Listener) string
- func (s *Supervisor) Logs(name string) (*LogBuffer, bool)
- func (s *Supervisor) LookPath(name string) string
- func (s *Supervisor) Lookup(name string) (config.Server, bool)
- func (s *Supervisor) NotifyProblem(title, message string)
- func (s *Supervisor) PrepareHandoff() ([]Handoff, error)
- func (s *Supervisor) Recover(restore bool)
- func (s *Supervisor) Resize(name string, cols, rows uint16)
- func (s *Supervisor) Restart(name string, opt StartOptions) error
- func (s *Supervisor) Run(ctx context.Context)
- func (s *Supervisor) SetForwarded(fn func(port int) (string, bool))
- func (s *Supervisor) SetPortRelease(fn func(port int))
- func (s *Supervisor) SetPublishedPorts(fn func(server string, port int) bool)
- func (s *Supervisor) Shutdown()
- func (s *Supervisor) Snapshot(daemonPort int) []View
- func (s *Supervisor) Start(name string, opt StartOptions) error
- func (s *Supervisor) Stop(name string) error
- func (s *Supervisor) Subscribe() chan struct{}
- func (s *Supervisor) TemporaryPorts() func(port int) bool
- func (s *Supervisor) Unsubscribe(ch chan struct{})
- func (s *Supervisor) WaitReady(ctx context.Context, name string, timeout time.Duration) error
- func (s *Supervisor) WantsPort(port int) bool
- type View
Constants ¶
const PruneInterval = 10 * time.Second
PruneInterval is how often temporary servers are checked for a checkout that no longer exists.
const ReadyTimeout = 90 * time.Second
ReadyTimeout is how long ensure and restart wait for readiness when the caller gives no timeout.
const SampleInterval = 2 * time.Second
SampleInterval is how often usage is sampled; histories hold historyLen samples.
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 ¶
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 ¶
IconPath returns the icon file for a server directory, preferring an explicitly configured one. Results are cached for a minute.
func IsContainerRuntime ¶
IsContainerRuntime reports whether a process name belongs to a container engine that publishes container ports on the host.
func KeepOnExec ¶
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 ¶
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 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 ¶
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 ¶
PlainLines converts raw terminal output to readable lines.
func SavedTemporaryPorts ¶
SavedTemporaryPorts is TemporaryPorts for the temporary servers saved in stateDir, for use before a supervisor exists.
func ServerLookPath ¶
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.
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"`
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 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) Lines ¶
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) Tail ¶
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 ¶
TimedLines returns the scrollback as plain lines with their times.
func (*LogBuffer) Unsubscribe ¶
Unsubscribe stops delivery to ch.
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 ¶
ReadLoginShell reads the environment of the account's login shell. The environment is nil when the read fails.
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) NotifyProblem ¶
func (s *Supervisor) NotifyProblem(title, message string)
NotifyProblem uses the same notification setting and desktop-client guard as crashes.
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) 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 ¶
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.
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"`
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"`
}
View is the public, JSON-serialisable state of one server.