sshmgr

package
v0.107.34 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 35 Imported by: 0

Documentation

Overview

Package sshmgr runs SSHManager: SSH connections, shells, remote commands and SFTP for the hosts stored in sshhosts, opened by the K-brain process itself.

A session is one SSH connection to one host, owned by a project (the ProjectPathKey of the run's working directory) and shared by every conversation in that project. It may carry an interactive PTY shell and an SFTP client, both started on first use. Sessions stay open across turns and close after IdleTimeout without use, when their host's settings change, or when the backend closes.

Index

Constants

View Source
const (
	DefaultExecTimeout = 30 * time.Second
	MinExecTimeout     = time.Second
	MaxExecTimeout     = 300 * time.Second
	DefaultExecBytes   = 64 << 10
	MinExecBytes       = 4 << 10
	MaxExecBytes       = 256 << 10
)

Exec limits, as LiveAgent v1.

View Source
const (
	DefaultReadTextBytes = 200 << 10
	MinReadTextBytes     = 4 << 10
	MaxReadTextBytes     = 1 << 20
)

SFTP limits, as LiveAgent v1.

View Source
const (
	TransferQueued    = "queued"
	TransferRunning   = "running"
	TransferCompleted = "completed"
	TransferFailed    = "failed"
	TransferCancelled = "cancelled"
)

Transfer statuses.

View Source
const (
	DefaultReadBytes = 32 << 10
	MinReadBytes     = 4 << 10
	MaxReadBytes     = 128 << 10
	DefaultCols      = 120
	DefaultRows      = 32
)

Shell limits.

View Source
const (
	// DefaultIdleTimeout closes a session nobody used for this long.
	DefaultIdleTimeout = 30 * time.Minute
)
View Source
const ToolName = tools.SSHManagerTool

ToolName is the tool's name, as in LiveAgent v1.

Variables

This section is empty.

Functions

func NormalizeRemotePath

func NormalizeRemotePath(p string) string

NormalizeRemotePath is LiveAgent v1's normalize_remote_path: backslashes become slashes, "." and ".." parts are dropped, a leading "/" is kept and the empty path is ".".

func Tool

func Tool(m *Manager, opts ToolOptions) tools.Tool

Tool is SSHManager for the hosts and sessions of m. The project is the call's working directory (tools.WorkingDir).

Types

type ExecResult

type ExecResult struct {
	ExitCode        *int   `json:"exitCode"`
	ExitSignal      string `json:"exitSignal,omitempty"`
	Stdout          string `json:"stdout"`
	Stderr          string `json:"stderr"`
	StdoutBytes     int64  `json:"stdoutBytes"`
	StderrBytes     int64  `json:"stderrBytes"`
	StdoutTruncated bool   `json:"stdoutTruncated"`
	StderrTruncated bool   `json:"stderrTruncated"`
	TimedOut        bool   `json:"timedOut"`
	Cancelled       bool   `json:"cancelled,omitempty"`
	DurationMs      int64  `json:"durationMs"`
}

ExecResult is the outcome of a remote command. Field names follow LiveAgent v1's terminal_ssh_exec result.

type HostKeyChangedError

type HostKeyChangedError struct {
	Host      string
	Presented sshhosts.KnownKey
	Known     []sshhosts.KnownKey
}

HostKeyChangedError refuses a host whose key differs from the stored one.

func (*HostKeyChangedError) Error

func (e *HostKeyChangedError) Error() string

type Interaction

type Interaction struct {
	// Unattended: nobody can answer (scheduled runs). Connecting then needs a
	// saved credential and an already trusted host key; anything else fails
	// at once.
	Unattended bool
	// Ask asks a question (host key confirmation); nil when nobody can be
	// asked.
	Ask tools.AskFunc
	// Elicit shows a form (keyboard-interactive prompts); nil when no front
	// end can show one.
	Elicit elicit.Func
}

Interaction says what a call may ask the user.

type Manager

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

Manager owns every SSH session of the backend.

func New

func New(store *sshhosts.Store, opts Options) *Manager

New starts a manager for the hosts in store.

func (*Manager) Acquire

func (m *Manager) Acquire(ctx context.Context, project string, host sshhosts.Host, strategy Strategy, title string, inter Interaction) (Resolved, error)

Acquire returns a session to host for project per strategy, connecting when needed.

func (*Manager) Close

func (m *Manager) Close()

Close closes every session.

func (*Manager) CloseHostSessions

func (m *Manager) CloseHostSessions(id string)

CloseHostSessions closes every session to the host id, in every project.

func (*Manager) CloseSession

func (m *Manager) CloseSession(s *Session)

CloseSession closes one session.

func (*Manager) Hosts

func (m *Manager) Hosts() *sshhosts.Store

Hosts is the host store.

func (*Manager) Session

func (m *Manager) Session(project, id string) (*Session, bool)

Session returns the open session id of project.

func (*Manager) Sessions

func (m *Manager) Sessions(project string) []*Session

Sessions lists the open sessions of project, oldest first.

func (*Manager) Sync

func (m *Manager) Sync()

Sync closes the sessions whose host was deleted or whose connection settings changed. Call it after every change to the host store.

type Options

type Options struct {
	IdleTimeout time.Duration
	// contains filtered or unexported fields
}

Options configure a Manager.

type Resolved

type Resolved struct {
	Session  *Session
	Strategy string
	Reused   bool
	Created  bool
}

Resolved is the session a call runs on and how it was found.

type SFTPAction

type SFTPAction struct {
	Action   string         `json:"action"`
	Path     string         `json:"path"`
	Entry    *SFTPEntry     `json:"entry,omitempty"`
	Transfer *TransferState `json:"transfer,omitempty"`
}

SFTPAction is the result of a write, mkdir, rename or delete.

type SFTPEntry

type SFTPEntry struct {
	Path      string `json:"path"`
	Name      string `json:"name"`
	Kind      string `json:"kind"`
	SizeBytes int64  `json:"sizeBytes"`
	// Mtime is in milliseconds (second precision).
	Mtime int64 `json:"mtime"`
}

SFTPEntry is one remote file. Field names follow LiveAgent v1.

type SFTPList

type SFTPList struct {
	Path    string      `json:"path"`
	Entries []SFTPEntry `json:"entries"`
}

SFTPList is an sftp_list result.

type SFTPReadText

type SFTPReadText struct {
	Path      string     `json:"path"`
	Content   string     `json:"content"`
	Offset    int64      `json:"offset"`
	BytesRead int        `json:"bytesRead"`
	SizeBytes int64      `json:"sizeBytes"`
	Truncated bool       `json:"truncated"`
	Entry     *SFTPEntry `json:"entry,omitempty"`
}

SFTPReadText is an sftp_read_text result.

type SFTPStat

type SFTPStat struct {
	Exists bool       `json:"exists"`
	Entry  *SFTPEntry `json:"entry,omitempty"`
}

SFTPStat is an sftp_stat result.

type Session

type Session struct {
	ID         string
	ProjectKey string
	HostID     string
	Title      string
	CreatedAt  time.Time
	// contains filtered or unexported fields
}

Session is one SSH connection.

func (*Session) CancelTransfer

func (s *Session) CancelTransfer(id string) error

CancelTransfer stops a running transfer of s and waits briefly for it to stop.

func (*Session) Delete

func (s *Session) Delete(ctx context.Context, p string, recursive bool) (SFTPAction, error)

Delete removes a remote file, symlink or (with recursive) directory. A symlink is removed itself; its target is never followed.

func (*Session) EnableSFTP

func (s *Session) EnableSFTP(ctx context.Context) error

EnableSFTP starts the session's SFTP client when it has none.

func (*Session) Exec

func (s *Session) Exec(ctx context.Context, command, cwd string, timeout time.Duration, maxBytes int) (ExecResult, error)

Exec runs command on s over a new channel. Cancelling ctx (the run was cancelled) or reaching timeout sends SIGTERM and closes the channel.

func (*Session) Info

func (s *Session) Info() SessionInfo

Info describes s.

func (*Session) List

func (s *Session) List(ctx context.Context, p string) (SFTPList, error)

List lists a remote directory ("." is the login directory).

func (*Session) Mkdir

func (s *Session) Mkdir(ctx context.Context, p string) (SFTPAction, error)

Mkdir creates one remote directory.

func (*Session) ReadShell

func (s *Session) ReadShell(maxBytes int) (ShellOutput, error)

ReadShell returns the last maxBytes of the shell's output.

func (*Session) ReadText

func (s *Session) ReadText(ctx context.Context, p string, offset int64, maxBytes int) (SFTPReadText, error)

ReadText reads up to maxBytes of a remote file from offset as text.

func (*Session) Rename

func (s *Session) Rename(ctx context.Context, from, to string) (SFTPAction, error)

Rename renames a remote path.

func (*Session) Resize

func (s *Session) Resize(cols, rows int) error

Resize changes the shell's terminal size.

func (*Session) SendInput

func (s *Session) SendInput(data string) error

SendInput writes data to the shell.

func (*Session) StartTransfer

func (s *Session) StartTransfer(ctx context.Context, req TransferRequest) (TransferState, error)

StartTransfer validates req and runs it in the background. The returned state is "queued"; sftp_transfer_status follows it.

func (*Session) Stat

func (s *Session) Stat(ctx context.Context, p string) (SFTPStat, error)

Stat describes a remote path; a missing path is not an error.

func (*Session) TransferStatus

func (s *Session) TransferStatus(id string) (TransferResponse, error)

TransferStatus reports a transfer of s.

func (*Session) WriteText

func (s *Session) WriteText(ctx context.Context, p, content string, overwrite, createParents bool) (SFTPAction, error)

WriteText writes content to a remote file.

type SessionInfo

type SessionInfo struct {
	SessionID   string `json:"session_id"`
	HostID      string `json:"host_id"`
	Status      string `json:"status"`
	SFTPEnabled bool   `json:"sftpEnabled"`
	Shell       bool   `json:"shell"`
	Title       string `json:"title"`
	Running     bool   `json:"running"`
	CreatedAt   int64  `json:"created_at"`
	UpdatedAt   int64  `json:"updated_at"`
}

SessionInfo is a session as list_sessions reports it.

type ShellOutput

type ShellOutput struct {
	Output    string `json:"output"`
	Truncated bool   `json:"truncated"`
	// StartOffset and EndOffset place Output in everything the shell printed.
	StartOffset int64 `json:"outputStartOffset"`
	EndOffset   int64 `json:"outputEndOffset"`
	Exited      bool  `json:"exited"`
}

ShellOutput is a read_session result.

type Strategy

type Strategy string

Strategy is how a call finds its session when it names no session_id.

const (
	ReuseOrCreate   Strategy = "reuse_or_create"
	NewSession      Strategy = "new"
	RequireExisting Strategy = "require_existing"
)

type ToolOptions

type ToolOptions struct {
	// Interaction says, for a call's context, what the call may ask the
	// user. Nil means nobody can be asked.
	Interaction func(context.Context) Interaction
}

ToolOptions configure the tool.

type TransferRequest

type TransferRequest struct {
	// Upload: Local is the source, Remote the target directory. Download:
	// Remote is the source, Local the target directory.
	Upload bool
	// Local is an absolute local path already checked against the workspace.
	Local string
	// Display renders a local absolute path for the result.
	Display   func(string) string
	Remote    string
	Recursive bool
	Overwrite bool
}

TransferRequest starts an upload or download.

type TransferResponse

type TransferResponse struct {
	Transfer TransferState `json:"transfer"`
}

TransferResponse wraps a TransferState like LiveAgent v1.

type TransferState

type TransferState struct {
	ID          string `json:"id"`
	SessionID   string `json:"sessionId"`
	Direction   string `json:"direction"`
	Status      string `json:"status"`
	SourcePath  string `json:"sourcePath"`
	TargetPath  string `json:"targetPath"`
	CurrentPath string `json:"currentPath"`
	BytesDone   int64  `json:"bytesDone"`
	BytesTotal  int64  `json:"bytesTotal"`
	FilesDone   int    `json:"filesDone"`
	FilesTotal  int    `json:"filesTotal"`
	Error       string `json:"error,omitempty"`
}

TransferState is an upload or download as sftp_transfer_status reports it.

Directories

Path Synopsis
Package sshtest runs an SSH server inside the test process, on 127.0.0.1, for SSHManager tests.
Package sshtest runs an SSH server inside the test process, on 127.0.0.1, for SSHManager tests.

Jump to

Keyboard shortcuts

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