driver.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 driver
  15. import (
  16. "fmt"
  17. "io"
  18. "io/ioutil"
  19. "yunion.io/x/onecloud/pkg/util/procutils"
  20. )
  21. type IFsutilExecDriver interface {
  22. Run(name string, args ...string) error
  23. Exec(name string, args ...string) ([]byte, error)
  24. ExecInputWait(name string, args []string, input []string) (int, string, string, error)
  25. }
  26. type SProcDriver struct {
  27. }
  28. func NewProcDriver() IFsutilExecDriver {
  29. return new(SProcDriver)
  30. }
  31. func (*SProcDriver) Exec(name string, args ...string) ([]byte, error) {
  32. return procutils.NewCommand(name, args...).Output()
  33. }
  34. func (*SProcDriver) Run(name string, args ...string) error {
  35. return procutils.NewCommand(name, args...).Run()
  36. }
  37. func (*SProcDriver) ExecInputWait(name string, args []string, input []string) (int, string, string, error) {
  38. proc := procutils.NewCommand(name, args...)
  39. stdin, err := proc.StdinPipe()
  40. if err != nil {
  41. return -1, "", "", err
  42. }
  43. defer stdin.Close()
  44. outb, err := proc.StdoutPipe()
  45. if err != nil {
  46. return -1, "", "", err
  47. }
  48. defer outb.Close()
  49. errb, err := proc.StderrPipe()
  50. if err != nil {
  51. return -1, "", "", err
  52. }
  53. defer errb.Close()
  54. if err := proc.Start(); err != nil {
  55. return -1, "", "", err
  56. }
  57. for _, s := range input {
  58. io.WriteString(stdin, fmt.Sprintf("%s\n", s))
  59. }
  60. stdoutPut, err := ioutil.ReadAll(outb)
  61. if err != nil {
  62. return -1, "", "", err
  63. }
  64. stderrOutPut, err := ioutil.ReadAll(errb)
  65. if err != nil {
  66. return -1, "", "", err
  67. }
  68. if err = proc.Wait(); err != nil {
  69. if status, succ := proc.GetExitStatus(err); succ {
  70. return status, string(stdoutPut), string(stderrOutPut), err
  71. } else {
  72. return 0, string(stdoutPut), string(stderrOutPut), err
  73. }
  74. }
  75. return 0, string(stdoutPut), string(stderrOutPut), nil
  76. }