Skip to content

Commit

Permalink
Support timeout for commands
Browse files Browse the repository at this point in the history
Commands can now be stopped after the specified timeout. The default
behaviour of no timeouts is kept the same. Users wanting to opt into
this feature must set a new DefaultRunner with properly set values.

Related to #70.
  • Loading branch information
antonag32 committed Jul 29, 2024
1 parent 9b43ea0 commit 9a21256
Showing 1 changed file with 36 additions and 1 deletion.
37 changes: 36 additions & 1 deletion utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package zfs

import (
"bytes"
"context"
"errors"
"fmt"
"io"
Expand All @@ -10,18 +11,52 @@ import (
"runtime"
"strconv"
"strings"
"sync/atomic"
"syscall"
"time"

"github.com/google/uuid"
)

type Runner struct {
Timeout time.Duration
Grace time.Duration
}

var defaultRunner atomic.Value

func init() {
defaultRunner.Store(&Runner{})
}

func Default() *Runner {
return defaultRunner.Load().(*Runner)
}

func SetDefault(runner *Runner) {
defaultRunner.Store(runner)
}

type command struct {
Command string
Stdin io.Reader
Stdout io.Writer
}

func (c *command) Run(arg ...string) ([][]string, error) {
cmd := exec.Command(c.Command, arg...)
var cmd *exec.Cmd
if Default().Timeout == 0 {
cmd = exec.Command(c.Command, arg...)
} else {
ctx, cancel := context.WithTimeout(context.Background(), Default().Timeout)
defer cancel()

cmd = exec.CommandContext(ctx, c.Command, arg...)
cmd.Cancel = func() error {
return cmd.Process.Signal(syscall.SIGTERM)
}
cmd.WaitDelay = Default().Grace
}

var stdout, stderr bytes.Buffer

Expand Down

0 comments on commit 9a21256

Please sign in to comment.