Documentation
¶
Overview ¶
Package executor defines portable contracts for running external commands: a Command description, the Executor and Process interfaces, the final Result with captured output and resource Usage, and the ExitError returned for non-zero exits and wait failures.
The package contains no operating-system process code. The local subpackage implements Executor with os/exec; Remote adapts any Starter (for example a network transport) to Executor. RunAll runs commands with bounded concurrency and ordered results, Shell and ShellWith build commands that run a script through a shell, and NewPrefixWriter labels streamed output lines.
Commands are copied before execution: Args and Env are owned by the executor, while Stdin, Stdout and Stderr remain shared references that the caller must synchronize when several commands share them.
Example ¶
Run a shell command on the local machine and inspect its result.
package main
import (
"context"
"errors"
"fmt"
"log"
"strings"
executor "github.com/justusschock/executor"
"github.com/justusschock/executor/local"
)
func main() {
result, err := local.New().Run(context.Background(), executor.Shell("echo hello"))
if err != nil {
var exit *executor.ExitError
if errors.As(err, &exit) {
fmt.Println("exit code:", exit.Result.ExitCode)
}
log.Fatal(err)
}
fmt.Println(strings.TrimSpace(string(result.Stdout)), result.ExitCode)
}
Output: hello 0
Index ¶
Examples ¶
Constants ¶
const DefaultKillGrace = 10 * time.Second
DefaultKillGrace is the termination grace period selected by Shell and ShellWith.
const MaxPrefixLineBytes = 64 << 10
MaxPrefixLineBytes bounds the partial line a prefix writer buffers. A longer line without a newline, such as carriage-return progress output, is emitted in chunks of this size, each completed with a newline.
Variables ¶
var ( // ErrInvalidCommand reports a Command that fails Validate. ErrInvalidCommand = errors.New("executor: invalid command") // ErrInvalidSignal reports a signal name the platform does not support. ErrInvalidSignal = errors.New("executor: invalid signal") // ErrNotStarted reports an operation on a process that was never started. ErrNotStarted = errors.New("executor: process not started") // ErrProcessExited reports an export of a process that has already exited. ErrProcessExited = errors.New("executor: process exited") // ErrNilDependency reports a nil or typed-nil dependency, such as a nil // Starter, Executor or stream implementation. ErrNilDependency = errors.New("executor: nil dependency") // ErrUnsupportedAdoption reports that an adapter cannot adopt an exported // process reference. ErrUnsupportedAdoption = errors.New("executor: unsupported adoption") )
Sentinel errors. Errors returned by this module wrap them with %w; test them with errors.Is.
Functions ¶
func NewPrefixWriter ¶
func NewPrefixWriter(w io.Writer, prefix string) io.WriteCloser
NewPrefixWriter returns a line-buffered writer that writes every line to w as prefix followed by the line. Writes are safe for concurrent use, and all prefix writers that share the same w serialize their writes to it, so lines from different writers never interleave mid-line. Each underlying write contains only complete lines.
Close writes a buffered partial line, completed with a newline, and releases the shared destination lock. Close is idempotent; Write after Close returns io.ErrClosedPipe. w must be non-nil and is never closed. A w whose dynamic value is not comparable cannot be identified, so such writers share one process-wide lock instead.
Example ¶
NewPrefixWriter labels every line, which keeps output from concurrent commands readable when it shares one destination.
package main
import (
"bytes"
"fmt"
executor "github.com/justusschock/executor"
)
func main() {
var output bytes.Buffer
writer := executor.NewPrefixWriter(&output, "[train] ")
_, _ = writer.Write([]byte("epoch 1\nepoch"))
_, _ = writer.Write([]byte(" 2\npartial"))
_ = writer.Close()
fmt.Print(output.String())
}
Output: [train] epoch 1 [train] epoch 2 [train] partial
Types ¶
type Command ¶
type Command struct {
Path string
Args []string
Dir string
Env map[string]string
// ClearEnv prevents executors from supplying the parent environment. Env
// entries are still supplied explicitly, and the underlying platform may
// add critical values. The zero value preserves environment inheritance.
ClearEnv bool
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
// MaxStdoutBytes and MaxStderrBytes bound retained output independently.
// Zero keeps all output; configured stream writers still receive every byte.
MaxStdoutBytes int64
MaxStderrBytes int64
// ProcessGroup starts the command as the leader of a new process group
// (Unix) or process group and Job Object (Windows). Signal, Kill, and
// start-context cancellation then target the whole group, including
// grandchildren. The zero value targets only the direct child.
ProcessGroup bool
// KillGrace is the delay between the terminate request and the forced
// kill when the start context ends. Zero kills immediately, which is the
// compatibility behavior. Platforms without a terminate signal kill
// immediately regardless of the grace period.
KillGrace time.Duration
}
Command describes one process invocation. Args and Env are owned by Clone; stream references are shallow and may require caller synchronization when shared across concurrent commands.
func Shell ¶
Shell returns a command that runs script through DefaultShell. The command runs in its own process group with DefaultKillGrace, so cancellation reaches every program the script starts. Callers may change any field of the returned command before running it. The script is interpreted by the shell; never interpolate untrusted input into it.
func ShellWith ¶
func ShellWith(options ShellOptions, script string) Command
ShellWith returns a Shell command that uses options to select the interpreter. The script is always passed as the final argument.
type Executor ¶
type Executor interface {
// Run starts the command and waits for its final Result. A non-zero exit
// or wait failure returns the populated Result and an *ExitError.
Run(context.Context, Command) (Result, error)
// Start validates and starts the command and returns a handle to it. The
// meaning of the context for the process lifetime is defined by the
// implementation; for local.Executor it owns the child's lifetime.
Start(context.Context, Command) (Process, error)
}
Executor starts commands and waits for their results. Implementations must support concurrent method calls when used with RunAll. Run returns a final Result whose captured streams remain stable after the call returns.
type ExitError ¶
ExitError reports a process that exited with a non-zero code or whose wait failed, for example because a configured output writer returned an error or the start context ended. Result holds the same snapshot the call returned. Cause is reachable through errors.Is and errors.As; for local executions it is the os/exec wait error, joined with the start context's cause when that context ended.
type Process ¶
type Process interface {
// Wait blocks until the process has finished or the context ends.
// Cancelling the context ends only this call, never the process, and Wait
// may be called again.
Wait(context.Context) (Result, error)
// Signal sends a signal by exact uppercase name, such as "TERM". Names
// the platform does not support return an error wrapping ErrInvalidSignal.
Signal(context.Context, string) error
// Kill unconditionally stops the process.
Kill(context.Context) error
// Export returns a reference to the live process without transferring
// custody. It returns ErrNotStarted or ErrProcessExited when the process
// is unavailable.
Export(context.Context) (handoff.Artifact, error)
}
Process controls and observes one started command. Every Wait call returns independently owned captured streams that remain stable after return.
type Remote ¶
type Remote struct {
// contains filtered or unexported fields
}
Remote adapts a Starter to Executor. It owns and validates commands before forwarding them. Remote is safe for concurrent use when its Starter is.
func NewRemote ¶
NewRemote returns a Remote that forwards to starter. A nil or typed-nil starter returns an error wrapping ErrNilDependency.
Example ¶
NewRemote adapts any Starter to Executor. A local executor is used here as the Starter; a real adapter would forward the command over a transport.
package main
import (
"context"
"fmt"
"log"
"strings"
executor "github.com/justusschock/executor"
"github.com/justusschock/executor/local"
)
func main() {
remote, err := executor.NewRemote(local.New())
if err != nil {
log.Fatal(err)
}
result, err := remote.Run(context.Background(), executor.Shell("echo remote"))
if err != nil {
log.Fatal(err)
}
fmt.Println(strings.TrimSpace(string(result.Stdout)))
}
Output: remote
func (*Remote) Run ¶
Run calls Start and then Wait on the returned process, both with ctx, and returns Wait's result and error unchanged.
type Result ¶
type Result struct {
ExitCode int
StartedAt time.Time
FinishedAt time.Time
Stdout []byte
Stderr []byte
// StdoutTruncated and StderrTruncated report output omitted by capture limits.
StdoutTruncated bool
StderrTruncated bool
// Usage reports resource consumption when the executor can observe it.
// Zero fields mean the value is unknown, not that nothing was consumed.
Usage Usage
}
Result is a final execution snapshot. Stdout and Stderr are owned by the caller; executor implementations must not retain and later mutate them. Truncation flags are final for the corresponding captured streams.
func RunAll ¶
RunAll executes commands with at most limit concurrent calls to runner and preserves command order in successful results. Runner must support concurrent Run calls. Commands are cloned eagerly, but their stream references remain shallow; callers sharing streams must synchronize them.
A command error stops further admission, cancels admitted peers through their contexts, waits for those peers to finish, and returns nil results. Errors from admitted commands are indexed and joined in admission order. An invalid limit is returned as concurrency.ErrInvalidLimit.
Example ¶
RunAll runs commands with bounded concurrency and returns results in command order.
package main
import (
"context"
"fmt"
"log"
"strings"
executor "github.com/justusschock/executor"
"github.com/justusschock/executor/local"
)
func main() {
commands := []executor.Command{
executor.Shell("echo first"),
executor.Shell("echo second"),
}
results, err := executor.RunAll(context.Background(), local.New(), commands, 2)
if err != nil {
log.Fatal(err)
}
for index, result := range results {
fmt.Println(index, strings.TrimSpace(string(result.Stdout)))
}
}
Output: 0 first 1 second
type ShellOptions ¶
type ShellOptions struct {
// Path is the interpreter program. Empty selects the DefaultShell path.
Path string
// Args precede the script, for example []string{"-euo", "pipefail", "-c"}
// for bash. Empty selects the DefaultShell arguments.
Args []string
}
ShellOptions selects the interpreter used by ShellWith. Each zero field falls back to the platform default independently.
func DefaultShell ¶
func DefaultShell() ShellOptions
DefaultShell returns the platform interpreter used by Shell: "/bin/sh -c" on Unix-like systems ("/system/bin/sh -c" on Android) and "cmd.exe /d /s /c" on Windows. Each call returns independently owned arguments.
type Starter ¶
Starter is the command-starting port used by Remote. Implementations own transport, authentication and session semantics; they receive a validated command whose Args and Env they may keep.
type Usage ¶
type Usage struct {
// MaxRSSBytes is the peak resident set size in bytes.
MaxRSSBytes int64
// UserCPU and SystemCPU are the CPU time spent in user and kernel mode.
UserCPU time.Duration
SystemCPU time.Duration
// ReadBytes and WriteBytes approximate storage I/O. They are zero when the
// platform does not report byte-granular block I/O.
ReadBytes int64
WriteBytes int64
}
Usage is a best-effort resource accounting snapshot for one finished process. Unix-like local executions report the child's rusage, which also includes descendants the child waited for, such as programs run by a shell.