github.com/go/docker@v1.12.0-rc2/cmd/docker/daemon_unix.go (about)

     1  // +build daemon
     2  
     3  package main
     4  
     5  import (
     6  	"os"
     7  	"os/exec"
     8  	"path/filepath"
     9  	"syscall"
    10  )
    11  
    12  // CmdDaemon execs dockerd with the same flags
    13  func (p DaemonProxy) CmdDaemon(args ...string) error {
    14  	// Special case for handling `docker help daemon`. When pkg/mflag is removed
    15  	// we can support this on the daemon side, but that is not possible with
    16  	// pkg/mflag because it uses os.Exit(1) instead of returning an error on
    17  	// unexpected args.
    18  	if len(args) == 0 || args[0] != "--help" {
    19  		// Use os.Args[1:] so that "global" args are passed to dockerd
    20  		args = stripDaemonArg(os.Args[1:])
    21  	}
    22  
    23  	binaryPath, err := findDaemonBinary()
    24  	if err != nil {
    25  		return err
    26  	}
    27  
    28  	return syscall.Exec(
    29  		binaryPath,
    30  		append([]string{daemonBinary}, args...),
    31  		os.Environ())
    32  }
    33  
    34  // findDaemonBinary looks for the path to the dockerd binary starting with
    35  // the directory of the current executable (if one exists) and followed by $PATH
    36  func findDaemonBinary() (string, error) {
    37  	execDirname := filepath.Dir(os.Args[0])
    38  	if execDirname != "" {
    39  		binaryPath := filepath.Join(execDirname, daemonBinary)
    40  		if _, err := os.Stat(binaryPath); err == nil {
    41  			return binaryPath, nil
    42  		}
    43  	}
    44  
    45  	return exec.LookPath(daemonBinary)
    46  }
    47  
    48  // stripDaemonArg removes the `daemon` argument from the list
    49  func stripDaemonArg(args []string) []string {
    50  	for i, arg := range args {
    51  		if arg == "daemon" {
    52  			return append(args[:i], args[i+1:]...)
    53  		}
    54  	}
    55  	return args
    56  }