process

package
v0.10.1 Latest Latest
Warning

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

Go to latest
Published: Feb 6, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Overview

Package process provides the process runner implementation on the host.

Index

Constants

View Source
const DefaultBashScriptFilePattern = "gpud-*.bash"

Variables

View Source
var (
	ErrProcessNotStarted = errors.New("process not started")
	ErrProcessAborted    = errors.New("process aborted")
)
View Source
var (
	ErrProcessAlreadyRunning = errors.New("process already running")
)
View Source
var ErrProcessAlreadyStarted = errors.New("process already started")

Functions

func CheckRunningByPid added in v0.3.7

func CheckRunningByPid(ctx context.Context, processName string) bool

func CountProcessesByStatus added in v0.1.5

func CountProcessesByStatus(ctx context.Context) (map[string][]ProcessStatus, error)

CountProcessesByStatus counts all processes by its process status.

func CountRunningPids added in v0.3.1

func CountRunningPids() (uint64, error)

CountRunningPids returns the number of running pids.

func Read added in v0.3.6

func Read(ctx context.Context, p Process, opts ...ReadOpOption) error

Types

type Op

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

type OpOption

type OpOption func(*Op)

func WithAllowDetachedProcess added in v0.10.0

func WithAllowDetachedProcess(allow bool) OpOption

WithAllowDetachedProcess controls whether backgrounded processes can outlive the parent shell.

When allow=true:

  • Setpgid is NOT set (processes run in parent's process group)
  • Only the direct child process (shell) is killed on Close()
  • Backgrounded processes (using "&") become orphans and continue running
  • USE THIS for scripts that end with patterns like: "sleep 10 && systemctl restart gpud &"

When allow=false (DEFAULT):

  • Setpgid is set (creates a new process group)
  • Close() kills the entire process group (parent AND all children)
  • Safer behavior that prevents orphaned/leaked processes
  • USE THIS for normal commands where you want clean process cleanup

Example use case for allow=true:

Package installation scripts often end with:
  sleep 10 && systemctl restart gpud &
This schedules a delayed restart of gpud after the script exits.
Without allowDetachedProcess=true, the backgrounded command would be killed
when Close() is called.

Example:

p, err := New(
    WithBashScriptContentsToRun(deployScript),
    WithAllowDetachedProcess(true),
)

func WithBashScriptContentsToRun added in v0.0.4

func WithBashScriptContentsToRun(script string) OpOption

Sets the bash script contents to run. This is useful for running multiple/complicated commands.

func WithBashScriptFilePattern added in v0.4.4

func WithBashScriptFilePattern(pattern string) OpOption

Sets the pattern of the bash script file names. Default is to use "tmpbash*.bash".

func WithBashScriptTmpDirectory added in v0.4.4

func WithBashScriptTmpDirectory(dir string) OpOption

Sets the temporary directory to store bash script files. Default is to use the system's temporary directory.

func WithCommand added in v0.0.4

func WithCommand(args ...string) OpOption

Add a new command to run.

func WithCommands added in v0.0.4

func WithCommands(commands [][]string) OpOption

Sets/overwrites the commands to run.

func WithEnvs

func WithEnvs(envs ...string) OpOption

Add a new environment variable to the process in the format of `KEY=VALUE`.

func WithLabel added in v0.3.7

func WithLabel(key, value string) OpOption

func WithOutputFile

func WithOutputFile(file *os.File) OpOption

Sets the file to which stderr and stdout will be written. For instance, you can set it to os.Stderr to pipe all the sub-process stderr and stdout to the parent process's stderr. Default is to set the os.Pipe to forward its output via io.ReadCloser.

If the process exits with a non-zero exit code, stdout/stderr pipes may not work. If retry configuration is specified, specify the output file to read all the output.

func WithRestartConfig

func WithRestartConfig(config RestartConfig) OpOption

Configures the process restart behavior. If the process exits with a non-zero exit code, stdout/stderr pipes may not work.

func WithRunAsBashScript

func WithRunAsBashScript() OpOption

Set true to run commands as a bash script. This is useful for running multiple/complicated commands.

func WithRunBashInline added in v0.8.0

func WithRunBashInline() OpOption

WithRunBashInline executes the bash script without creating a temp file. Implementation note:

  • We prefer `bash -s` and feed the script via stdin (instead of `bash -c`). Why `-s` over `-c` across macOS and Linux:
  • No ARG_MAX issues: `-s` reads the script from stdin; `-c` places the entire script into an argv element, which can hit kernel argument-length limits.
  • Fewer quoting pitfalls: `-c` requires double-quoting/escaping the whole script; stdin avoids extra quoting layers and shell metacharacter surprises.
  • Same semantics on macOS and Linux: both support `-s` and `-c` consistently; stdin is the most portable way for inline scripts.

Default remains file-backed (WithRunAsBashScript without inline) for backwards compatibility; use this when disk writes are undesirable (e.g., "no space left on device").

type Process

type Process interface {
	// Starts the process but does not wait for it to exit.
	Start(ctx context.Context) error
	// Returns true if the process is started.
	Started() bool

	// StartAndWaitForCombinedOutput starts the process and returns the combined output of the command.
	// Returns ErrProcessAlreadyStarted if the process is already started.
	StartAndWaitForCombinedOutput(ctx context.Context) ([]byte, error)

	// Closes the process (aborts if still running) and waits for it to exit.
	// Cleans up the process resources.
	//
	// CLOSE BEHAVIOR DEPENDS ON allowDetachedProcess:
	//
	// With WithAllowDetachedProcess(true):
	//   - Only kills the direct child process
	//   - Backgrounded processes (e.g., "sleep 10 && systemctl restart gpud &")
	//     become orphans and continue running
	//   - Use this for scripts that need to spawn long-running background processes
	//
	// Without WithAllowDetachedProcess (default):
	//   - Kills the entire process group (parent AND all children)
	//   - Cancels the process context (triggers cmd.Cancel() -> SIGKILL)
	//   - Sends SIGTERM to the process group, falls back to SIGKILL after 3 seconds
	//   - Safer behavior that prevents orphaned/leaked processes
	Close(ctx context.Context) error
	// Returns true if the process is closed.
	Closed() bool

	// Waits for the process to exit and returns the error, if any.
	// If the command completes successfully, the error will be nil.
	Wait() <-chan error

	// Returns the current pid of the process.
	PID() int32

	// Returns the exit code of the process.
	// Returns 0 if the process is not started yet.
	// Returns non-zero if the process exited with a non-zero exit code.
	ExitCode() int32

	// Returns the stdout reader.
	// stderr/stdout piping sometimes doesn't work well on latest mac with io.ReadAll
	// Use bufio.NewScanner(p.StdoutReader()) instead.
	//
	// If the process exits with a non-zero exit code, stdout/stderr pipes may not work.
	// If retry configuration is specified, specify the output file to read all the output.
	//
	// The returned reader is set to nil upon the abort call on the process,
	// to prevent redundant closing of the reader.
	StdoutReader() io.Reader

	// Returns the stderr reader.
	// stderr/stdout piping sometimes doesn't work well on latest mac with io.ReadAll
	// Use bufio.NewScanner(p.StderrReader()) instead.
	//
	// If the process exits with a non-zero exit code, stdout/stderr pipes may not work.
	// If retry configuration is specified, specify the output file to read all the output.
	//
	// The returned reader is set to nil upon the abort call on the process,
	// to prevent redundant closing of the reader.
	StderrReader() io.Reader
}

func New

func New(opts ...OpOption) (Process, error)

type ProcessStatus added in v0.5.0

type ProcessStatus interface {
	Name() (string, error)
	PID() int32
	Status() ([]string, error)
}

ProcessStatus represents the read-only status of a process. Derived from "github.com/shirou/gopsutil/v4/process.Process" struct. ref. https://pkg.go.dev/github.com/shirou/gopsutil/v4@v4.25.3/process#Process

func FindProcessByName added in v0.5.0

func FindProcessByName(ctx context.Context, processName string) (ProcessStatus, error)

FindProcessByName finds a process by its name.

type ReadOp added in v0.3.6

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

type ReadOpOption added in v0.3.6

type ReadOpOption func(*ReadOp)

func WithInitialBufferSize added in v0.4.3

func WithInitialBufferSize(size int) ReadOpOption

Sets the initial buffer size for the scanner. Defaults to 4096 bytes.

func WithProcessLine added in v0.3.6

func WithProcessLine(fn func(line string)) ReadOpOption

Sets a function to process each line of the command output. Helps with debugging if command times out in the middle of reading.

func WithReadStderr added in v0.3.6

func WithReadStderr() ReadOpOption

func WithReadStdout added in v0.3.6

func WithReadStdout() ReadOpOption

func WithWaitForCmd added in v0.3.6

func WithWaitForCmd() ReadOpOption

type RestartConfig

type RestartConfig struct {
	// Set true to restart the process on error exit.
	OnError bool
	// Set the maximum number of restarts.
	Limit int
	// Set the interval between restarts.
	Interval time.Duration
}

RestartConfig is the configuration for the process restart. If the process exits with a non-zero exit code, stdout/stderr pipes may not work. If retry configuration is specified, specify the output file to read all the output.

type Runner added in v0.5.0

type Runner interface {
	// RunUntilCompletion starts a bash script, blocks until it finishes,
	// and returns the output and the exit code.
	// Whether to return an error when there is already a process running is up to the implementation.
	// Optional OpOption arguments can be passed to customize process behavior
	// (e.g., WithAllowDetachedProcess(true) for scripts with backgrounded commands).
	RunUntilCompletion(ctx context.Context, script string, opts ...OpOption) ([]byte, int32, error)
}

Runner defines the interface for a process runner. It facillitates scheduling and running arbitrary bash scripts.

func NewExclusiveRunner added in v0.5.0

func NewExclusiveRunner() Runner

Directories

Path Synopsis
examples
simple-command command
simple-commands command
stream-commands command

Jump to

Keyboard shortcuts

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