Skip to content

Commit a9c9f02

Browse files
authored
fix: Fix cronjob manual stop not working (#11300)
1 parent 8606427 commit a9c9f02

File tree

1 file changed

+31
-10
lines changed

1 file changed

+31
-10
lines changed

agent/utils/cmd/cmdx.go

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -108,12 +108,16 @@ func (c *CommandHelper) run(name string, arg ...string) (string, error) {
108108
cmd = exec.CommandContext(newContext, name, arg...)
109109
} else {
110110
if c.context == nil {
111+
newContext = context.Background()
111112
cmd = exec.Command(name, arg...)
112113
} else {
113114
newContext = c.context
114115
cmd = exec.CommandContext(c.context, name, arg...)
115116
}
116117
}
118+
cmd.SysProcAttr = &syscall.SysProcAttr{
119+
Setpgid: true,
120+
}
117121

118122
customWriter := &CustomWriter{taskItem: c.taskItem}
119123
var stdout, stderr bytes.Buffer
@@ -145,22 +149,39 @@ func (c *CommandHelper) run(name string, arg ...string) (string, error) {
145149
cmd.Dir = c.workDir
146150
}
147151

148-
err := cmd.Run()
152+
if err := cmd.Start(); err != nil {
153+
return "", fmt.Errorf("cmd.Start() failed with '%s'\n", err)
154+
}
149155
if c.taskItem != nil {
150156
customWriter.Flush()
151157
}
152-
if c.timeout != 0 {
153-
if newContext != nil && errors.Is(newContext.Err(), context.DeadlineExceeded) {
154-
return "", buserr.New("ErrCmdTimeout")
158+
159+
done := make(chan error, 1)
160+
go func() {
161+
done <- cmd.Wait()
162+
}()
163+
select {
164+
case err := <-done:
165+
if err != nil {
166+
return handleErr(stdout, stderr, c.IgnoreExist1, err)
155167
}
156-
}
157-
if err != nil {
158-
if err.Error() == "signal: killed" {
159-
return "", buserr.New("ErrShutDown")
168+
return stdout.String(), nil
169+
case <-newContext.Done():
170+
if cmd.Process != nil && cmd.Process.Pid > 0 {
171+
syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
172+
}
173+
var err error
174+
switch newContext.Err() {
175+
case context.DeadlineExceeded:
176+
err = buserr.New("ErrCmdTimeout")
177+
case context.Canceled:
178+
err = buserr.New("ErrShutDown")
179+
default:
180+
err = newContext.Err()
160181
}
161-
return handleErr(stdout, stderr, c.IgnoreExist1, err)
182+
<-done
183+
return "", err
162184
}
163-
return stdout.String(), nil
164185
}
165186

166187
func WithContext(ctx context.Context) Option {

0 commit comments

Comments
 (0)