executor

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: Apache-2.0 Imports: 12 Imported by: ? 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.

README

executor

executor is a Go library for running external commands with precise, tested semantics: portable command and process contracts, a local os/exec implementation with bounded output capture, process-group control and graceful cancellation, ordered parallel batches, line-prefixed output streaming, and a thin adapter for remote transports. It is for Go developers who build tools, pipeline runners, job agents and CLIs that start other programs and need to stop them reliably and report what happened.

Programs run directly. A shell is involved only when you ask for one through Shell or ShellWith; the module adds no transport, PTY, sandbox or durable process manager.

Features

  • Command contract: Command describes path, arguments, working directory, environment (inherited with overrides, or cleared with ClearEnv), optional standard streams and per-stream capture limits. Validate checks portable invariants; Clone copies Args and Env.
  • Local execution: local.New() returns an Executor that runs commands with os/exec, streams output to your writers while capturing it, and reports exit code, timing and resource Usage.
  • Start, wait and control: Start returns a Process with repeatable Wait, Signal, Kill and Export. The start context owns the process lifetime; wait contexts bound only the wait.
  • Process groups and graceful stop: ProcessGroup makes signals and cancellation reach grandchildren; KillGrace sends TERM first and KILL after a grace period.
  • Shell commands: Shell and ShellWith run scripts through the platform shell or an interpreter of your choice, in their own process group.
  • Bounded capture: MaxStdoutBytes/MaxStderrBytes cap retained output while writers still receive every byte.
  • Ordered batches: RunAll runs commands with bounded concurrency, returns results in input order and stops on the first failure.
  • Prefixed output: NewPrefixWriter labels lines and never interleaves lines from concurrent commands that share a destination.
  • Remote adapters: NewRemote turns any one-method Starter into an Executor.
  • Errors that keep the result: non-zero exits return the populated Result and an *ExitError. No logging; safe for concurrent use.

Installation

go get github.com/justusschock/executor@latest

Requires Go 1.25 or newer. Import the contracts and the local implementation as:

import (
	executor "github.com/justusschock/executor"
	"github.com/justusschock/executor/local"
)

Quick start

Run a shell command locally and inspect the result. This is the package Example, so it is compiled and checked by go test:

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) // hello 0
}

example_test.go also has ExampleRunAll, ExampleNewPrefixWriter and ExampleNewRemote; local/example_test.go shows Executor.Run.

Run a program directly
result, err := local.New().Run(ctx, executor.Command{
	Path:           "go",
	Args:           []string{"version"},
	Stdout:         os.Stdout, // streamed live and captured in result.Stdout
	Stderr:         os.Stderr,
	MaxStdoutBytes: 1 << 20, // retain at most 1 MiB; os.Stdout still gets everything
	MaxStderrBytes: 1 << 20,
})

By default the child inherits the current environment with Command.Env entries overriding it. With ClearEnv: true, only Command.Env is supplied; os/exec may still add values the platform requires (on Windows, SYSTEMROOT). ClearEnv does not change how Path is looked up.

A positive capture limit retains that stream's prefix, keeps draining the child, forwards every byte to the configured writer, and sets Result.StdoutTruncated or Result.StderrTruncated when bytes were dropped. Zero retains everything; negative limits are invalid.

Start and control a process
processContext, cancelProcess := context.WithCancel(context.Background())
defer cancelProcess()

process, err := local.New().Start(processContext, executor.Command{Path: "go", Args: []string{"version"}})
if err != nil {
	return err
}

waitContext, cancelWait := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelWait()
result, err := process.Wait(waitContext)
  • The context passed to Start owns the child's lifetime. Cancelling it stops the child (or its process group); Run still waits until the child has been reaped.
  • A context passed to Wait bounds only that call. A timed-out Wait leaves the process running, and a later Wait returns the final result. Every Wait returns independently owned output.
  • Signal takes exact uppercase names: TERM, KILL, INT and HUP on Unix-like systems, KILL on Windows. Kill stops the process unconditionally.
Shell scripts and process groups

Shell runs a script through /bin/sh -c on Unix-like systems (/system/bin/sh -c on Android) and cmd.exe /d /s /c on Windows. ShellWith selects another interpreter; each zero ShellOptions field falls back to DefaultShell:

train := executor.Shell("python train.py --lr 0.1")
train.Dir = "pipelines/model"

strict := executor.ShellWith(executor.ShellOptions{
	Path: "bash",
	Args: []string{"-euo", "pipefail", "-c"},
}, "make data | tee data.log")

The shell interprets the script, so never interpolate untrusted input into it. Shell commands set ProcessGroup: true and KillGrace: DefaultKillGrace (10 seconds); any command can set these fields.

  • ProcessGroup starts the child as the leader of a new process group (Setpgid on Unix). On Windows it uses CREATE_NEW_PROCESS_GROUP and a Job Object, falling back to taskkill /T /F. Signal, Kill and start-context cancellation then reach grandchildren; after the group has been reaped they return os.ErrProcessDone. Do not pass a terminal as stdin to a Unix group child: it is not in the terminal's foreground group.
  • KillGrace controls start-context cancellation. Zero kills immediately; a positive value sends TERM and then KILL if the process has not been reaped when the grace period ends. Windows has no TERM and kills immediately.
Run commands concurrently
commands := []executor.Command{
	{Path: "go", Args: []string{"env", "GOOS"}},
	{Path: "go", Args: []string{"env", "GOARCH"}},
}
results, err := executor.RunAll(ctx, local.New(), commands, 2)

RunAll makes at most limit concurrent Run calls and returns results in input order. On the first failure it stops admitting commands, cancels the running ones through their contexts, waits for them and returns no results; failures are labelled with their command index and joined. A non-positive limit returns concurrency.ErrInvalidLimit from concurrency.

Label streamed output
stdout := executor.NewPrefixWriter(os.Stdout, "[train] ")
defer stdout.Close()

command := executor.Shell("python train.py")
command.Stdout = stdout
command.Stderr = stdout

Prefix writers that share a destination serialize their writes, and each destination write contains only complete lines. A partial line longer than MaxPrefixLineBytes (64 KiB) is emitted in chunks. Close each writer after its command finishes to flush the last partial line and release the shared destination lock.

Resource usage

Result.Usage is filled for successful runs and ExitError results; zero means "not reported":

  • UserCPU and SystemCPU on every platform.
  • MaxRSSBytes (peak resident set size) on Unix-like systems.
  • ReadBytes and WriteBytes (storage I/O, excluding page-cache hits) on Linux and Android.

On Unix-like systems the values include descendants the child waited for, so a shell's usage includes the programs it ran in the foreground.

Remote adapters and process references

A transport implements one method and gets a full Executor:

type Starter interface {
	Start(context.Context, executor.Command) (executor.Process, error)
}

remote, err := executor.NewRemote(myStarter)

Remote.Start clones and validates the command before forwarding it; Remote.Run is one Start and one Wait with the same context. Transport, authentication and custody are the adapter's responsibility.

Process.Export returns a handoff.Artifact from lifecycle with media type application/vnd.justusschock.process-reference+json, version 1, and only the JSON fields pid, path and started_at. Arguments, environment and streams are never included. Export does not transfer custody, and a reference can become stale. Remote.Adopt returns ErrUnsupportedAdoption.

Packages

Package Import path Purpose
executor github.com/justusschock/executor Contracts (Command, Executor, Process, Result, ExitError), shells, RunAll, NewPrefixWriter, Remote
local github.com/justusschock/executor/local Executor implementation for the local machine using os/exec

Anything under internal/ (none today) is not part of the API.

Design and guarantees

  • Concurrency: local.Executor, its processes and prefix writers are safe for concurrent use; Remote is safe when its Starter is. RunAll requires an executor that supports concurrent Run calls. Commands are cloned before execution, but Stdin, Stdout and Stderr remain shared references; synchronize a stream that several commands share.

  • Errors: a non-zero exit or wait failure (including a failing output writer) returns both the populated Result and an *executor.ExitError; use errors.As to get it and errors.Is to find its cause, including a start-context context.Canceled or context.DeadlineExceeded. Invalid commands wrap ErrInvalidCommand, typed-nil streams wrap ErrNilDependency, unsupported signal names wrap ErrInvalidSignal.

    result, err := local.New().Run(ctx, command)
    if err != nil {
    	var exit *executor.ExitError
    	if errors.As(err, &exit) {
    		// result and exit.Result both hold the captured outcome.
    	}
    	if errors.Is(err, context.DeadlineExceeded) {
    		// The start context expired and the process was stopped.
    	}
    }
    
  • Platforms: the root package contains no OS process code. local supports Windows and aix, android, darwin, dragonfly, freebsd, linux, netbsd, openbsd and solaris. Plan 9, JavaScript and WASI are not supported.

  • Stability: the module is v0.x. Minor releases may break the API; every break is listed in CHANGELOG.md and backed by an ADR.

Documentation

Contributing

Contributions are welcome through pull requests; nothing is pushed to main directly. Read AGENTS.md first: it describes the docs-first process, the public API rules and the checks to run before opening a pull request.

License

Licensed under the Apache License, Version 2.0. See LICENSE and NOTICE.

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

View Source
const DefaultKillGrace = 10 * time.Second

DefaultKillGrace is the termination grace period selected by Shell and ShellWith.

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

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

func Shell(script string) Command

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.

func (Command) Clone

func (c Command) Clone() Command

Clone owns Args and Env while preserving the supplied stream references.

func (Command) Validate

func (c Command) Validate() error

Validate checks portable command and dependency invariants.

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

type ExitError struct {
	Result Result
	Cause  error
}

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.

func (*ExitError) Error

func (e *ExitError) Error() string

Error reports the exit code and, when present, the cause.

func (*ExitError) Unwrap

func (e *ExitError) Unwrap() error

Unwrap returns Cause.

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

func NewRemote(starter Starter) (*Remote, error)

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) Adopt

Adopt is unsupported because a process reference does not transfer custody.

func (*Remote) Run

func (remote *Remote) Run(ctx context.Context, command Command) (Result, error)

Run calls Start and then Wait on the returned process, both with ctx, and returns Wait's result and error unchanged.

func (*Remote) Start

func (remote *Remote) Start(ctx context.Context, command Command) (Process, error)

Start clones and validates command and forwards it with ctx to the Starter exactly once. Validation errors wrap ErrInvalidCommand or ErrNilDependency; the Starter's process and error are returned 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

func RunAll(ctx context.Context, runner Executor, commands []Command, limit int) ([]Result, error)

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

type Starter interface {
	Start(context.Context, Command) (Process, error)
}

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.

Directories

Path Synopsis
Package local implements executor.Executor for the local machine with os/exec.
Package local implements executor.Executor for the local machine with os/exec.

Jump to

Keyboard shortcuts

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