mirror of
https://github.com/ceph/ceph-csi.git
synced 2025-06-13 02:33:34 +00:00
util: add helper ExecCommandWithTimeout function
added ExecCommandWithTimeout helper function to execute the commands with the timeout option, if the command does not return any response with in the timeout time the process will be terminated and error will be returned back to the user. Signed-off-by: Madhu Rajanna <madhupr007@gmail.com>
This commit is contained in:
committed by
mergify[bot]
parent
2b7fb1bbb1
commit
95e9595c1f
@ -22,6 +22,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"time"
|
||||
|
||||
"github.com/ceph/ceph-csi/internal/util/log"
|
||||
|
||||
@ -65,6 +66,59 @@ func ExecCommand(ctx context.Context, program string, args ...string) (string, s
|
||||
return stdout, stderr, nil
|
||||
}
|
||||
|
||||
// ExecCommandWithTimeout executes passed in program with args, timeout and
|
||||
// returns separate stdout and stderr streams. If the command is not executed
|
||||
// within given timeout, the process will be killed. In case ctx is not set to
|
||||
// context.TODO(), the command will be logged after it was executed.
|
||||
func ExecCommandWithTimeout(
|
||||
ctx context.Context,
|
||||
timeout time.Duration,
|
||||
program string,
|
||||
args ...string) (
|
||||
string,
|
||||
string,
|
||||
error) {
|
||||
var (
|
||||
sanitizedArgs = StripSecretInArgs(args)
|
||||
stdoutBuf bytes.Buffer
|
||||
stderrBuf bytes.Buffer
|
||||
)
|
||||
|
||||
cctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
cmd := exec.CommandContext(cctx, program, args...) // #nosec:G204, commands executing not vulnerable.
|
||||
cmd.Stdout = &stdoutBuf
|
||||
cmd.Stderr = &stderrBuf
|
||||
|
||||
err := cmd.Run()
|
||||
stdout := stdoutBuf.String()
|
||||
stderr := stderrBuf.String()
|
||||
if err != nil {
|
||||
// if its a timeout log return context deadline exceeded error message
|
||||
if errors.Is(cctx.Err(), context.DeadlineExceeded) {
|
||||
err = fmt.Errorf("timeout: %w", cctx.Err())
|
||||
}
|
||||
err = fmt.Errorf("an error (%w) and stderror (%s) occurred while running %s args: %v",
|
||||
err,
|
||||
stderr,
|
||||
program,
|
||||
sanitizedArgs)
|
||||
|
||||
if ctx != context.TODO() {
|
||||
log.ErrorLog(ctx, "%s", err)
|
||||
}
|
||||
|
||||
return stdout, stderr, err
|
||||
}
|
||||
|
||||
if ctx != context.TODO() {
|
||||
log.UsefulLog(ctx, "command succeeded: %s %v", program, sanitizedArgs)
|
||||
}
|
||||
|
||||
return stdout, stderr, nil
|
||||
}
|
||||
|
||||
// GetPoolID fetches the ID of the pool that matches the passed in poolName
|
||||
// parameter.
|
||||
func GetPoolID(monitors string, cr *Credentials, poolName string) (int64, error) {
|
||||
|
Reference in New Issue
Block a user