Skip to content
Merged
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
41 changes: 31 additions & 10 deletions agent/utils/cmd/cmdx.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@
return c.run("bash", "-c", fmt.Sprintf(command, arg...))
}

func (c *CommandHelper) run(name string, arg ...string) (string, error) {

Check failure on line 95 in agent/utils/cmd/cmdx.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this method to reduce its Cognitive Complexity from 22 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=1Panel-dev_1Panel&issues=AZsLZBAU5WIV6xkm-hxm&open=AZsLZBAU5WIV6xkm-hxm&pullRequest=11300
var cmd *exec.Cmd
var newContext context.Context
var cancel context.CancelFunc
Expand All @@ -108,12 +108,16 @@
cmd = exec.CommandContext(newContext, name, arg...)
} else {
if c.context == nil {
newContext = context.Background()
cmd = exec.Command(name, arg...)
} else {
newContext = c.context
cmd = exec.CommandContext(c.context, name, arg...)
}
}
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
}

customWriter := &CustomWriter{taskItem: c.taskItem}
var stdout, stderr bytes.Buffer
Expand Down Expand Up @@ -145,22 +149,39 @@
cmd.Dir = c.workDir
}

err := cmd.Run()
if err := cmd.Start(); err != nil {
return "", fmt.Errorf("cmd.Start() failed with '%s'\n", err)
}
if c.taskItem != nil {
customWriter.Flush()
}
if c.timeout != 0 {
if newContext != nil && errors.Is(newContext.Err(), context.DeadlineExceeded) {
return "", buserr.New("ErrCmdTimeout")

done := make(chan error, 1)
go func() {
done <- cmd.Wait()
}()
select {
case err := <-done:
if err != nil {
return handleErr(stdout, stderr, c.IgnoreExist1, err)
}
}
if err != nil {
if err.Error() == "signal: killed" {
return "", buserr.New("ErrShutDown")
return stdout.String(), nil
case <-newContext.Done():
if cmd.Process != nil && cmd.Process.Pid > 0 {
syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
}
var err error
switch newContext.Err() {
case context.DeadlineExceeded:
err = buserr.New("ErrCmdTimeout")
case context.Canceled:
err = buserr.New("ErrShutDown")
default:
err = newContext.Err()
}
return handleErr(stdout, stderr, c.IgnoreExist1, err)
<-done
return "", err
}
return stdout.String(), nil
}

func WithContext(ctx context.Context) Option {
Expand Down
Loading