Skip to content

Commit

Permalink
Add timeout option
Browse files Browse the repository at this point in the history
  • Loading branch information
larrabee committed Mar 23, 2018
1 parent 10cc5b4 commit 92e49cf
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 2 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@

main
release/
.idea/
1 change: 1 addition & 0 deletions ewn/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ type Args struct {
DontDuplicate bool `arg:"--dont-duplicate" help:"Not run process when process with same key already run"`
DontDuplicateKey string `arg:"--dont-duplicate-key" help:"Default: --command value"`
Retry int `help:"Retry run N times on fail."`
Timeout int `arg:"-t" help:"Kill process after N seconds. Default: 0"`
RetrySleep int `arg:"--retry-sleep" help:"Sleep between retries (seconds)"`
Config string `help:"Path to config file."`
InitConfig bool `help:"Write default config to --config path and exit"`
Expand Down
14 changes: 13 additions & 1 deletion ewn/ewn.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,9 @@ type Message struct {
}

// Popen execute given command and return retry structure
func Popen(command string) (result Retry, err error) {
func Popen(command string, timeout time.Duration) (result Retry, err error) {
var outB bytes.Buffer
var timer *time.Timer
result.StartTime = time.Now().UTC()
cmd := exec.Command("/bin/bash", "-c", command)
if isatty.IsTerminal(os.Stdout.Fd()) {
Expand All @@ -42,8 +43,19 @@ func Popen(command string) (result Retry, err error) {
}

err2 := cmd.Start()
if timeout > time.Duration(0) {
timer = time.AfterFunc(timeout, func() {
cmd.Process.Kill()
})
}


_ = cmd.Wait()

if timeout > time.Duration(0) {
timer.Stop()
}

result.Output = outB.String()
result.EndTime = time.Now().UTC()
result.Duration = result.EndTime.Sub(result.StartTime)
Expand Down
3 changes: 2 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"os"
"os/signal"
"syscall"
"time"
)

func main() {
Expand Down Expand Up @@ -55,7 +56,7 @@ func main() {

RetryLoop:
for retryCounter := 1; retryCounter <= cli.Retry; retryCounter++ {
retry, err := ewn.Popen(cli.Command)
retry, err := ewn.Popen(cli.Command, time.Duration(cli.Timeout) * time.Second)
if err != nil {
msg.GeneralError = err
ewn.Notify(&msg, cfg)
Expand Down

0 comments on commit 92e49cf

Please sign in to comment.