executor.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package drivers
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "os/exec"
  20. "yunion.io/x/log"
  21. "yunion.io/x/pkg/errors"
  22. "yunion.io/x/onecloud/pkg/util/ssh"
  23. )
  24. type Executor struct{}
  25. func (e *Executor) Run(cmds ...string) ([]string, error) {
  26. return e.run(true, cmds, nil)
  27. }
  28. func (e *Executor) RunWithInput(input io.Reader, cmds ...string) ([]string, error) {
  29. return e.run(true, cmds, input)
  30. }
  31. func (e *Executor) run(parseOutput bool, cmds []string, input io.Reader) ([]string, error) {
  32. ret := []string{}
  33. for _, cmd := range cmds {
  34. log.Debugf("Run command: %s", cmd)
  35. proc := exec.Command("sh", "-c", cmd)
  36. var stdOut bytes.Buffer
  37. var stdErr bytes.Buffer
  38. proc.Stdout = &stdOut
  39. proc.Stderr = &stdErr
  40. proc.Stdin = input
  41. if err := proc.Run(); err != nil {
  42. var outputErr error
  43. errMsg := stdErr.String()
  44. if len(stdOut.String()) != 0 {
  45. errMsg = fmt.Sprintf("%s %s", errMsg, stdOut.String())
  46. }
  47. outputErr = errors.Error(errMsg)
  48. err = errors.Wrapf(outputErr, "%q error: %v, cmd error", cmd, err)
  49. return nil, err
  50. }
  51. if parseOutput {
  52. ret = append(ret, ssh.ParseOutput(stdOut.Bytes())...)
  53. } else {
  54. ret = append(ret, stdOut.String())
  55. }
  56. }
  57. return ret, nil
  58. }
  59. func NewExecutor() *Executor {
  60. return new(Executor)
  61. }