github.com/spotify/syslog-redirector-golang@v0.0.0-20140320174030-4859f03d829a/src/pkg/os/exec/exec.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package exec runs external commands. It wraps os.StartProcess to make it
     6  // easier to remap stdin and stdout, connect I/O with pipes, and do other
     7  // adjustments.
     8  package exec
     9  
    10  import (
    11  	"bytes"
    12  	"errors"
    13  	"io"
    14  	"os"
    15  	"strconv"
    16  	"sync"
    17  	"syscall"
    18  )
    19  
    20  // Error records the name of a binary that failed to be executed
    21  // and the reason it failed.
    22  type Error struct {
    23  	Name string
    24  	Err  error
    25  }
    26  
    27  func (e *Error) Error() string {
    28  	return "exec: " + strconv.Quote(e.Name) + ": " + e.Err.Error()
    29  }
    30  
    31  // Cmd represents an external command being prepared or run.
    32  type Cmd struct {
    33  	// Path is the path of the command to run.
    34  	//
    35  	// This is the only field that must be set to a non-zero
    36  	// value.
    37  	Path string
    38  
    39  	// Args holds command line arguments, including the command as Args[0].
    40  	// If the Args field is empty or nil, Run uses {Path}.
    41  	//
    42  	// In typical use, both Path and Args are set by calling Command.
    43  	Args []string
    44  
    45  	// Env specifies the environment of the process.
    46  	// If Env is nil, Run uses the current process's environment.
    47  	Env []string
    48  
    49  	// Dir specifies the working directory of the command.
    50  	// If Dir is the empty string, Run runs the command in the
    51  	// calling process's current directory.
    52  	Dir string
    53  
    54  	// Stdin specifies the process's standard input. If Stdin is
    55  	// nil, the process reads from the null device (os.DevNull).
    56  	Stdin io.Reader
    57  
    58  	// Stdout and Stderr specify the process's standard output and error.
    59  	//
    60  	// If either is nil, Run connects the corresponding file descriptor
    61  	// to the null device (os.DevNull).
    62  	//
    63  	// If Stdout and Stderr are the same writer, at most one
    64  	// goroutine at a time will call Write.
    65  	Stdout io.Writer
    66  	Stderr io.Writer
    67  
    68  	// ExtraFiles specifies additional open files to be inherited by the
    69  	// new process. It does not include standard input, standard output, or
    70  	// standard error. If non-nil, entry i becomes file descriptor 3+i.
    71  	//
    72  	// BUG: on OS X 10.6, child processes may sometimes inherit unwanted fds.
    73  	// http://golang.org/issue/2603
    74  	ExtraFiles []*os.File
    75  
    76  	// SysProcAttr holds optional, operating system-specific attributes.
    77  	// Run passes it to os.StartProcess as the os.ProcAttr's Sys field.
    78  	SysProcAttr *syscall.SysProcAttr
    79  
    80  	// Process is the underlying process, once started.
    81  	Process *os.Process
    82  
    83  	// ProcessState contains information about an exited process,
    84  	// available after a call to Wait or Run.
    85  	ProcessState *os.ProcessState
    86  
    87  	err             error // last error (from LookPath, stdin, stdout, stderr)
    88  	finished        bool  // when Wait was called
    89  	childFiles      []*os.File
    90  	closeAfterStart []io.Closer
    91  	closeAfterWait  []io.Closer
    92  	goroutine       []func() error
    93  	errch           chan error // one send per goroutine
    94  }
    95  
    96  // Command returns the Cmd struct to execute the named program with
    97  // the given arguments.
    98  //
    99  // It sets Path and Args in the returned structure and zeroes the
   100  // other fields.
   101  //
   102  // If name contains no path separators, Command uses LookPath to
   103  // resolve the path to a complete name if possible. Otherwise it uses
   104  // name directly.
   105  //
   106  // The returned Cmd's Args field is constructed from the command name
   107  // followed by the elements of arg, so arg should not include the
   108  // command name itself. For example, Command("echo", "hello")
   109  func Command(name string, arg ...string) *Cmd {
   110  	aname, err := LookPath(name)
   111  	if err != nil {
   112  		aname = name
   113  	}
   114  	return &Cmd{
   115  		Path: aname,
   116  		Args: append([]string{name}, arg...),
   117  		err:  err,
   118  	}
   119  }
   120  
   121  // interfaceEqual protects against panics from doing equality tests on
   122  // two interfaces with non-comparable underlying types
   123  func interfaceEqual(a, b interface{}) bool {
   124  	defer func() {
   125  		recover()
   126  	}()
   127  	return a == b
   128  }
   129  
   130  func (c *Cmd) envv() []string {
   131  	if c.Env != nil {
   132  		return c.Env
   133  	}
   134  	return os.Environ()
   135  }
   136  
   137  func (c *Cmd) argv() []string {
   138  	if len(c.Args) > 0 {
   139  		return c.Args
   140  	}
   141  	return []string{c.Path}
   142  }
   143  
   144  func (c *Cmd) stdin() (f *os.File, err error) {
   145  	if c.Stdin == nil {
   146  		f, err = os.Open(os.DevNull)
   147  		if err != nil {
   148  			return
   149  		}
   150  		c.closeAfterStart = append(c.closeAfterStart, f)
   151  		return
   152  	}
   153  
   154  	if f, ok := c.Stdin.(*os.File); ok {
   155  		return f, nil
   156  	}
   157  
   158  	pr, pw, err := os.Pipe()
   159  	if err != nil {
   160  		return
   161  	}
   162  
   163  	c.closeAfterStart = append(c.closeAfterStart, pr)
   164  	c.closeAfterWait = append(c.closeAfterWait, pw)
   165  	c.goroutine = append(c.goroutine, func() error {
   166  		_, err := io.Copy(pw, c.Stdin)
   167  		if err1 := pw.Close(); err == nil {
   168  			err = err1
   169  		}
   170  		return err
   171  	})
   172  	return pr, nil
   173  }
   174  
   175  func (c *Cmd) stdout() (f *os.File, err error) {
   176  	return c.writerDescriptor(c.Stdout)
   177  }
   178  
   179  func (c *Cmd) stderr() (f *os.File, err error) {
   180  	if c.Stderr != nil && interfaceEqual(c.Stderr, c.Stdout) {
   181  		return c.childFiles[1], nil
   182  	}
   183  	return c.writerDescriptor(c.Stderr)
   184  }
   185  
   186  func (c *Cmd) writerDescriptor(w io.Writer) (f *os.File, err error) {
   187  	if w == nil {
   188  		f, err = os.OpenFile(os.DevNull, os.O_WRONLY, 0)
   189  		if err != nil {
   190  			return
   191  		}
   192  		c.closeAfterStart = append(c.closeAfterStart, f)
   193  		return
   194  	}
   195  
   196  	if f, ok := w.(*os.File); ok {
   197  		return f, nil
   198  	}
   199  
   200  	pr, pw, err := os.Pipe()
   201  	if err != nil {
   202  		return
   203  	}
   204  
   205  	c.closeAfterStart = append(c.closeAfterStart, pw)
   206  	c.closeAfterWait = append(c.closeAfterWait, pr)
   207  	c.goroutine = append(c.goroutine, func() error {
   208  		_, err := io.Copy(w, pr)
   209  		return err
   210  	})
   211  	return pw, nil
   212  }
   213  
   214  func (c *Cmd) closeDescriptors(closers []io.Closer) {
   215  	for _, fd := range closers {
   216  		fd.Close()
   217  	}
   218  }
   219  
   220  // Run starts the specified command and waits for it to complete.
   221  //
   222  // The returned error is nil if the command runs, has no problems
   223  // copying stdin, stdout, and stderr, and exits with a zero exit
   224  // status.
   225  //
   226  // If the command fails to run or doesn't complete successfully, the
   227  // error is of type *ExitError. Other error types may be
   228  // returned for I/O problems.
   229  func (c *Cmd) Run() error {
   230  	if err := c.Start(); err != nil {
   231  		return err
   232  	}
   233  	return c.Wait()
   234  }
   235  
   236  // Start starts the specified command but does not wait for it to complete.
   237  func (c *Cmd) Start() error {
   238  	if c.err != nil {
   239  		c.closeDescriptors(c.closeAfterStart)
   240  		c.closeDescriptors(c.closeAfterWait)
   241  		return c.err
   242  	}
   243  	if c.Process != nil {
   244  		return errors.New("exec: already started")
   245  	}
   246  
   247  	type F func(*Cmd) (*os.File, error)
   248  	for _, setupFd := range []F{(*Cmd).stdin, (*Cmd).stdout, (*Cmd).stderr} {
   249  		fd, err := setupFd(c)
   250  		if err != nil {
   251  			c.closeDescriptors(c.closeAfterStart)
   252  			c.closeDescriptors(c.closeAfterWait)
   253  			return err
   254  		}
   255  		c.childFiles = append(c.childFiles, fd)
   256  	}
   257  	c.childFiles = append(c.childFiles, c.ExtraFiles...)
   258  
   259  	var err error
   260  	c.Process, err = os.StartProcess(c.Path, c.argv(), &os.ProcAttr{
   261  		Dir:   c.Dir,
   262  		Files: c.childFiles,
   263  		Env:   c.envv(),
   264  		Sys:   c.SysProcAttr,
   265  	})
   266  	if err != nil {
   267  		c.closeDescriptors(c.closeAfterStart)
   268  		c.closeDescriptors(c.closeAfterWait)
   269  		return err
   270  	}
   271  
   272  	c.closeDescriptors(c.closeAfterStart)
   273  
   274  	c.errch = make(chan error, len(c.goroutine))
   275  	for _, fn := range c.goroutine {
   276  		go func(fn func() error) {
   277  			c.errch <- fn()
   278  		}(fn)
   279  	}
   280  
   281  	return nil
   282  }
   283  
   284  // An ExitError reports an unsuccessful exit by a command.
   285  type ExitError struct {
   286  	*os.ProcessState
   287  }
   288  
   289  func (e *ExitError) Error() string {
   290  	return e.ProcessState.String()
   291  }
   292  
   293  // Wait waits for the command to exit.
   294  // It must have been started by Start.
   295  //
   296  // The returned error is nil if the command runs, has no problems
   297  // copying stdin, stdout, and stderr, and exits with a zero exit
   298  // status.
   299  //
   300  // If the command fails to run or doesn't complete successfully, the
   301  // error is of type *ExitError. Other error types may be
   302  // returned for I/O problems.
   303  func (c *Cmd) Wait() error {
   304  	if c.Process == nil {
   305  		return errors.New("exec: not started")
   306  	}
   307  	if c.finished {
   308  		return errors.New("exec: Wait was already called")
   309  	}
   310  	c.finished = true
   311  	state, err := c.Process.Wait()
   312  	c.ProcessState = state
   313  
   314  	var copyError error
   315  	for _ = range c.goroutine {
   316  		if err := <-c.errch; err != nil && copyError == nil {
   317  			copyError = err
   318  		}
   319  	}
   320  
   321  	c.closeDescriptors(c.closeAfterWait)
   322  
   323  	if err != nil {
   324  		return err
   325  	} else if !state.Success() {
   326  		return &ExitError{state}
   327  	}
   328  
   329  	return copyError
   330  }
   331  
   332  // Output runs the command and returns its standard output.
   333  func (c *Cmd) Output() ([]byte, error) {
   334  	if c.Stdout != nil {
   335  		return nil, errors.New("exec: Stdout already set")
   336  	}
   337  	var b bytes.Buffer
   338  	c.Stdout = &b
   339  	err := c.Run()
   340  	return b.Bytes(), err
   341  }
   342  
   343  // CombinedOutput runs the command and returns its combined standard
   344  // output and standard error.
   345  func (c *Cmd) CombinedOutput() ([]byte, error) {
   346  	if c.Stdout != nil {
   347  		return nil, errors.New("exec: Stdout already set")
   348  	}
   349  	if c.Stderr != nil {
   350  		return nil, errors.New("exec: Stderr already set")
   351  	}
   352  	var b bytes.Buffer
   353  	c.Stdout = &b
   354  	c.Stderr = &b
   355  	err := c.Run()
   356  	return b.Bytes(), err
   357  }
   358  
   359  // StdinPipe returns a pipe that will be connected to the command's
   360  // standard input when the command starts.
   361  // The pipe will be closed automatically after Wait sees the command exit.
   362  // A caller need only call Close to force the pipe to close sooner.
   363  // For example, if the command being run will not exit until standard input
   364  // is closed, the caller must close the pipe.
   365  func (c *Cmd) StdinPipe() (io.WriteCloser, error) {
   366  	if c.Stdin != nil {
   367  		return nil, errors.New("exec: Stdin already set")
   368  	}
   369  	if c.Process != nil {
   370  		return nil, errors.New("exec: StdinPipe after process started")
   371  	}
   372  	pr, pw, err := os.Pipe()
   373  	if err != nil {
   374  		return nil, err
   375  	}
   376  	c.Stdin = pr
   377  	c.closeAfterStart = append(c.closeAfterStart, pr)
   378  	wc := &closeOnce{File: pw}
   379  	c.closeAfterWait = append(c.closeAfterWait, wc)
   380  	return wc, nil
   381  }
   382  
   383  type closeOnce struct {
   384  	*os.File
   385  
   386  	close    sync.Once
   387  	closeErr error
   388  }
   389  
   390  func (c *closeOnce) Close() error {
   391  	c.close.Do(func() {
   392  		c.closeErr = c.File.Close()
   393  	})
   394  	return c.closeErr
   395  }
   396  
   397  // StdoutPipe returns a pipe that will be connected to the command's
   398  // standard output when the command starts.
   399  //
   400  // Wait will close the pipe after seeing the command exit, so most callers
   401  // need not close the pipe themselves; however, an implication is that
   402  // it is incorrect to call Wait before all reads from the pipe have completed.
   403  // For the same reason, it is incorrect to call Run when using StdoutPipe.
   404  // See the example for idiomatic usage.
   405  func (c *Cmd) StdoutPipe() (io.ReadCloser, error) {
   406  	if c.Stdout != nil {
   407  		return nil, errors.New("exec: Stdout already set")
   408  	}
   409  	if c.Process != nil {
   410  		return nil, errors.New("exec: StdoutPipe after process started")
   411  	}
   412  	pr, pw, err := os.Pipe()
   413  	if err != nil {
   414  		return nil, err
   415  	}
   416  	c.Stdout = pw
   417  	c.closeAfterStart = append(c.closeAfterStart, pw)
   418  	c.closeAfterWait = append(c.closeAfterWait, pr)
   419  	return pr, nil
   420  }
   421  
   422  // StderrPipe returns a pipe that will be connected to the command's
   423  // standard error when the command starts.
   424  //
   425  // Wait will close the pipe after seeing the command exit, so most callers
   426  // need not close the pipe themselves; however, an implication is that
   427  // it is incorrect to call Wait before all reads from the pipe have completed.
   428  // For the same reason, it is incorrect to use Run when using StderrPipe.
   429  // See the StdoutPipe example for idiomatic usage.
   430  func (c *Cmd) StderrPipe() (io.ReadCloser, error) {
   431  	if c.Stderr != nil {
   432  		return nil, errors.New("exec: Stderr already set")
   433  	}
   434  	if c.Process != nil {
   435  		return nil, errors.New("exec: StderrPipe after process started")
   436  	}
   437  	pr, pw, err := os.Pipe()
   438  	if err != nil {
   439  		return nil, err
   440  	}
   441  	c.Stderr = pw
   442  	c.closeAfterStart = append(c.closeAfterStart, pw)
   443  	c.closeAfterWait = append(c.closeAfterWait, pr)
   444  	return pr, nil
   445  }