transport

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2026 License: GPL-3.0, LGPL-3.0 Imports: 30 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package transport runs commands on remote hosts through the OpenSSH client.

OpenSSH is driven rather than replaced, so ProxyJump, ControlMaster, Kerberos, the agent and the administrator's own configuration keep working exactly as they do from a shell.

A remote command is never built by joining words into a string. The argument vector is quoted once, handed to ssh as a single argument, and split back by the remote shell into exactly the arguments that were given, so a glob, an apostrophe or repeated whitespace survives the trip.

Index

Constants

View Source
const DefaultMaxOutput = 32 << 20

DefaultMaxOutput is how much of each output stream Run keeps unless a request says otherwise. A host controls its own output for as long as the command runs, and without a bound it could fill the memory of the CLI or the MCP server.

Variables

This section is empty.

Functions

func RemoteCommand

func RemoteCommand(req Request) (string, error)

RemoteCommand renders a request as the single argument ssh is given.

The result is one shell command line. The remote shell splits it back into the original argument vector, because every word was quoted.

Types

type Call

type Call struct {
	Target  Target
	Request Request
	// Command is the shell command line the request renders to, which is
	// what --dry-run prints and what the tests assert on.
	Command string
}

Call is one request a Recorder was asked to run.

func (Call) Describe

func (c Call) Describe() string

Describe renders a call the way --dry-run prints it.

type Client

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

Client drives the OpenSSH client.

func New

func New(opts Options) *Client

New returns a client. The ssh configuration is written on first use.

func (*Client) Args

func (c *Client) Args(target Target, req Request) ([]string, error)

Args builds the full argument vector, ssh included, that a request runs as. Commands use it for --dry-run and for reporting what they would do.

func (*Client) Binary

func (c *Client) Binary() string

Binary returns the ssh client to run.

func (*Client) Command added in v0.3.0

func (c *Client) Command() ([]string, error)

Command returns ssh with the generated configuration, the part of every argument vector that decides how a host is reached and which host key it must present. A program that runs ssh itself, such as sshuttle, is given this command, so that it connects the way every other connection does.

func (*Client) ConfigPath

func (c *Client) ConfigPath() (string, error)

ConfigPath returns the generated ssh configuration, writing it once.

func (*Client) Copy

func (c *Client) Copy(ctx context.Context, target Target, req CopyRequest) (*Result, error)

Copy runs a file transfer.

func (*Client) CopyArgs

func (c *Client) CopyArgs(target Target, req CopyRequest) ([]string, error)

CopyArgs builds the scp argument vector for a transfer.

func (*Client) Destination added in v0.3.0

func (c *Client) Destination(target Target) (string, error)

Destination renders the [user@]host a target is reached as, with the account resolved and checked as it is for a command.

func (*Client) Interactive

func (c *Client) Interactive(ctx context.Context, target Target, req Request) error

Interactive runs a request wired to the terminal, for a login shell or anything that needs to talk to the user.

func (*Client) JumpHosts added in v0.4.0

func (c *Client) JumpHosts(host string) []string

JumpHosts names the jump hosts ssh connects to on the way to host, each of which a session to host opens a connection to as well: the proxyJump chain of the role whose block matches host, and the chain of that chain's first hop, which ssh reaches with the hop's own block. The later hops are handed the rest of the chain instead of their own. It is empty when ssh connects to host directly. A jump host that only an included file or ssh.options names is not known here.

func (*Client) Run

func (c *Client) Run(ctx context.Context, target Target, req Request) (*Result, error)

Run executes a request and captures its output.

The output is also cut into lines as it arrives, for the request's OnLine and for a display that shows the lines of the span the context carries, which is the call a Traced runner reports. Run returns only once ssh has exited and both streams have been read to the end, which Wait does before it returns, so the call is still open when the last of the output reaches the display, and a line the output ended without a newline is shown before the call's end.

A request with a timeout is bounded here as well as on the host. timeout(1) ends the command only once it has reached the host, and only a host that still answers can say so, so a connection that hangs while it is made, or goes quiet while the command runs, would hold the caller for as long as ssh waits, minutes with its keepalives. ssh is stopped once the command has had its timeout, the grace timeout(1) gives it and the time the generated configuration lets reaching the host take; a host that answered has ended the command by then.

func (*Client) ScpBinary

func (c *Client) ScpBinary() string

ScpBinary returns the scp client to run.

type CopyRequest

type CopyRequest struct {
	// Sources are local paths when Upload is set, and remote paths
	// otherwise.
	Sources []string
	// Destination is the remote path when Upload is set, and a local path
	// otherwise.
	Destination string
	// Upload says which way the transfer goes.
	Upload bool
	// Recursive copies directories.
	Recursive bool
	// Preserve keeps modification times and modes.
	Preserve bool
	// Progress receives scp's standard output, where it draws its progress
	// meter when that is a terminal. nil discards it: the meters of
	// transfers running side by side would overwrite each other.
	Progress io.Writer
}

CopyRequest describes a file transfer.

type Options

type Options struct {
	// SSH is the transport configuration of the site.
	SSH v1alpha1.SSHSpec
	// Roles are the infrastructure roles, used for per role settings and
	// for resolving a jump host by name.
	Roles map[string]v1alpha1.HostRole
	// StateDir holds the generated configuration and the control sockets.
	StateDir string
	// KnownHostsFile is the host key file, already made absolute.
	KnownHostsFile string
	// DefaultUser is the account used where nothing names one.
	DefaultUser string
	// NoTerminal says that nobody is at a terminal to answer a prompt, as
	// under the MCP server. ssh is then run in batch mode and in a session
	// of its own, so that it fails instead of asking for a password or a
	// passphrase on whatever terminal the process was started from.
	NoTerminal bool
	// Context bounds what the client runs on its own account, such as
	// asking ssh for its version before the configuration is written; nil
	// is context.Background(). A request runs under the context it is
	// given.
	Context context.Context
}

Options configure a client.

func (Options) Validate added in v0.3.0

func (o Options) Validate() error

Validate checks everything the generated ssh configuration is built from.

Each value is written into a line of the file, so a line break in one would add a directive and a space would split it; ssh would then reject the whole file, or worse, obey the line. Jump chains are checked for cycles, because ssh follows one without end.

type Recorder

type Recorder struct {
	// Responses are returned in the order the calls arrive; once they run
	// out, an empty successful result is returned. A fan-out makes its
	// calls in any order, so Responses suit calls made one after another,
	// and ByTarget the calls of a fan-out.
	Responses []*Result
	// ByTarget holds the result for every call to a target, by the
	// target's name, whatever order the calls arrive in; nil is an empty
	// successful result. The calls to a target it does not name take
	// Responses.
	ByTarget map[string]*Result
	// Reply returns the result for a call. It wins over ByTarget and
	// Responses. It is called from as many goroutines at once as the
	// caller runs requests, so under a fan-out it must be safe for
	// concurrent use, and lock whatever it keeps between calls.
	Reply func(Target, Request) (*Result, error)
	// contains filtered or unexported fields
}

Recorder is a Runner that records requests instead of running them.

It backs --dry-run, where the point is to show exactly what would be sent, and the tests, where a real ssh is neither available nor wanted.

Whatever answers a call, its standard output and then its standard error are handed to the request's OnLine a line at a time, only the lines that ended, and to a display that shows the lines, as Client.Run hands on the output of ssh as it arrives.

func (*Recorder) Calls

func (r *Recorder) Calls() []Call

Calls returns the recorded requests.

func (*Recorder) Commands

func (r *Recorder) Commands() []string

Commands returns the rendered command line of each recorded request.

func (*Recorder) Run

func (r *Recorder) Run(ctx context.Context, target Target, req Request) (*Result, error)

Run implements Runner.

func (*Recorder) Sorted added in v0.4.0

func (r *Recorder) Sorted() []Call

Sorted returns the recorded requests ordered by target, in node set order, so that exe2 comes before exe10, and for each target in the order they were made. A fan-out makes its calls in any order; this is the order to compare or print them in.

type Request

type Request struct {
	// Argv is the remote command. An empty Argv and Script start an
	// interactive login.
	Argv []string
	// Script is a shell program run with the shell's -c, as one argument.
	// Argv and Script are mutually exclusive.
	Script string
	// TTY controls pseudo terminal allocation.
	TTY TTY
	// Timeout bounds the command. It is enforced on the target with
	// timeout(1), because killing the local ssh leaves the remote process
	// running. Run also stops ssh itself once the command has had its
	// timeout, killGrace and the time reaching the target may take, for a
	// host that stopped answering before timeout(1) could end the command.
	Timeout time.Duration
	// Stdin is fed to the command. Secrets travel this way so that they
	// never appear in an argument vector, where ps shows them.
	Stdin io.Reader
	// Stdout and Stderr receive the output when the command is run
	// interactively. Run captures them instead.
	Stdout, Stderr io.Writer
	// MaxOutput bounds how much of each of standard output and standard
	// error Run keeps; zero keeps up to DefaultMaxOutput.
	MaxOutput int
	// OnLine, when it is set, is handed each line of standard output and
	// standard error Run reads, as it arrives, for a parser that reports
	// on the items of a command that prints one line for each, such as a
	// target a display can end before the command has. It is handed only
	// lines that ended, without the "\n" and a "\r" before it; a line the
	// end of the output cut off, or one longer than 64 KiB, is none. It is
	// called from the goroutines that read the two streams, possibly at
	// the same time, and every call has returned before Run does. The
	// lines are the host's: nothing in them may be trusted. What Run
	// keeps of the output is not changed by it, and neither is MaxOutput,
	// which does not bound what OnLine is handed.
	OnLine func(stream progress.Stream, line string)
	// NoShell says the host's command line is not a POSIX shell, as on a
	// power distribution unit, so the command is sent without the guard that
	// tells its exit status 255 from ssh's, which it could not run. A 255
	// from such a command reads as a connection failure.
	NoShell bool
}

Request is what to run on a target.

type Result

type Result struct {
	Target   Target        `json:"target" yaml:"target"`
	ExitCode int           `json:"exitCode" yaml:"exitCode"`
	Stdout   string        `json:"stdout,omitempty" yaml:"stdout,omitempty"`
	Stderr   string        `json:"stderr,omitempty" yaml:"stderr,omitempty"`
	Duration time.Duration `json:"-" yaml:"-"`
	// Truncated says that the output was cut off at the request's
	// MaxOutput. Such a result has failed: what was kept is not all the
	// host said.
	Truncated bool `json:"truncated,omitempty" yaml:"truncated,omitempty"`
	// Err is set when the command could not be run or did not exit zero.
	Err error `json:"-" yaml:"-"`
}

Result is the outcome of one remote command.

func ExitResult added in v0.3.0

func ExitResult(target Target, code int, stdout, stderr string) *Result

ExitResult is the result Run reports for a command that ran and exited with a status, with its error set the same way. A stand-in for the client, such as a test's, uses it so that a failure looks as it would over ssh.

func (*Result) Check added in v0.4.0

func (r *Result) Check(program string) error

Check returns nil for a command that succeeded, and otherwise why it failed, as an error that carries its exit code. An error the transport coded itself, such as ssh's own exit 255 or an interrupt, is returned as it is, and one that came without an exit status is a transport failure. Any other failure is that of a host that answered: it exits 1, and what the command printed on standard error is the reason, its lines joined into one, or else the first line it printed on standard output. The reason is escaped, because the host wrote it. The error Run gave, such as a TimeoutError, is still found behind it with errors.As. program names what ran, for the message; it may be empty.

func (*Result) Failed

func (r *Result) Failed() bool

Failed reports whether the command did not succeed.

func (*Result) Lines

func (r *Result) Lines() []string

Lines returns the standard output split into non-empty lines.

func (Result) MarshalJSON added in v0.3.0

func (r Result) MarshalJSON() ([]byte, error)

MarshalJSON adds the error text to the result, which the machine formats would otherwise leave out: Err is an error value, not a string.

func (*Result) Output

func (r *Result) Output() string

Output returns the standard output with trailing newlines removed.

type Runner

type Runner interface {
	Run(ctx context.Context, target Target, req Request) (*Result, error)
}

Runner runs a command on a target. Commands depend on this rather than on the client, so that a dry run or a test can stand in for real ssh.

func Traced added in v0.4.0

func Traced(next Runner, dryRun bool) Runner

Traced returns a Runner that reports every request next runs as a call, "ssh", under the span its context carries: the target of a pool, a step, or the command itself. The call carries the node, the host, the role and the request's timeout, and ends with the command's exit status and the error it failed with, which says why it failed in a word: a host that could not be reached, a command that ran out of time or one that exited non-zero. The context next is given carries the call, so that what next reports of its own nests under it.

A dry run's recorder is traced with dryRun set: what it was given was recorded, not sent, so its calls are marked as a dry run's and end skipped. The real transport of a dry run's lookups is traced without it, since those reach the host.

Without a Bus in the context, nothing is reported, and the request runs as it would untraced.

type TTY

type TTY int

TTY says whether a pseudo terminal is allocated for a remote command.

const (
	// TTYAuto allocates a terminal for an interactive login and none for a
	// command, which is what ssh does on its own.
	TTYAuto TTY = iota
	// TTYForce allocates one even for a command, for anything that prompts.
	TTYForce
	// TTYNone never allocates one, so that output is not echoed back.
	TTYNone
)

type Target

type Target struct {
	// Name is the node or role as the administrator named it, used in
	// output and errors.
	Name string `json:"name" yaml:"name"`
	// Host is the name ssh connects to.
	Host string `json:"host" yaml:"host"`
	// User is the remote account; empty uses what the configuration says.
	User string `json:"user" yaml:"user"`
	// Role names the infrastructure role, when the target is one.
	Role string `json:"role,omitempty" yaml:"role,omitempty"`
	// ForwardAgent and ForwardX11 are requested per command, on top of what
	// the role already asks for.
	ForwardAgent bool `json:"forwardAgent,omitempty" yaml:"forwardAgent,omitempty"`
	ForwardX11   bool `json:"forwardX11,omitempty" yaml:"forwardX11,omitempty"`
}

Target is a host to run something on.

func (Target) String

func (t Target) String() string

String renders the target the way errors refer to it.

type TimeoutError added in v0.4.0

type TimeoutError struct {
	Target Target
	// ExitCode is timeout(1)'s: 124, or 137 when the command had to be
	// killed.
	ExitCode int
	Timeout  time.Duration
}

TimeoutError is the error of a remote command that timeout(1) ended because it ran for the whole of its request's Timeout. The host answered, so it reads and exits like any other command that exited with a status; only its progress class tells a display that the command ran out of time.

func (*TimeoutError) Error added in v0.4.0

func (e *TimeoutError) Error() string

func (*TimeoutError) ProgressClass added in v0.4.0

func (e *TimeoutError) ProgressClass() progress.Class

ProgressClass says that the command ran out of time.

Jump to

Keyboard shortcuts

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