Skip to content

Commit

Permalink
Add timeout to zfs/zpool commands, except zfs send/receive commands
Browse files Browse the repository at this point in the history
Fixes #70
  • Loading branch information
avnish30jn authored and mmlb committed Apr 1, 2022
1 parent 6377fc1 commit 21a1df2
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 6 deletions.
30 changes: 26 additions & 4 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,38 +2,60 @@ package zfs

import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"regexp"
"runtime"
"strconv"
"strings"
"time"

"github.com/google/uuid"
)

const (
cmdtimeoutEnv = "COMMAND_TIMEOUT"
)

type command struct {
Command string
Stdin io.Reader
Stdout io.Writer
timeout *time.Duration
}

func getCommandTimeout() *time.Duration {
value := os.Getenv(cmdtimeoutEnv)
if timeout, err := time.ParseDuration(value); value != "" && err == nil {
return &timeout
}
return nil
}

func (c *command) Run(arg ...string) ([][]string, error) {
cmd := exec.Command(c.Command, arg...)
if c.timeout != nil {
ctx, cancel := context.WithTimeout(context.TODO(), *c.timeout)
defer cancel()
cmd = exec.CommandContext(ctx, c.Command, arg...)
}

var stdout, stderr bytes.Buffer
if c.Stdin != nil {
cmd.Stdin = c.Stdin
}

var stdout bytes.Buffer
if c.Stdout == nil {
cmd.Stdout = &stdout
} else {
cmd.Stdout = c.Stdout
}

if c.Stdin != nil {
cmd.Stdin = c.Stdin
}
var stderr bytes.Buffer
cmd.Stderr = &stderr

id := uuid.New().String()
Expand Down
2 changes: 1 addition & 1 deletion zfs.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ func zfs(arg ...string) error {

// zfs is a helper function to wrap typical calls to zfs.
func zfsOutput(arg ...string) ([][]string, error) {
c := command{Command: "zfs"}
c := command{Command: "zfs", timeout: getCommandTimeout()}
return c.Run(arg...)
}

Expand Down
2 changes: 1 addition & 1 deletion zpool.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func zpool(arg ...string) error {

// zpool is a helper function to wrap typical calls to zpool.
func zpoolOutput(arg ...string) ([][]string, error) {
c := command{Command: "zpool"}
c := command{Command: "zpool", timeout: getCommandTimeout()}
return c.Run(arg...)
}

Expand Down

0 comments on commit 21a1df2

Please sign in to comment.