Documentation
¶
Overview ¶
Package runner executes external commands — docker, pg_dump, rsync — with the subprocess semantics that long-running programs need:
- Pipefail: a pipeline fails if ANY stage fails. The leftmost failure is reported as the root cause (downstream failures are usually its cascade), and no failure is ever masked by a later stage's success. No shell is ever invoked — arguments go to execve verbatim — so pipefail is implemented by the runner itself and there is no shell-injection surface.
- SIGPIPE/EPIPE: a command whose reader closed the pipe early is reported distinctly (ErrBrokenPipe), never conflated with a command malfunction; and a real command failure is never masked by the SIGPIPE cascade it caused upstream.
- Both exit status and stderr are captured: a non-zero exit is never silently swallowed, and a redacted stderr tail rides along in every error.
- Context cancellation kills the whole pipeline and is reported as cancellation, not as a spurious "signal: killed".
- On Linux, every started command is SIGKILLed if the host program itself dies, so no orphaned child process keeps working after the host's run lock is released.
Index ¶
- Variables
- func CheckCredentialFile(path string) error
- func FileEnv(dir string, files map[string]string) ([]string, error)
- func FindCredentialDir(name string, dirs ...string) string
- func LoadCredentialValue(dir, name string) (string, error)
- type AbortError
- type BrokenPipeError
- type Command
- type ExitError
- type Result
- type Runner
- type SignalError
Constants ¶
This section is empty.
Variables ¶
var ErrBrokenPipe = errors.New("downstream reader closed the pipe early")
ErrBrokenPipe marks the distinct condition of a reader closing a pipe early: the writer was cut off, which is not a command malfunction. Match it with errors.Is(err, ErrBrokenPipe).
Functions ¶
func CheckCredentialFile ¶
CheckCredentialFile validates that path is a regular file readable only by its owner (0600 or stricter) — the same rule FileEnv applies to every credential path it resolves. Exported so other packages that read a credential file's *contents* directly (e.g. internal/notify, for secrets an in-process HTTP client needs in memory rather than as a subprocess env var pointing at a file) can apply the identical check without duplicating it.
The file's contents are never touched here: only its mode is inspected, so this can be called before deciding whether it is even safe to read.
func FileEnv ¶
FileEnv builds KEY=<dir>/<name> environment entries pointing at credential files inside dir, for programs that accept credential *file* paths (CRED_PASSWORD_FILE, AWS_SHARED_CREDENTIALS_FILE, a tool's own config file, ...).
dir must be absolute — resolve it at runtime via the config package ($CREDENTIALS_DIRECTORY semantics). Every file must exist, be a regular file, and be readable only by its owner (0600 or stricter); anything looser is a loud error, not a warning. File contents are never read: only paths ever leave this function, so the caller can log which directory was used without risking a leak.
func FindCredentialDir ¶
FindCredentialDir returns the first of dirs that holds an entry called name, so a credential can live either where the operator put it ($CREDENTIALS_DIRECTORY under systemd) or where the program saved it itself. When none holds it, the first non-empty dir is returned, so a "missing file" error names the operator-facing location. Empty dirs are skipped. Only paths are inspected, never contents.
func LoadCredentialValue ¶
LoadCredentialValue reads the trimmed contents of a root-only credential file (systemd LoadCredential= semantics via $CREDENTIALS_DIRECTORY) and returns it as the secret value itself — e.g. an ntfy topic URL, a webhook URL, or a templated secret value.
This is the counterpart to FileEnv for callers that need the secret value in memory rather than a file path in an env var: an in-process HTTP client or a value about to be forwarded into a container's environment. It reuses CheckCredentialFile so every credential-reading path enforces the exact same permission rule (secrets must never leak).
dir must be an absolute path to the credential directory; name must be a plain file name inside it (no path separators or ".." components). The file must be a regular file readable only by its owner (0600 or stricter) — anything looser is a loud error, not a warning.
The file's contents are never included in a returned error or in any log line: only the directory and file name ever appear there, so callers can log or wrap this function's errors freely.
Types ¶
type AbortError ¶
AbortError reports a command stopped early because its own stderr showed a failure that retrying cannot fix (Command.AbortOn).
func (*AbortError) Error ¶
func (e *AbortError) Error() string
Error describes the failure in plain English.
type BrokenPipeError ¶
type BrokenPipeError struct {
Cmd string // program name of the cut-off writer
}
BrokenPipeError reports a command whose reader closed its pipe before the command finished writing (EPIPE/SIGPIPE). It is distinct from ExitError: the command did not malfunction — its consumer went away. Matches ErrBrokenPipe.
func (*BrokenPipeError) Error ¶
func (e *BrokenPipeError) Error() string
Error describes the condition in plain English.
func (*BrokenPipeError) Is ¶
func (e *BrokenPipeError) Is(target error) bool
Is reports whether target is ErrBrokenPipe.
type Command ¶
type Command struct {
Name string // program name or absolute path
Args []string // arguments, excluding argv[0]
Env []string // extra KEY=VALUE entries; override BaseEnv duplicates
Dir string // working directory; empty means current directory
// AbortOn, when set, is called with each complete stderr line as
// the command runs. Returning true stops the whole pipeline at
// once and makes it fail with an *AbortError. It exists for tools
// that retry a failure no retry can fix (some tools retry a rejected
// credential for many minutes) — it only ever turns a certain failure
// into an early one, never a failure into success. Lines are raw
// (unredacted): the predicate must not log or keep them.
AbortOn func(line string) bool
}
Command is one external program invocation. Name is resolved against $PATH when it contains no path separator. Arguments are passed to execve verbatim — no shell is involved.
type ExitError ¶
type ExitError struct {
Cmd string // program name
Code int // exit status
Stderr string // redacted stderr tail
}
ExitError reports a command that exited with a non-zero status.
type Result ¶
type Result struct {
// Stdout is the full stdout, captured when no stdout writer was
// given. It is raw payload data and is never redacted: do not log it.
Stdout []byte
Stderr []byte // stderr tail (at most StderrCap bytes), redacted
ExitCode int // exit status; -1 when killed by a signal
Signaled bool // true when the command was killed by a signal
Signal syscall.Signal // the killing signal, when Signaled
Duration time.Duration // wall time from start to reap
}
Result describes how one command finished.
type Runner ¶
type Runner struct {
// BaseEnv is the base environment for every command; a command's
// own Env entries override duplicate keys. Nil uses os.Environ().
BaseEnv []string
// Redact holds secret strings (passwords, keys) that must never
// reach logs or error messages: every occurrence in captured
// stderr is replaced with "[redacted]" before it can leak. Nil
// redacts nothing.
Redact *secret.Set
// StderrCap bounds how many bytes of stderr are retained per
// command (the tail is kept). Zero uses a 64 KiB default.
StderrCap int
}
Runner executes external commands with the pipefail/SIGPIPE semantics described above. The zero value is ready to use.
func (*Runner) Pipeline ¶
func (r *Runner) Pipeline(ctx context.Context, stdin io.Reader, stdout io.Writer, stages ...Command) ([]Result, error)
Pipeline executes stages connected stdout→stdin with real OS pipes, exactly like a shell pipeline with `set -o pipefail`: backpressure and SIGPIPE behave as the kernel dictates, every stage is waited for, and the pipeline fails if ANY stage fails.
stdin feeds the first stage (nil = /dev/null); stdout drains the last stage (nil = captured into the last Result's Stdout). Every stage's stderr is tail-captured into its Result. The per-stage Results are returned even on error.
Error classification, in priority order:
- ExitError — the leftmost stage that exited non-zero (root cause).
- context error — cancellation; any "signal: killed" outcome is the runner's own kill.
- unexpected wait errors that are not exit-status outcomes.
- SignalError — a stage killed by a signal other than SIGPIPE.
- output writer failure — the caller's stdout writer failed (e.g. disk full); any SIGPIPE death above is its consequence.
- stdin feed failure — the caller's stdin reader failed; if the first stage merely closed stdin early yet exited 0 (truncated input), that is a BrokenPipeError instead.
- BrokenPipeError — a stage died of SIGPIPE while every downstream reader exited 0 (reader closed early on purpose).
func (*Runner) Run ¶
func (r *Runner) Run(ctx context.Context, stdin io.Reader, stdout io.Writer, c Command) (Result, error)
Run executes a single command to completion. stdin may be nil (the command reads /dev/null); stdout may be nil (stdout is captured into Result.Stdout). The Result is returned even on error so callers can inspect partial output.
type SignalError ¶
type SignalError struct {
Cmd string // program name
Signal syscall.Signal // the killing signal
Stderr string // redacted stderr tail
}
SignalError reports a command killed by a signal other than SIGPIPE (a SIGPIPE death is the BrokenPipeError case instead).
func (*SignalError) Error ¶
func (e *SignalError) Error() string
Error describes the failure in plain English.