github.com/cvmfs/docker-graphdriver@v0.0.0-20181206110523-155ec6df0521/repository-manager/lib/exec_commands.go (about) 1 package lib 2 3 import ( 4 "fmt" 5 "io" 6 "io/ioutil" 7 "os/exec" 8 9 log "github.com/sirupsen/logrus" 10 ) 11 12 type execCmd struct { 13 cmd *exec.Cmd 14 err io.ReadCloser 15 out io.ReadCloser 16 } 17 18 func ExecCommand(input ...string) *execCmd { 19 Log().WithFields(log.Fields{"action": "executing"}).Info(input) 20 cmd := exec.Command(input[0], input[1:]...) 21 stdout, errOUT := cmd.StdoutPipe() 22 if errOUT != nil { 23 LogE(errOUT).Warning("Impossible to obtain the STDOUT pipe") 24 return nil 25 } 26 stderr, errERR := cmd.StderrPipe() 27 if errERR != nil { 28 LogE(errERR).Warning("Impossible to obtain the STDERR pipe") 29 return nil 30 } 31 32 return &execCmd{cmd: cmd, err: stderr, out: stdout} 33 } 34 35 func (e *execCmd) Start() error { 36 if e == nil { 37 err := fmt.Errorf("Use of nil execCmd") 38 LogE(err).Error("Call start with nil cmd, maybe error in the constructor") 39 return err 40 } 41 42 err := e.cmd.Start() 43 if err != nil { 44 LogE(err).Error("Error in starting the command") 45 return err 46 } 47 48 slurpOut, errOUT := ioutil.ReadAll(e.out) 49 if errOUT != nil { 50 LogE(errOUT).Warning("Impossible to read the STDOUT") 51 return err 52 } 53 slurpErr, errERR := ioutil.ReadAll(e.err) 54 if errERR != nil { 55 LogE(errERR).Warning("Impossible to read the STDERR") 56 return err 57 } 58 59 err = e.cmd.Wait() 60 if err != nil { 61 LogE(err).Error("Error in executing the command") 62 Log().WithFields(log.Fields{"pipe": "STDOUT"}).Info(string(slurpOut)) 63 Log().WithFields(log.Fields{"pipe": "STDERR"}).Info(string(slurpErr)) 64 return err 65 } 66 return nil 67 } 68 69 func (e *execCmd) Env(key, value string) *execCmd { 70 if e == nil { 71 err := fmt.Errorf("Use of nil execCmd") 72 LogE(err).Error("Set ENV to nil cmd, maybe error in the constructor") 73 return nil 74 } 75 e.cmd.Env = append(e.cmd.Env, fmt.Sprintf("%s=%s", key, value)) 76 return e 77 }