exechelper

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2020 License: Apache-2.0 Imports: 11 Imported by: 13

README

exechelper is a simple wrapper around standard go 'exec' that tries to follow the spirit of its API closely

Its main features are:

  1. It allows you to pass strings containing the command you want executed instead of an array of args.
  2. It's Start() returns an errCh that will get zero or one errors, and be closed after the command has finished running
  3. You can use the WithXYZ pattern to do things like customize things like Stdout, Stdin, StdError, Dir, and Env variables

Run Examples:

if err := exechelper.Run("go list -m");err != nil {...}

if err := exechelper.Run("go list -m",WithEnv(os.Environs()));err != nil {...}

if err := exechelper.Run("go list -m",WithDir(dir)); err != nil {...}

outputBuffer := bytes.NewBuffer([]byte{})
errBuffer := bytes.NewBuffer([]bytes{})
if err := exechelper.Run("go list -m",WithStdout(outputBuffer),WithStderr(errBuffer));err != nil {...}

Start Examples

ctx,cancel := context.WithCancel(context.Background())
errCh := exechelper.Start(startContext,"spire-server run",WithContext(ctx))

// cancel() - will stop the running cmd if its still running
// <-errCh - provides any error from the Start.  Will always have zero or one err, so <-errCh will block until Start has finished
//           For non-zero Exit code will return a exec.ExitError
//           Note: cancel() will almost always result in a non-zero exit code

Similarly, exechelper.Output(...), exechelper.CombinedOutput(...) are provided.

Multiplexing Stdout/Stderr

WithStdout and WithStderr can be used multiple times, with each provided io.Writer provided getting a copy of the stdout/stderr. As many WithStdout or WithStderr options may be used on the same Run/Start/Output/CombinedOutput as you wish

Example:

outputBuffer := bytes.NewBuffer([]byte{})
errBuffer := bytes.NewBuffer([]bytes{})
if err := exechelper.Run("go list -m",WithStdout(outputBuffer),WithStderr(errBuffer),WithStdout(os.Stdout),WithStderr(os.Stderr));err != nil {...}
// stdout of "go list -m" is written to both outputBuffer and os.Stdout.  stderr is written to both errBuffer and os.Stdout

Terminating with SIGTERM and a grace period

By default, canceling the context on a Start will result in SIGKILL being sent to the child process (this is how exec.Cmd works). It is often useful to send SIGTERM first, and allow a grace period before sending SIGKILL to allow processes the opportunity to clean themselves up.

Example:

ctx,cancel := context.WithCancel(context.Background())
errCh := exechelper.Start(startContext,"spire-server run",WithContext(ctx),WithGracePeriod(30*time.Second))
cancel()
<-errCh
// Calling cancel will send SIGTERM to the spire-server and wait up to 30 seconds for it to exit before sending SIGKILL
// errCh will receive any errors from the exit of spire-server immediately after spire-server exiting, whether that
// is immediately, any time during the 30 second grace period, or after the SIGKILL is sent

Documentation

Overview

Package exechelper provides a wrapper around cmd.Exec that makes it easier to use

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CombinedOutput

func CombinedOutput(cmdStr string, options ...*Option) ([]byte, error)

CombinedOutput - Creates a exec.Cmd using cmdStr. Runs exec.Cmd.CombinedOutput and returns the resulting output as []byte and error

func Output

func Output(cmdStr string, options ...*Option) ([]byte, error)

Output - Creates a exec.Cmd using cmdStr. Runs exec.Cmd.Output and returns the resulting output as []byte and error

func Run

func Run(cmdStr string, options ...*Option) error

Run - Creates a exec.Cmd using cmdStr. Runs exec.Cmd.Run and returns the resulting error

func Start

func Start(cmdStr string, options ...*Option) <-chan error

Start - Creates an exec.Cmd cmdStr. Runs exec.Cmd.Start.

Types

type CmdFunc

type CmdFunc func(cmd *exec.Cmd) error

CmdFunc function for setting exec.Cmd parameters.

type Option

type Option struct {
	// Context - context (if any) for running the exec.Cmd
	Context context.Context
	// SIGTERM grace period
	GracePeriod time.Duration
	// CmdFunc to be applied to the exec.Cmd
	CmdOption CmdFunc

	// PostRunOption - CmdFunc to be applied to the exec.Cmd after running
	PostRunOption CmdFunc
}

Option - expresses optional behavior for exec.Cmd

func CmdOption

func CmdOption(cmdFunc CmdFunc) *Option

CmdOption - convenience function for producing an Option that only has an Option.CmdOption

func WithArgs

func WithArgs(args ...string) *Option

WithArgs - appends additional args to cmdStr

useful for ensuring correctness when you start from
args []string rather than from a cmdStr to be parsed

func WithContext

func WithContext(ctx context.Context) *Option

WithContext - option for setting the context.Context for running the exec.Cmd

func WithDir

func WithDir(dir string) *Option

WithDir - Option that will create the requested dir if it does not exist and set exec.Cmd.Dir = dir

func WithEnvKV

func WithEnvKV(envs ...string) *Option

WithEnvKV - add entries to exec.Cmd as a series key,value pairs in a list of strings Existing instances of 'key' will be overwritten Example: WithEnvKV(key1,value2,key2,value2...)

func WithEnvMap

func WithEnvMap(envMap map[string]string) *Option

WithEnvMap - add entries to exec.Cmd from envMap Existing instances of 'key' will be overwritten Example: WithEnvKV(map[string]string{key1:value1,key2:value2})

func WithEnvirons

func WithEnvirons(environs ...string) *Option

WithEnvirons - add entries to exec.Cmd.Env as a series of "key=value" strings Example: WithEnvirons("key1=value1","key2=value2",...)

func WithGracePeriod added in v1.0.2

func WithGracePeriod(gracePeriod time.Duration) *Option

WithGracePeriod - will send a SIGTERM when ctx.Done() and wait up to gracePeriod before SIGKILLing the process.

func WithNetNS added in v1.0.3

func WithNetNS(handle netns.NsHandle) *Option

WithNetNS - run the cmd in the network namespace (netNS) specified by handle.

func WithOnDeathSignalChildren added in v1.0.2

func WithOnDeathSignalChildren(signal syscall.Signal) *Option

WithOnDeathSignalChildren - set the signal that will be sent to children of process on processes death (only available on linux)

func WithStderr

func WithStderr(writer io.Writer) *Option

WithStderr - option to provide a writer to receive exec.Cmd.Stderr

if multiple WithStderr options are received, they are combined
with an io.Multiwriter

func WithStdin

func WithStdin(reader io.Reader) *Option

WithStdin - option to set exec.Cmd.Stdout

func WithStdout

func WithStdout(writer io.Writer) *Option

WithStdout - option to provide a writer to receive exec.Cmd.Stdout

if multiple WithStdout options are received, they are combined
with an io.Multiwriter

Directories

Path Synopsis
testcmds

Jump to

Keyboard shortcuts

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