Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support timeout for commands #93

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 41 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,57 @@ import (
"runtime"
"strconv"
"strings"
"sync/atomic"
"syscall"
"time"

"github.com/google/uuid"
)

// Runner specifies the parameters used when executing ZFS commands.
type Runner struct {
// Timeout specifies how long to wait before sending a SIGTERM signal to the running process.
Timeout time.Duration

// Grace specifies the time waited after signaling the running process with SIGTERM before it is forcefully
// killed with SIGKILL.
Grace time.Duration
}

var defaultRunner atomic.Value

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

func Default() *Runner {
return defaultRunner.Load().(*Runner) //nolint: forcetypeassert // Impossible for it to be anything else.
}

func SetRunner(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