github.com/zhuohuang-hust/src-cbuild@v0.0.0-20230105071821-c7aab3e7c840/cmd/firstContainer/daemon_unix.go (about)

     1  package firstContainer
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"os"
     7  	"os/exec"
     8  	"path/filepath"
     9  	"syscall"
    10  
    11  	"github.com/spf13/cobra"
    12  )
    13  
    14  const daemonBinary = "dockerd"
    15  
    16  func newDaemonCommand() *cobra.Command {
    17      fmt.Println("cmd/firstContainer/daemon_unix.go  newDaemonCommand()")
    18  	cmd := &cobra.Command{
    19  		Use:                "daemon",
    20  		Hidden:             true,
    21  		Args:               cobra.ArbitraryArgs,
    22  		DisableFlagParsing: true,
    23  		RunE: func(cmd *cobra.Command, args []string) error {
    24  			return runDaemon()
    25  		},
    26  		Deprecated: "and will be removed in Docker 1.16. Please run `dockerd` directly.",
    27  	}
    28  	cmd.SetHelpFunc(helpFunc)
    29  	return cmd
    30  }
    31  
    32  // CmdDaemon execs dockerd with the same flags
    33  func runDaemon() error {
    34  	// Use os.Args[1:] so that "global" args are passed to dockerd
    35  	return execDaemon(stripDaemonArg(os.Args[1:]))
    36  }
    37  
    38  func execDaemon(args []string) error {
    39  	binaryPath, err := findDaemonBinary()
    40  	if err != nil {
    41  		return err
    42  	}
    43  
    44  	return syscall.Exec(
    45  		binaryPath,
    46  		append([]string{daemonBinary}, args...),
    47  		os.Environ())
    48  }
    49  
    50  func helpFunc(cmd *cobra.Command, args []string) {
    51  	if err := execDaemon([]string{"--help"}); err != nil {
    52  		fmt.Fprintf(os.Stderr, "%s\n", err.Error())
    53  	}
    54  }
    55  
    56  // findDaemonBinary looks for the path to the dockerd binary starting with
    57  // the directory of the current executable (if one exists) and followed by $PATH
    58  func findDaemonBinary() (string, error) {
    59  	execDirname := filepath.Dir(os.Args[0])
    60  	if execDirname != "" {
    61  		binaryPath := filepath.Join(execDirname, daemonBinary)
    62  		if _, err := os.Stat(binaryPath); err == nil {
    63  			return binaryPath, nil
    64  		}
    65  	}
    66  
    67  	return exec.LookPath(daemonBinary)
    68  }
    69  
    70  // stripDaemonArg removes the `daemon` argument from the list
    71  func stripDaemonArg(args []string) []string {
    72  	for i, arg := range args {
    73  		if arg == "daemon" {
    74  			return append(args[:i], args[i+1:]...)
    75  		}
    76  	}
    77  	return args
    78  }