Files
knowledge-governance/internal/dobotaiops/sshdial.go
T

134 lines
5.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package dobotaiops
import (
"context"
"fmt"
"io"
"net"
"os"
"os/exec"
"strings"
"sync"
"syscall"
"time"
)
// SSHDialer 复用既有的 SSH direct-tcpip 能力:`ssh -W <host>:<port> <target>` ——
// 由 SSH 侧完成到目标库的 TCP 连接,本机**不新增监听、不改 SSH/NPS/systemd/Docker 网络**。
//
// 实现用 socketpair:Go 侧拿到的是 fd 支撑的真实 net.Conn(支持 SetDeadline,
// pgx 的连接/查询超时才能在拨号阶段生效),ssh 子进程的 stdin/stdout 指向同一对端的另一端。
//
// context 语义(刻意区分两段):
// - **拨号阶段**尊重 ctx:ctx 已取消就不再创建连接、不再启动子进程;
// - **连接建立之后不绑定这个 ctx** —— pgx 在连接成功后就会取消拨号 ctx,
// 若把连接生命周期挂上去,健康连接会被立刻掐断。连接生命周期绑定在
// "连接关闭 ⇄ 子进程回收" 这对关系上(见 tunnelConn.Close)。
//
// 依赖:运行环境里必须有 ssh 客户端与已批准的密钥/known_hosts。容器内 localhost 不等于
// 宿主机 —— 容器没有 ssh 能力时返回 ErrUnavailable;**不擅自复制私钥、不放宽 known_hosts、
// 不改 network_mode**。
// dialAddress 是**配置里 DSN 的主机:端口**。为什么必须用它、而不是 pgx 传进来的 addr:
// pgx 会先在**本机**解析域名,本机若开了 Clash/mihomo 之类的 Fake-IP(198.18.0.0/15)或
// 其他 DNS 劫持,解析结果是假地址;把假地址交给 ssh 去连必然挂住(实测:20s 超时)。
// 固定审批的隧道应当让**远端**解析并连接配置里的主机名 —— 这也是"不接受任意主机"的同一原则。
func SSHDialer(target, dialAddress string) (func(ctx context.Context, network, addr string) (net.Conn, error), error) {
if target == "" {
return nil, fmt.Errorf("%w: ssh target is required", ErrUnavailable)
}
if strings.TrimSpace(dialAddress) == "" {
return nil, fmt.Errorf("%w: dial address is required", ErrUnavailable)
}
if _, err := exec.LookPath("ssh"); err != nil {
return nil, fmt.Errorf("%w: ssh client is not available in this environment", ErrUnavailable)
}
return func(ctx context.Context, _ string, _ string) (net.Conn, error) {
addr := dialAddress
if err := ctx.Err(); err != nil {
return nil, fmt.Errorf("%w: ssh dial cancelled before start", ErrUnavailable)
}
fds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_STREAM, 0)
if err != nil {
return nil, fmt.Errorf("%w: cannot create a socketpair for the ssh tunnel", ErrUnavailable)
}
localEnd := os.NewFile(uintptr(fds[0]), "kg-ssh-tunnel-local")
remoteEnd := os.NewFile(uintptr(fds[1]), "kg-ssh-tunnel-child")
conn, err := net.FileConn(localEnd)
_ = localEnd.Close()
if err != nil {
_ = remoteEnd.Close()
return nil, fmt.Errorf("%w: cannot wrap the ssh tunnel in a connection", ErrUnavailable)
}
command := exec.Command("ssh",
"-o", "BatchMode=yes",
"-o", "ExitOnForwardFailure=yes",
"-o", "ServerAliveInterval=15",
"-W", addr, target)
command.Stdin = remoteEnd
command.Stdout = remoteEnd
// ssh 自身的 stderr 一律丢弃:里面可能带主机名/路径;失败统一上抛 ErrUnavailable。
command.Stderr = io.Discard
if err := command.Start(); err != nil {
_ = remoteEnd.Close()
_ = conn.Close()
return nil, fmt.Errorf("%w: cannot start the ssh tunnel", ErrUnavailable)
}
_ = remoteEnd.Close()
// reaped 必须先初始化:reap() 会在子进程退出时 close 它(nil channel 会 panic)。
tunnel := &tunnelConn{Conn: conn, command: command, reaped: make(chan struct{})}
go tunnel.reap()
return tunnel, nil
}, nil
}
// tunnelConn 把"连接关闭 ⇄ 子进程回收"显式绑定起来:
// - 连接被关(pgx 归还/释放连接、或对端断开)⇒ 子进程收到终止信号并回收,不留孤儿;
// - 子进程自己退出(隧道断/认证失败)⇒ Go 侧连接立刻关掉,让 pgx 马上感知断开;
// - Close 幂等,且不阻塞在等待子进程上(最多等一个短宽限期)。
type tunnelConn struct {
net.Conn
command *exec.Cmd
closeOnce sync.Once
reaped chan struct{}
}
func (t *tunnelConn) reap() {
if t.command != nil {
_ = t.command.Wait()
}
if t.reaped != nil {
close(t.reaped)
}
// 子进程退出 ⇒ 连接必然无用,主动关掉让调用方立刻看到 EOF。
_ = t.Conn.Close()
}
func (t *tunnelConn) Close() error {
var err error
t.closeOnce.Do(func() {
err = t.Conn.Close()
// 连接关闭后 ssh 通常自行退出;这里补一刀保证它不会挂着不退。
if t.command.Process != nil {
_ = t.command.Process.Signal(syscall.SIGTERM)
}
select {
case <-t.Exited():
case <-time.After(2 * time.Second):
if t.command.Process != nil {
_ = t.command.Process.Kill()
}
}
})
return err
}
// Exited 让测试/运维能确认子进程已经回收(不暴露任何连接信息)。
func (t *tunnelConn) Exited() <-chan struct{} {
if t.reaped == nil {
closed := make(chan struct{})
close(closed)
return closed
}
return t.reaped
}