[agent-go] update pipline command executor

This commit is contained in:
zeaslity
2023-04-13 15:19:52 +08:00
parent bb724603cc
commit c79eaab3a3
2 changed files with 14 additions and 35 deletions

View File

@@ -6,6 +6,7 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"os/exec" "os/exec"
"strings"
) )
type ExecutionMessage struct { type ExecutionMessage struct {
@@ -54,42 +55,20 @@ func Execute(em *ExecutionMessage) ([]string, error) {
func PipeLineCommandExecutor(pipeLineCommand [][]string) ([]string, error) { func PipeLineCommandExecutor(pipeLineCommand [][]string) ([]string, error) {
var cmds []*exec.Cmd var output []byte
var err error
// 创建每个命令对象,并将前一个命令的标准输出连接到当前命令的标准输入 for i, command := range pipeLineCommand {
for i, partOfCommand := range pipeLineCommand { cmd := exec.Command(command[0], command[1:]...)
cmd := exec.Command(partOfCommand[0], partOfCommand[1:]...) cmd.Stdin = bytes.NewReader(output)
if i > 0 { output, err = cmd.Output()
prevCmd := cmds[i-1] if err != nil {
out, err := prevCmd.StdoutPipe() return strings.Split(string(output), "\n"), err
if err != nil { }
log.ErrorF("Pipeline command error happened! Command is => %v, Error is %v", partOfCommand, err) if i == len(pipeLineCommand)-1 {
return nil, err return strings.Split(string(output), "\n"), nil
}
cmd.Stdin = out
} }
cmds = append(cmds, cmd)
} }
return []string{}, nil
// 执行最后一个命令,并获取其输出
lastCmd := cmds[len(cmds)-1]
var out bytes.Buffer
lastCmd.Stdout = &out
lastCmd.Stderr = &out
err := lastCmd.Run()
scanner := bufio.NewScanner(&out)
var result []string
for scanner.Scan() {
result = append(result, scanner.Text())
}
if err != nil {
return nil, err
}
return result, nil
} }
func MultiLineCommandExecutor(multiLineCommandExecutor [][]string) ([]string, error) { func MultiLineCommandExecutor(multiLineCommandExecutor [][]string) ([]string, error) {

View File

@@ -2,7 +2,7 @@
"uuid": "2023-03-27 14:38:49", "uuid": "2023-03-27 14:38:49",
"init_time": "2023-03-27T14:38:49.8162801+08:00", "init_time": "2023-03-27T14:38:49.8162801+08:00",
"type": "EXECUTOR", "type": "EXECUTOR",
"content": "{\n \"needResultReplay\": true,\n \"durationTask,default:false\": false,\n \"type\": \"pipeline\",\n \"singleLineCommand\": null,\n \"multiLineCommand\": null,\n \"pipeLineCommand\": [[\"ls\",\"-la\"],[\"grep\",\"-c\", \"dev\"]],\n \"resultKey\": \"output\"\n}\n", "content": "{\n \"needResultReplay\": true,\n \"durationTask,default:false\": false,\n \"type\": \"pipeline\",\n \"singleLineCommand\": null,\n \"multiLineCommand\": null,\n \"pipeLineCommand\": [[\"ls\",\"-la\"],[\"grep\", \"dev\"]],\n \"resultKey\": \"output\"\n}\n",
"result": "", "result": "",
"ac_time": "0001-01-01T00:00:00Z" "ac_time": "0001-01-01T00:00:00Z"
} }