Keepalive with a per-reply timeout marks a frozen link Lost and closes it so hung SFTP calls fail with ErrConnLost (N-P1-2). Reconnect installs a new generation in the same Conn. Exec takes a ctx (SIGKILL + close on cancel) and an output limit (N-P2-15, N-P1-7). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
83 lines
2.2 KiB
Go
83 lines
2.2 KiB
Go
package conn
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
"fmt"
|
||
"time"
|
||
)
|
||
|
||
// errKeepalive is the reason recorded when keepalives go unanswered.
|
||
var errKeepalive = errors.New("no reply to keepalive")
|
||
|
||
// keepalive sends keepalive@openssh.com every interval. KeepaliveMaxMiss
|
||
// unanswered requests in a row (each waits KeepaliveTimeout) close the SSH
|
||
// client: every pending request fails at once and the state becomes Lost
|
||
// (N-P1-2). Worst-case detection: interval*(maxMiss+1) + timeout.
|
||
func (c *Conn) keepalive(g *generation) {
|
||
t := time.NewTicker(c.opts.KeepaliveInterval)
|
||
defer t.Stop()
|
||
miss := 0
|
||
for {
|
||
select {
|
||
case <-g.done:
|
||
return
|
||
case <-t.C:
|
||
}
|
||
if c.ping(g, c.opts.KeepaliveTimeout) {
|
||
miss = 0
|
||
continue
|
||
}
|
||
miss++
|
||
if miss >= c.opts.KeepaliveMaxMiss {
|
||
c.lose(g, fmt.Errorf("%w (%d × %v)", errKeepalive, miss, c.opts.KeepaliveTimeout))
|
||
return
|
||
}
|
||
}
|
||
}
|
||
|
||
// ping sends one keepalive and reports whether a reply (any reply: OpenSSH
|
||
// and x/crypto servers answer "failure" to unknown global requests) arrived
|
||
// within timeout. A request stuck on a dead link finishes when the client
|
||
// is closed (it is not tracked in c.wg: Probe may run concurrently with
|
||
// close, and WaitGroup.Add must not race with Wait).
|
||
func (c *Conn) ping(g *generation, timeout time.Duration) bool {
|
||
res := make(chan error, 1)
|
||
go func() {
|
||
_, _, err := g.ssh.SendRequest("keepalive@openssh.com", true, nil)
|
||
res <- err
|
||
}()
|
||
timer := time.NewTimer(timeout)
|
||
defer timer.Stop()
|
||
select {
|
||
case err := <-res:
|
||
return err == nil
|
||
case <-timer.C:
|
||
return false
|
||
case <-g.done:
|
||
return false
|
||
}
|
||
}
|
||
|
||
// Probe is the operation watchdog (§3.4): when an SFTP call has hung for a
|
||
// long time, sftpfs sends an out-of-band keepalive. No reply within timeout
|
||
// marks the connection Lost (closing it, so the hung call returns) and
|
||
// returns ErrConnLost. ctx only bounds the wait; it does not mark anything.
|
||
func (c *Conn) Probe(ctx context.Context, timeout time.Duration) error {
|
||
if err := c.Err(); err != nil {
|
||
return err
|
||
}
|
||
g := c.cur.Load()
|
||
ok := make(chan bool, 1)
|
||
go func() { ok <- c.ping(g, timeout) }()
|
||
select {
|
||
case alive := <-ok:
|
||
if alive {
|
||
return nil
|
||
}
|
||
c.lose(g, fmt.Errorf("%w (probe, %v)", errKeepalive, timeout))
|
||
return c.Err()
|
||
case <-ctx.Done():
|
||
return ctx.Err()
|
||
}
|
||
}
|