github.com/cloudbase/juju-core@v0.0.0-20140504232958-a7271ac7912f/utils/exec/exec_linux.go (about)

     1  package exec
     2  
     3  import (
     4      "bytes"
     5      "os/exec"
     6      "syscall"
     7  )
     8  
     9  // RunCommands executes the Commands specified in the RunParams using
    10  // '/bin/bash -s', passing the commands through as stdin, and collecting
    11  // stdout and stderr.  If a non-zero return code is returned, this is
    12  // collected as the code for the response and this does not classify as an
    13  // error.
    14  func RunCommands(run RunParams) (*ExecResponse, error) {
    15      ps := exec.Command("/bin/bash", "-s")
    16      if run.Environment != nil {
    17          ps.Env = run.Environment
    18      }
    19      if run.WorkingDir != "" {
    20          ps.Dir = run.WorkingDir
    21      }
    22      ps.Stdin = bytes.NewBufferString(run.Commands)
    23  
    24      stdout := &bytes.Buffer{}
    25      stderr := &bytes.Buffer{}
    26  
    27      ps.Stdout = stdout
    28      ps.Stderr = stderr
    29  
    30      err := ps.Start()
    31      if err == nil {
    32          err = ps.Wait()
    33      }
    34      result := &ExecResponse{
    35          Stdout: stdout.Bytes(),
    36          Stderr: stderr.Bytes(),
    37      }
    38      if ee, ok := err.(*exec.ExitError); ok && err != nil {
    39          status := ee.ProcessState.Sys().(syscall.WaitStatus)
    40          if status.Exited() {
    41              // A non-zero return code isn't considered an error here.
    42              result.Code = status.ExitStatus()
    43              err = nil
    44          }
    45          logger.Infof("run result: %v", ee)
    46      }
    47      return result, err
    48  }