execute.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. // Author: NiuJiuRu
  2. // Email: niujiuru@qq.com
  3. package shell
  4. import (
  5. "bytes"
  6. "context"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "os/exec"
  11. "syscall"
  12. "time"
  13. "github.com/mattn/go-shellwords"
  14. )
  15. const (
  16. defaultTimeout = 5 * time.Second
  17. gracePeriod = 2 * time.Second
  18. forceKillWait = 2 * time.Second
  19. exitTimeoutCode = 124
  20. maxOutputSize = 1 << 20 // 最大 1 MB, 限制输出大小
  21. checkProcessDelay = 50 * time.Millisecond
  22. )
  23. var (
  24. ErrInvalidCommand = errors.New("invalid command")
  25. ErrExecutorLostControl = errors.New("executor lost control of process")
  26. )
  27. type ExecuteParams struct {
  28. Cmd string `json:"cmd"` // 命令
  29. Timeout int `json:"timeout,omitempty"` // 超时(秒)
  30. }
  31. type ExecuteResult struct {
  32. Stdout string `json:"stdout"` ///////// 标准输出
  33. Stderr string `json:"stderr"` ///////// 错误输出
  34. ExitCode int `json:"exit_code"` ///////// 退出状态码: 0表示成功, 非0表示失败
  35. }
  36. type limitedBuffer struct {
  37. buf *bytes.Buffer
  38. limit int
  39. }
  40. func (l *limitedBuffer) Write(p []byte) (int, error) {
  41. remain := l.limit - l.buf.Len()
  42. if remain <= 0 {
  43. return len(p), nil
  44. }
  45. if len(p) > remain {
  46. p = p[:remain]
  47. }
  48. return l.buf.Write(p)
  49. }
  50. type processGroup struct {
  51. cmd *exec.Cmd
  52. pgid int
  53. }
  54. // 进程组是否存在
  55. func (pg *processGroup) isProcessGroupAlive() bool {
  56. err := syscall.Kill(-pg.pgid, syscall.Signal(0))
  57. if err == nil {
  58. return true
  59. }
  60. if errno, ok := err.(syscall.Errno); ok && errno == syscall.ESRCH {
  61. return false
  62. }
  63. return true
  64. }
  65. // 等待进程组终止
  66. func (pg *processGroup) waitForTermination(timeout time.Duration) bool {
  67. deadline := time.Now().Add(timeout)
  68. for time.Now().Before(deadline) {
  69. if !pg.isProcessGroupAlive() {
  70. return true
  71. }
  72. time.Sleep(checkProcessDelay)
  73. }
  74. return !pg.isProcessGroupAlive()
  75. }
  76. // 终止整个进程组
  77. func (pg *processGroup) terminate() error {
  78. if pg.cmd.Process == nil || pg.pgid <= 0 || !pg.isProcessGroupAlive() {
  79. return nil
  80. }
  81. // 第一阶段: 尝试优雅终止, SIGTERM
  82. if err := syscall.Kill(-pg.pgid, syscall.SIGTERM); err != nil { // 如果发送信号失败,可能进程已经不存在
  83. if errno, ok := err.(syscall.Errno); ok && errno == syscall.ESRCH {
  84. return nil
  85. }
  86. }
  87. if pg.waitForTermination(gracePeriod) {
  88. return nil
  89. }
  90. // 第二阶段: 最后强制终止, SIGKILL
  91. if err := syscall.Kill(-pg.pgid, syscall.SIGKILL); err != nil { // 如果发送信号失败,可能进程已经不存在
  92. if errno, ok := err.(syscall.Errno); ok && errno == syscall.ESRCH {
  93. return nil
  94. }
  95. return fmt.Errorf("failed to send SIGKILL to process group: %w", err)
  96. }
  97. if pg.waitForTermination(forceKillWait) {
  98. return nil
  99. }
  100. return fmt.Errorf("%w: process group %d still alive after force kill",
  101. ErrExecutorLostControl, pg.pgid)
  102. }
  103. func Execute(p ExecuteParams) (*ExecuteResult, error) {
  104. swp := shellwords.NewParser()
  105. swp.ParseEnv = true // 展开 "环境变量"
  106. swp.ParseBacktick = true // 展开 `...`命令
  107. argv, err := swp.Parse(p.Cmd)
  108. if err != nil || len(argv) == 0 {
  109. return nil, ErrInvalidCommand
  110. }
  111. timeout := time.Duration(p.Timeout) * time.Second
  112. if timeout <= 0 {
  113. timeout = defaultTimeout
  114. }
  115. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  116. defer cancel()
  117. cmd := exec.Command(argv[0], argv[1:]...)
  118. cmd.SysProcAttr = &syscall.SysProcAttr{ // 新的进程组
  119. Setpgid: true,
  120. Pdeathsig: syscall.SIGKILL,
  121. }
  122. var stdout, stderr bytes.Buffer
  123. cmd.Stdout = io.Writer(&limitedBuffer{buf: &stdout, limit: maxOutputSize})
  124. cmd.Stderr = io.Writer(&limitedBuffer{buf: &stderr, limit: maxOutputSize})
  125. if err := cmd.Start(); err != nil {
  126. return nil, err
  127. }
  128. processInfo := &processGroup{
  129. cmd: cmd,
  130. pgid: cmd.Process.Pid, // 进程组ID就是主进程的PID
  131. }
  132. done := make(chan error, 1)
  133. go func() {
  134. done <- cmd.Wait()
  135. }()
  136. exitCode := 0
  137. var finalErr error
  138. select {
  139. case err := <-done: // 命令已结束, 输出结果
  140. if err != nil {
  141. if ee, ok := err.(*exec.ExitError); ok {
  142. exitCode = ee.ExitCode()
  143. } else {
  144. return nil, err
  145. }
  146. }
  147. case <-ctx.Done(): /// 超时, kill整个进程组
  148. exitCode = exitTimeoutCode
  149. if err := processInfo.terminate(); err != nil {
  150. finalErr = err
  151. break
  152. }
  153. select {
  154. case <-done:
  155. case <-time.After(forceKillWait):
  156. finalErr = ErrExecutorLostControl
  157. }
  158. }
  159. return &ExecuteResult{
  160. Stdout: stdout.String(),
  161. Stderr: stderr.String(),
  162. ExitCode: exitCode,
  163. }, finalErr
  164. }