daemon_unix.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. RunE: func(cmd *cobra.Command, args []string) error {
  17. return runDaemon()
  18. },
  19. }
  20. cmd.SetHelpFunc(helpFunc)
  21. return cmd
  22. }
  23. // CmdDaemon execs dockerd with the same flags
  24. func runDaemon() error {
  25. // Use os.Args[1:] so that "global" args are passed to dockerd
  26. return execDaemon(stripDaemonArg(os.Args[1:]))
  27. }
  28. func execDaemon(args []string) error {
  29. binaryPath, err := findDaemonBinary()
  30. if err != nil {
  31. return err
  32. }
  33. return syscall.Exec(
  34. binaryPath,
  35. append([]string{daemonBinary}, args...),
  36. os.Environ())
  37. }
  38. func helpFunc(cmd *cobra.Command, args []string) {
  39. if err := execDaemon([]string{"--help"}); err != nil {
  40. fmt.Fprintf(os.Stderr, "%s\n", err.Error())
  41. }
  42. }
  43. // findDaemonBinary looks for the path to the dockerd binary starting with
  44. // the directory of the current executable (if one exists) and followed by $PATH
  45. func findDaemonBinary() (string, error) {
  46. execDirname := filepath.Dir(os.Args[0])
  47. if execDirname != "" {
  48. binaryPath := filepath.Join(execDirname, daemonBinary)
  49. if _, err := os.Stat(binaryPath); err == nil {
  50. return binaryPath, nil
  51. }
  52. }
  53. return exec.LookPath(daemonBinary)
  54. }
  55. // stripDaemonArg removes the `daemon` argument from the list
  56. func stripDaemonArg(args []string) []string {
  57. for i, arg := range args {
  58. if arg == "daemon" {
  59. return append(args[:i], args[i+1:]...)
  60. }
  61. }
  62. return args
  63. }