main.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. /*
  2. Copyright (c) 2020 Docker Inc.
  3. Permission is hereby granted, free of charge, to any person
  4. obtaining a copy of this software and associated documentation
  5. files (the "Software"), to deal in the Software without
  6. restriction, including without limitation the rights to use, copy,
  7. modify, merge, publish, distribute, sublicense, and/or sell copies
  8. of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be
  11. included in all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  13. EXPRESS OR IMPLIED,
  14. INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  16. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  17. HOLDERS BE LIABLE FOR ANY CLAIM,
  18. DAMAGES OR OTHER LIABILITY,
  19. WHETHER IN AN ACTION OF CONTRACT,
  20. TORT OR OTHERWISE,
  21. ARISING FROM, OUT OF OR IN CONNECTION WITH
  22. THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. */
  24. package main
  25. import (
  26. "context"
  27. "fmt"
  28. "os"
  29. "os/exec"
  30. "os/signal"
  31. "path/filepath"
  32. "syscall"
  33. "github.com/pkg/errors"
  34. "github.com/sirupsen/logrus"
  35. "github.com/spf13/cobra"
  36. // Backend registrations
  37. _ "github.com/docker/api/azure"
  38. _ "github.com/docker/api/example"
  39. _ "github.com/docker/api/moby"
  40. "github.com/docker/api/cli/cmd"
  41. "github.com/docker/api/cli/cmd/compose"
  42. contextcmd "github.com/docker/api/cli/cmd/context"
  43. "github.com/docker/api/cli/cmd/run"
  44. cliconfig "github.com/docker/api/cli/config"
  45. cliopts "github.com/docker/api/cli/options"
  46. apicontext "github.com/docker/api/context"
  47. "github.com/docker/api/context/store"
  48. )
  49. var (
  50. runningOwnCommand bool
  51. )
  52. func init() {
  53. // initial hack to get the path of the project's bin dir
  54. // into the env of this cli for development
  55. path, err := filepath.Abs(filepath.Dir(os.Args[0]))
  56. if err != nil {
  57. fatal(errors.Wrap(err, "unable to get absolute bin path"))
  58. }
  59. if err := os.Setenv("PATH", fmt.Sprintf("%s:%s", os.Getenv("PATH"), path)); err != nil {
  60. panic(err)
  61. }
  62. }
  63. func isOwnCommand(cmd *cobra.Command) bool {
  64. if cmd == nil {
  65. return false
  66. }
  67. if cmd.Name() == "context" || cmd.Name() == "serve" {
  68. return true
  69. }
  70. return isOwnCommand(cmd.Parent())
  71. }
  72. func main() {
  73. var opts cliopts.GlobalOpts
  74. root := &cobra.Command{
  75. Use: "docker",
  76. Long: "docker for the 2020s",
  77. SilenceErrors: true,
  78. SilenceUsage: true,
  79. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  80. runningOwnCommand = isOwnCommand(cmd)
  81. if !runningOwnCommand {
  82. execMoby(cmd.Context())
  83. }
  84. return nil
  85. },
  86. RunE: func(cmd *cobra.Command, args []string) error {
  87. return cmd.Help()
  88. },
  89. }
  90. root.AddCommand(
  91. contextcmd.Command(&opts),
  92. cmd.PsCommand(),
  93. cmd.ServeCommand(),
  94. run.Command(),
  95. cmd.ExecCommand(),
  96. cmd.LogsCommand(),
  97. cmd.RmCommand(),
  98. compose.Command(),
  99. )
  100. helpFunc := root.HelpFunc()
  101. root.SetHelpFunc(func(cmd *cobra.Command, args []string) {
  102. runningOwnCommand = isOwnCommand(cmd)
  103. if !runningOwnCommand {
  104. execMoby(cmd.Context())
  105. }
  106. helpFunc(cmd, args)
  107. })
  108. root.PersistentFlags().BoolVarP(&opts.Debug, "debug", "d", false, "enable debug output in the logs")
  109. opts.AddConfigFlags(root.PersistentFlags())
  110. opts.AddContextFlags(root.PersistentFlags())
  111. // populate the opts with the global flags
  112. _ = root.PersistentFlags().Parse(os.Args[1:])
  113. if opts.Debug {
  114. logrus.SetLevel(logrus.DebugLevel)
  115. }
  116. ctx, cancel := newSigContext()
  117. defer cancel()
  118. if opts.Config == "" {
  119. fatal(errors.New("config path cannot be empty"))
  120. }
  121. config, err := cliconfig.LoadFile(opts.Config)
  122. if err != nil {
  123. fatal(errors.Wrap(err, "unable to find configuration file"))
  124. }
  125. currentContext := opts.Context
  126. if currentContext == "" {
  127. currentContext = config.CurrentContext
  128. }
  129. if currentContext == "" {
  130. currentContext = "default"
  131. }
  132. s, err := store.New(store.WithRoot(opts.Config))
  133. if err != nil {
  134. fatal(errors.Wrap(err, "unable to create context store"))
  135. }
  136. ctx = apicontext.WithCurrentContext(ctx, currentContext)
  137. ctx = store.WithContextStore(ctx, s)
  138. if err = root.ExecuteContext(ctx); err != nil {
  139. // Context should always be handled by new CLI
  140. if runningOwnCommand {
  141. fmt.Fprintln(os.Stderr, err)
  142. os.Exit(1)
  143. }
  144. execMoby(ctx)
  145. fmt.Println(err)
  146. os.Exit(1)
  147. }
  148. }
  149. func newSigContext() (context.Context, func()) {
  150. ctx, cancel := context.WithCancel(context.Background())
  151. s := make(chan os.Signal)
  152. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  153. go func() {
  154. <-s
  155. cancel()
  156. }()
  157. return ctx, cancel
  158. }
  159. func execMoby(ctx context.Context) {
  160. currentContext := apicontext.CurrentContext(ctx)
  161. s := store.ContextStore(ctx)
  162. _, err := s.Get(currentContext, nil)
  163. // Only run original docker command if the current context is not
  164. // ours.
  165. if err != nil {
  166. cmd := exec.Command("docker", os.Args[1:]...)
  167. cmd.Stdin = os.Stdin
  168. cmd.Stdout = os.Stdout
  169. cmd.Stderr = os.Stderr
  170. if err := cmd.Run(); err != nil {
  171. if exiterr, ok := err.(*exec.ExitError); ok {
  172. os.Exit(exiterr.ExitCode())
  173. }
  174. os.Exit(1)
  175. }
  176. os.Exit(0)
  177. }
  178. }
  179. func fatal(err error) {
  180. fmt.Fprint(os.Stderr, err)
  181. os.Exit(1)
  182. }