exec

package module
v0.0.0-...-2c4334c Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2018 License: MIT Imports: 12 Imported by: 4

README

Exec-Go v0.2.1-alpha

External command exec library for golang

Check details at GoDoc

Features

  • Util of native os.exec.cmd library.
  • Pipeline library for commands.
  • (Planning) PipelineGroup for parallelly manage multi-pipelines.
  • (Plan to Deprecate) Cron Job function for command.

Cmd

  • Error Message
    Error from native library is the output of exit, you will get error like exit status 1 except real error message. Use cmd.Error() to get it.
  • Cancel
    For both Linux and Windows. On Linux, it will kill process and it's children. On Windows, it may not work if the process create child processes.
  • STDOUT Streaming
    You can do it by Read() and GetMsg()
    cmd := exec.NewCmd("", "bash", "-c", `echo 1; sleep 1; echo 1; sleep 1; echo 1; sleep 1;`)
      err := cmd.Start()
    if err != nil {
      log.Fatal(err)
    }
    for cmd.Read() {
      fmt.Println(string(cmd.GetMsg()))
    }
    err = cmd.Wait()
    if err != nil {
      log.Fatal(err)
    }
    
    Or setup EventHandler
    cmd := exec.NewCmd("", "bash", "-c", `echo 1; sleep 1; echo 1; sleep 1; echo 1; sleep 1;`)
    cmd.SetEventHandler(&exec.EventHandler{
      CmdRead: func(cmd *exec.Cmd) {
        fmt.Println(string(cmd.GetMsg()))
      },
    })
    

Pipeline

Run set of commands. Also support Cancel and STDOUT Streaming. About STDOUT Streaming of pipeline, currently only support EventHandler way.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultEventHandler = &EventHandler{}

DefaultEventHandler default event handler

Functions

func RunCmd

func RunCmd(dir, name string, arg ...string) (out string, err error)

RunCmd run cmd and wait for response

Types

type Cmd

type Cmd struct {
	// run at dir
	Dir string
	// target executable name
	Name string
	// arguments of cmd
	Args []string
	// exec started
	Started bool
	// exec canceled
	Canceled bool
	// exec timedout
	TimedOut bool
	// exec failed by error
	Failed bool
	// exec done
	Done bool
	// exec timeout
	Timeout time.Duration
	// exec duration
	Duration time.Duration
	// EventHandler pointer
	EventHandler *EventHandler
	// native exec.Cmd target
	Cmd *exec.Cmd
	// contains filtered or unexported fields
}

Cmd ...

func NewCmd

func NewCmd(dir string, name string, arg ...string) *Cmd

NewCmd new Cmd object

func (*Cmd) AddEnv

func (c *Cmd) AddEnv(name, value string) *Cmd

AddEnv add Env

func (*Cmd) Cancel

func (c *Cmd) Cancel()

Cancel terminate the command process

func (*Cmd) Error

func (c *Cmd) Error() string

Error get error output in string

func (*Cmd) GetCmd

func (c *Cmd) GetCmd() string

GetCmd get cmd string

func (*Cmd) GetMsg

func (c *Cmd) GetMsg() []byte

GetMsg get last output from cmd

func (*Cmd) Output

func (c *Cmd) Output() string

Output get outputs of cmd (without error) in string

func (*Cmd) Read

func (c *Cmd) Read() bool

Read read latest output from last Read()

func (*Cmd) Run

func (c *Cmd) Run() (string, error)

Run run cmd. If error, it return output until error and error messages as error.

func (*Cmd) SetEnv

func (c *Cmd) SetEnv(Env []string) *Cmd

SetEnv set Envs

func (*Cmd) SetEventHandler

func (c *Cmd) SetEventHandler(eh *EventHandler) *Cmd

SetEventHandler set event handler

func (*Cmd) SetTimeout

func (c *Cmd) SetTimeout(dur time.Duration) *Cmd

SetTimeout set timeout

func (*Cmd) Start

func (c *Cmd) Start() error

Start start cmd

func (*Cmd) Wait

func (c *Cmd) Wait() error

Wait wait for cmd until its done. It will return original error ( like exit(1) ) except error message. Use Error() to get error message.

type CmdEvent

type CmdEvent func(cmd *Cmd)

CmdEvent cmd event handle func

type Cron

type Cron struct {
	Stopped bool
	// contains filtered or unexported fields
}

Cron cron job scheduler

func NewCron

func NewCron() *Cron

NewCron get new Cron obejct

func (*Cron) DoJob

func (cr *Cron) DoJob(f func()) *Job

DoJob set schedule by timeSyntax which is the same as crontab's

func (*Cron) RemoveJob

func (cr *Cron) RemoveJob(id uint32)

RemoveJob remove job by id

func (*Cron) Start

func (cr *Cron) Start() error

Start start cron jobs

func (*Cron) Stop

func (cr *Cron) Stop()

Stop stop cron jobs

type EventHandler

type EventHandler struct {
	// trigger when cmd successfully started
	CmdStarted CmdEvent
	// trigger when cmd get any output ( error will trigger CmdFailed )
	CmdRead CmdEvent
	// trigger when cmd be canceled
	CmdCanceled CmdEvent
	// trigger when cmd failed which means process throw error
	CmdFailed CmdEvent
	// trigger when cmd done without any error
	CmdDone CmdEvent

	// trigger when pipeline successfully started
	PipelineStarted PipelineEvent
	// trigger when pipeline be canceled
	PipelineCanceled PipelineEvent
	// trigger when pipeline failed
	PipelineFailed PipelineEvent
	// trigger when pipeline done without any error
	PipelineDone PipelineEvent
}

EventHandler bind event hanlder to do logging or other handling as you want be careful that all event handler function will be triggered synchronously to provide you synchronously control. use `go func()` inside handler for asynchronously control

type HandleFunc

type HandleFunc func(output string, err error) (success bool, msg string)

HandleFunc handler after execution of Cmd

type Job

type Job struct {
	ID      uint32
	Stopped bool
	// contains filtered or unexported fields
}

Job cron job instance

func (*Job) Every

func (j *Job) Every(v ...int) uint32

Every set specific time in [second(0~59), minute(0~59), hour(0~23), day(1~31), month(1~12)], unset part will be pretended as every (*). Invalid value will be set to first valid value. Return trigger id.

func (*Job) EveryDay

func (j *Job) EveryDay() uint32

EveryDay setup trigger which run job every day (00:00:00)

func (*Job) EveryHour

func (j *Job) EveryHour() uint32

EveryHour setup trigger which run job every hour (**:00:00)

func (*Job) EveryMinute

func (j *Job) EveryMinute() uint32

EveryMinute setup trigger which run job every minute (**:**:00)

func (*Job) EveryMonth

func (j *Job) EveryMonth() uint32

EveryMonth setup trigger which run job every month (1st 00:00:00)

func (*Job) EverySecond

func (j *Job) EverySecond() uint32

EverySecond setup trigger which run job every second (**:**:**)

func (*Job) EveryWeek

func (j *Job) EveryWeek() uint32

EveryWeek setup trigger which run job every week (Sunday 00:00:00)

func (*Job) EveryWeekDay

func (j *Job) EveryWeekDay(weekday int, n ...int) uint32

EveryWeekDay setup trigger which run job every weekday at time. If time unset it will be 00:00:00.

func (*Job) EveryYear

func (j *Job) EveryYear() uint32

EveryYear setup trigger which run job every year (Jan 1st 00:00:00)

func (*Job) RemoveTrigger

func (j *Job) RemoveTrigger(id uint32)

RemoveTrigger remove trigger by id

func (*Job) Restart

func (j *Job) Restart()

Restart restart this job

func (*Job) Stop

func (j *Job) Stop()

Stop stop this job

type PipeCmd

type PipeCmd struct {
	Cmd        *Cmd
	HandleFunc HandleFunc
	HandleMsg  string
	DelayDur   time.Duration
	// contains filtered or unexported fields
}

PipeCmd cmd in pipeline

func (*PipeCmd) Delay

func (pcmd *PipeCmd) Delay(dur time.Duration) *PipeCmd

Delay delay cmd execution

func (*PipeCmd) Handle

func (pcmd *PipeCmd) Handle(f HandleFunc) *PipeCmd

Handle set HandleFunc to cmd for handling final output or error.

func (*PipeCmd) Run

func (pcmd *PipeCmd) Run() error

Run run pipeline, pointer of pipeline.Run()

func (*PipeCmd) SkipErr

func (pcmd *PipeCmd) SkipErr(f HandleFunc) *PipeCmd

SkipErr add handler after cmd to skip err.

func (*PipeCmd) Start

func (pcmd *PipeCmd) Start() error

Start start pipeline, pointer of pipeline.Start()

func (*PipeCmd) Then

func (pcmd *PipeCmd) Then(name string, arg ...string) *PipeCmd

Then define next step in pipeline

type Pipeline

type Pipeline struct {
	// pipeline started
	Started bool
	// pipeline done
	Done bool
	// pipeline failed
	Failed bool
	// pipeline canceld
	Canceled bool
	// pipline Timedout
	Timedout bool
	// Cmd pointer slice
	PipeCmds []*PipeCmd
	// current index of PipeCmd
	CurrentIndex int
	// EventHandler
	EventHandler *EventHandler
	// TimeoutDur duration
	TimeoutDur time.Duration
	// FailureMsg custom error message when failed at handler
	FailureMsg string
	// contains filtered or unexported fields
}

Pipeline commands pipeline

func NewPipeline

func NewPipeline() *Pipeline

NewPipeline new pipeline.

func (*Pipeline) AddEnv

func (pipe *Pipeline) AddEnv(name, value string) *Pipeline

AddEnv Add Env.

func (*Pipeline) Cancel

func (pipe *Pipeline) Cancel()

Cancel cancel pipeline

func (*Pipeline) Do

func (pipe *Pipeline) Do(name string, arg ...string) *PipeCmd

Do add cmd to pipeline. It use latest Dir/Env you set before.

func (*Pipeline) Finished

func (pipe *Pipeline) Finished() bool

Finished pipeline lifecycle is finished or not

func (*Pipeline) GetCmdsOutput

func (pipe *Pipeline) GetCmdsOutput() (string, error)

GetCmdsOutput get output of all Cmds concat into one string

func (*Pipeline) RemoveEnv

func (pipe *Pipeline) RemoveEnv(name string) *Pipeline

RemoveEnv Remove Env by name.

func (*Pipeline) Run

func (pipe *Pipeline) Run() error

Run run pipeline and wait for result

func (*Pipeline) SetCmdEventHandler

func (pipe *Pipeline) SetCmdEventHandler(eh *EventHandler) *Pipeline

SetCmdEventHandler set Event Handler for cmds. It inheirt from pipeline's by default.

func (*Pipeline) SetEnv

func (pipe *Pipeline) SetEnv(keyValue string, more ...string) *Pipeline

SetEnv replace whole Env for cmds. KeyValue should be like 'Key=Value'.

func (*Pipeline) SetPipelineEventHandler

func (pipe *Pipeline) SetPipelineEventHandler(eh *EventHandler) *Pipeline

SetPipelineEventHandler set event handler of pipeline

func (*Pipeline) SetTimeout

func (pipe *Pipeline) SetTimeout(dur time.Duration) *Pipeline

SetTimeout set timeout

func (*Pipeline) Start

func (pipe *Pipeline) Start() error

Start start pipeline

func (*Pipeline) Under

func (pipe *Pipeline) Under(dir string) *Pipeline

Under under which dir.

func (*Pipeline) Wait

func (pipe *Pipeline) Wait() error

Wait block until Done/Failed/Canceled

type PipelineEvent

type PipelineEvent func(pipe *Pipeline)

PipelineEvent pipeline event handle func

Jump to

Keyboard shortcuts

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