execute.go 4.7 KB

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