daemon_unix.go 1.7 KB

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