Skip to content

Commit

Permalink
Use context.Context for timeout in SSHContext.CmdInteractive
Browse files Browse the repository at this point in the history
  • Loading branch information
adamtulinius committed Feb 19, 2019
1 parent facd2f2 commit 3761136
Showing 1 changed file with 18 additions and 33 deletions.
51 changes: 18 additions & 33 deletions ssh/ssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,40 +153,25 @@ func valCommand(parts []string) ([]string, error) {
return parts, nil
}

func (ctx *SSHContext) CmdInteractive(host Host, timeout int, parts ...string) {
doneChan := make(chan bool)
timeoutChan := make(chan bool)
var cmd *exec.Cmd
var err error
if timeout > 0 {
go func() {
time.Sleep(time.Duration(timeout) * time.Second)
timeoutChan <- true
}()
}
go func() {
cmd, err = ctx.Cmd(host, parts...)
if err == nil {
cmd.Stdout = os.Stderr
cmd.Stderr = os.Stderr
err = cmd.Run()
}
doneChan <- true
func (sshCtx *SSHContext) CmdInteractive(host Host, timeout int, parts ...string) {
ctx, cancel := context.WithTimeout(context.TODO(), time.Duration(timeout)*time.Second)
defer cancel()

if err != nil && !<-timeoutChan {
fmt.Fprintf(os.Stderr, "Exec of cmd: %s failed with err: '%s'\n", parts, err.Error())
}
}()

for {
select {
case <-timeoutChan:
fmt.Fprintf(os.Stderr, "Exec of cmd: %s timed out\n", parts)
cmd.Process.Kill()
return
case <-doneChan:
return
}
cmd, err := sshCtx.CmdContext(ctx, host, parts...)
if err == nil {
cmd.Stdout = os.Stderr
cmd.Stderr = os.Stderr
err = cmd.Run()
}

// context was cancelled
if ctx.Err() != nil {
fmt.Fprintf(os.Stderr, "Exec of cmd: %s timed out\n", parts)
return
}

if err != nil {
fmt.Fprintf(os.Stderr, "Exec of cmd: %s failed with err: '%s'\n", parts, err.Error())
}
}

Expand Down

0 comments on commit 3761136

Please sign in to comment.