runner

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: Apache-2.0 Imports: 15 Imported by: 1 module, 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 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

Constants

This section is empty.

Variables

View Source
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

func CheckCredentialFile(path string) error

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

func FileEnv(dir string, files map[string]string) ([]string, error)

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

func FindCredentialDir(name string, dirs ...string) string

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

func LoadCredentialValue(dir, name string) (string, error)

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

type AbortError struct {
	Cmd    string // program name
	Stderr string // redacted stderr tail
}

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.

func (*ExitError) Error

func (e *ExitError) Error() string

Error describes the failure in plain English.

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:

  1. ExitError — the leftmost stage that exited non-zero (root cause).
  2. context error — cancellation; any "signal: killed" outcome is the runner's own kill.
  3. unexpected wait errors that are not exit-status outcomes.
  4. SignalError — a stage killed by a signal other than SIGPIPE.
  5. output writer failure — the caller's stdout writer failed (e.g. disk full); any SIGPIPE death above is its consequence.
  6. 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.
  7. 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.

Jump to

Keyboard shortcuts

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