Files
1Panel/agent/utils/terminal/ringbuf.go
HynoR 81b72d9b7d feat: Implement server-side SSH session persistence and recovery (#13707)
* feat(terminal): keep ssh sessions alive server-side with reattach

Split the terminal ws handling into a Session (pty + ssh backend) and an
Attachment (one websocket). A session outlives its websocket: a clean close
(1000) ends the pty, any other disconnect keeps it for a 30-minute grace
period and it can be reattached via `?session=<id>`. Output goes through a
fixed 128KB ring buffer so a reattaching client gets the recent tail, with a
truncation marker if it fell behind. Sessions are owner-scoped; a second
attachment kicks the first (4409), unknown ids get 4404.

New endpoints under /hosts/terminal/sessions (search, close) let the
frontend list and recover sessions after a tab or browser is closed.

* feat(terminal): floating terminal dock with session recovery

Terminals now live in a layout-level host and are teleported into whichever
view shows them, so leaving the terminal page no longer kills them. A dock
handle on the right edge opens a non-modal dialog from any page with every
live session, a picker for local shell / ssh hosts, minimize, and
close-all. On page load the store recovers sessions the server still holds,
so an accidentally closed tab or browser can resume within the grace period.
The menu-tab label shows the live session count.

* fix(terminal): page re-claims its slots under a locked menu tab

With the terminal menu tab locked (keep-alive), leaving the page deactivates
it instead of unmounting it, so the slot ref callback never re-runs on
return. After the dock had taken the Terminal over and released it, nobody
claimed it for the page again and it stayed parked in the hidden host.

Claim/release slots explicitly on mount, activated, deactivated and unmount,
the same ownership rule the dock uses, instead of relying on the ref callback.

* fix(terminal): logout closes every kept-alive terminal session

A logged-out panel has nobody watching it, so nothing it left running should
survive: core now tells the local agent to close all terminal sessions when the
user logs out, changes the password, or changes the bind domain. Until now the
teardown relied on the logging-out tab sending close code 1000; a second tab or
a websocket held outside the SPA kept its shell after logout.

Agent: terminal.CloseAll and POST /hosts/terminal/sessions/closeAll.
Core: LogOut / deleteCurrentSession / BindDomain call it via proxy_local,
best effort.

* fix(terminal): pin a local shell to the node it was opened on

The node a local shell connects to was resolved from the current node every
time the websocket was built, so after switching nodes a reconnect carried the
old session id to the new node (4404) and then opened a shell there instead.
Store the operateNode on the entry when it is created; ssh shells keep going to
the master. Shells on a non-master node get the node name in their title so a
restore in another node's view can tell them apart.
2026-09-07 15:01:35 +08:00

92 lines
2.4 KiB
Go

package terminal
import (
"bytes"
"sync"
)
// ringSize is the output retained per session. Reattach replays at most this much.
// ponytail: fixed; make it a setting if someone asks for a bigger tail.
const ringSize = 128 * 1024
// ringBuffer is a fixed capacity byte ring addressed by absolute write offset.
// Write never blocks and overwrites the oldest bytes; readers that fall behind
// skip ahead and are told they lost data.
type ringBuffer struct {
mu sync.Mutex
buf []byte
written uint64 // total bytes ever written; offset of the next byte
}
func newRingBuffer() *ringBuffer {
return &ringBuffer{buf: make([]byte, ringSize)}
}
// Write appends p, dropping the oldest bytes when full. Always reports len(p).
func (r *ringBuffer) Write(p []byte) (int, error) {
n := len(p)
if n == 0 {
return 0, nil
}
r.mu.Lock()
defer r.mu.Unlock()
capacity := len(r.buf)
if n > capacity {
// only the tail can survive; account for the skipped bytes so offsets stay absolute
r.written += uint64(n - capacity)
p = p[n-capacity:]
}
pos := int(r.written % uint64(capacity))
k := copy(r.buf[pos:], p)
copy(r.buf, p[k:])
r.written += uint64(len(p))
return n, nil
}
// Oldest is the offset of the oldest byte still retained.
func (r *ringBuffer) Oldest() uint64 {
r.mu.Lock()
defer r.mu.Unlock()
return r.oldestLocked()
}
func (r *ringBuffer) oldestLocked() uint64 {
if capacity := uint64(len(r.buf)); r.written > capacity {
return r.written - capacity
}
return 0
}
// ReadFrom returns every byte from offset onward and the offset to continue from.
// If offset was already overwritten, reading starts at the oldest retained byte
// and lost is true. Whenever the start is not the true beginning of output the
// result is aligned to the next '\n' so replay never begins mid escape sequence.
func (r *ringBuffer) ReadFrom(offset uint64) (data []byte, next uint64, lost bool) {
r.mu.Lock()
defer r.mu.Unlock()
oldest := r.oldestLocked()
if offset > r.written {
offset = r.written
}
if offset < oldest {
offset = oldest
lost = true
}
n := int(r.written - offset)
if n == 0 {
return nil, r.written, lost
}
out := make([]byte, n)
start := int(offset % uint64(len(r.buf)))
k := copy(out, r.buf[start:min(start+n, len(r.buf))])
if k < n {
copy(out[k:], r.buf[:n-k])
}
if offset == oldest && oldest > 0 {
if idx := bytes.IndexByte(out, '\n'); idx >= 0 && idx+1 < len(out) {
out = out[idx+1:]
}
}
return out, r.written, lost
}