Guest User

Untitled

a guest
Feb 17th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. package services
  2.  
  3. import (
  4. "fmt"
  5. "github.com/go-cmd/cmd"
  6. "github.com/golang/glog"
  7. "time"
  8. )
  9.  
  10. type BashExecutor struct {
  11. verbose bool
  12. }
  13.  
  14. func NewBashExecutor(verbose bool) *BashExecutor {
  15. return &BashExecutor{
  16. verbose: verbose,
  17. }
  18. }
  19.  
  20. func (bs *BashExecutor) ExecuteCommand(commandString string) int {
  21. // Disable output buffering, enable streaming
  22. cmdOptions := cmd.Options{
  23. Buffered: false,
  24. Streaming: true,
  25. }
  26.  
  27. mphCmd := cmd.NewCmdOptions(cmdOptions, "bash", "-c", commandString)
  28.  
  29. if bs.verbose {
  30. glog.Infoln("Executing bash command: " + commandString)
  31. }
  32.  
  33. // Print to STDOUT
  34. if bs.verbose {
  35. go func() {
  36. for line := range mphCmd.Stdout {
  37. fmt.Println(line)
  38. }
  39. }()
  40. } else {
  41. go func() {
  42. for range mphCmd.Stdout {
  43. // do nothing
  44. }
  45. }()
  46. }
  47.  
  48. // Run the command
  49. cmdStatus := <-mphCmd.Start()
  50.  
  51. // Cmd has finished but wait for goroutine to print all lines
  52. for len(mphCmd.Stdout) > 0 {
  53. time.Sleep(10 * time.Millisecond)
  54. }
  55.  
  56. if cmdStatus.Exit != 0 {
  57. glog.Errorf("Exit code: %d\n", cmdStatus.Exit)
  58. glog.Errorf("Executed command: %s\n", commandString)
  59. glog.Errorf("Error: %+v", cmdStatus.Error)
  60. for _, line := range cmdStatus.Stderr {
  61. fmt.Println(line)
  62. }
  63. return cmdStatus.Exit
  64. }
  65.  
  66. glog.Infof("Command took %f seconds to complete", cmdStatus.Runtime)
  67. return cmdStatus.Exit
  68. }
Add Comment
Please, Sign In to add comment