2022-10-09 23:35:24 +08:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
import (
|
2022-11-08 15:42:31 +08:00
|
|
|
"bytes"
|
2023-04-12 14:16:29 +08:00
|
|
|
"context"
|
2023-02-14 14:19:26 +08:00
|
|
|
"fmt"
|
2023-04-12 14:16:29 +08:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/buserr"
|
|
|
|
"github.com/1Panel-dev/1Panel/backend/constant"
|
2022-10-09 23:35:24 +08:00
|
|
|
"os/exec"
|
2023-04-12 14:16:29 +08:00
|
|
|
"time"
|
2022-10-09 23:35:24 +08:00
|
|
|
)
|
|
|
|
|
2022-11-08 15:42:31 +08:00
|
|
|
func Exec(cmdStr string) (string, error) {
|
2023-04-12 14:16:29 +08:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
|
|
|
defer cancel()
|
2022-11-08 15:42:31 +08:00
|
|
|
cmd := exec.Command("bash", "-c", cmdStr)
|
|
|
|
var stdout, stderr bytes.Buffer
|
|
|
|
cmd.Stdout = &stdout
|
|
|
|
cmd.Stderr = &stderr
|
|
|
|
err := cmd.Run()
|
2023-04-12 14:16:29 +08:00
|
|
|
if ctx.Err() == context.DeadlineExceeded {
|
|
|
|
return "", buserr.New(constant.ErrCmdTimeout)
|
|
|
|
}
|
2022-10-09 23:35:24 +08:00
|
|
|
if err != nil {
|
2023-03-13 10:04:53 +08:00
|
|
|
errMsg := ""
|
|
|
|
if len(stderr.String()) != 0 {
|
|
|
|
errMsg = fmt.Sprintf("stderr: %s", stderr.String())
|
|
|
|
}
|
|
|
|
if len(stdout.String()) != 0 {
|
|
|
|
if len(errMsg) != 0 {
|
|
|
|
errMsg = fmt.Sprintf("%s; stdout: %s", errMsg, stdout.String())
|
|
|
|
} else {
|
|
|
|
errMsg = fmt.Sprintf("stdout: %s", stdout.String())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return errMsg, err
|
2022-10-09 23:35:24 +08:00
|
|
|
}
|
2022-11-18 18:02:14 +08:00
|
|
|
return stdout.String(), nil
|
2022-10-09 23:35:24 +08:00
|
|
|
}
|
2023-02-14 14:19:26 +08:00
|
|
|
|
|
|
|
func Execf(cmdStr string, a ...interface{}) (string, error) {
|
|
|
|
cmd := exec.Command("bash", "-c", fmt.Sprintf(cmdStr, a...))
|
|
|
|
var stdout, stderr bytes.Buffer
|
|
|
|
cmd.Stdout = &stdout
|
|
|
|
cmd.Stderr = &stderr
|
|
|
|
err := cmd.Run()
|
|
|
|
if err != nil {
|
2023-03-13 10:04:53 +08:00
|
|
|
errMsg := ""
|
|
|
|
if len(stderr.String()) != 0 {
|
|
|
|
errMsg = fmt.Sprintf("stderr: %s", stderr.String())
|
|
|
|
}
|
|
|
|
if len(stdout.String()) != 0 {
|
|
|
|
if len(errMsg) != 0 {
|
|
|
|
errMsg = fmt.Sprintf("%s; stdout: %s", errMsg, stdout.String())
|
|
|
|
} else {
|
|
|
|
errMsg = fmt.Sprintf("stdout: %s", stdout.String())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return errMsg, err
|
2023-02-14 14:19:26 +08:00
|
|
|
}
|
|
|
|
return stdout.String(), nil
|
|
|
|
}
|