main.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. "math/rand"
  29. "os"
  30. "os/exec"
  31. "os/signal"
  32. "path/filepath"
  33. "syscall"
  34. "time"
  35. "github.com/pkg/errors"
  36. "github.com/sirupsen/logrus"
  37. "github.com/spf13/cobra"
  38. // Backend registrations
  39. _ "github.com/docker/api/azure"
  40. _ "github.com/docker/api/example"
  41. _ "github.com/docker/api/moby"
  42. "github.com/docker/api/cli/cmd"
  43. "github.com/docker/api/cli/cmd/compose"
  44. contextcmd "github.com/docker/api/cli/cmd/context"
  45. "github.com/docker/api/cli/cmd/run"
  46. cliconfig "github.com/docker/api/cli/config"
  47. cliopts "github.com/docker/api/cli/options"
  48. apicontext "github.com/docker/api/context"
  49. "github.com/docker/api/context/store"
  50. )
  51. var (
  52. runningOwnCommand bool
  53. )
  54. func init() {
  55. // initial hack to get the path of the project's bin dir
  56. // into the env of this cli for development
  57. path, err := filepath.Abs(filepath.Dir(os.Args[0]))
  58. if err != nil {
  59. fatal(errors.Wrap(err, "unable to get absolute bin path"))
  60. }
  61. if err := os.Setenv("PATH", fmt.Sprintf("%s:%s", os.Getenv("PATH"), path)); err != nil {
  62. panic(err)
  63. }
  64. // Seed random
  65. rand.Seed(time.Now().UnixNano())
  66. }
  67. func isOwnCommand(cmd *cobra.Command) bool {
  68. if cmd == nil {
  69. return false
  70. }
  71. if cmd.Name() == "context" || cmd.Name() == "serve" {
  72. return true
  73. }
  74. return isOwnCommand(cmd.Parent())
  75. }
  76. func main() {
  77. var opts cliopts.GlobalOpts
  78. root := &cobra.Command{
  79. Use: "docker",
  80. Long: "docker for the 2020s",
  81. SilenceErrors: true,
  82. SilenceUsage: true,
  83. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  84. runningOwnCommand = isOwnCommand(cmd)
  85. if !runningOwnCommand {
  86. execMoby(cmd.Context())
  87. }
  88. return nil
  89. },
  90. RunE: func(cmd *cobra.Command, args []string) error {
  91. return cmd.Help()
  92. },
  93. }
  94. root.AddCommand(
  95. contextcmd.Command(),
  96. cmd.PsCommand(),
  97. cmd.ServeCommand(),
  98. run.Command(),
  99. cmd.ExecCommand(),
  100. cmd.LogsCommand(),
  101. cmd.RmCommand(),
  102. compose.Command(),
  103. )
  104. helpFunc := root.HelpFunc()
  105. root.SetHelpFunc(func(cmd *cobra.Command, args []string) {
  106. runningOwnCommand = isOwnCommand(cmd)
  107. if !runningOwnCommand {
  108. execMoby(cmd.Context())
  109. }
  110. helpFunc(cmd, args)
  111. })
  112. root.PersistentFlags().BoolVarP(&opts.Debug, "debug", "d", false, "enable debug output in the logs")
  113. opts.AddConfigFlags(root.PersistentFlags())
  114. opts.AddContextFlags(root.PersistentFlags())
  115. // populate the opts with the global flags
  116. _ = root.PersistentFlags().Parse(os.Args[1:])
  117. if opts.Debug {
  118. logrus.SetLevel(logrus.DebugLevel)
  119. }
  120. ctx, cancel := newSigContext()
  121. defer cancel()
  122. if opts.Config == "" {
  123. fatal(errors.New("config path cannot be empty"))
  124. }
  125. configDir := opts.Config
  126. ctx = cliconfig.WithDir(ctx, configDir)
  127. currentContext, err := determineCurrentContext(opts.Context, configDir)
  128. if err != nil {
  129. fatal(errors.New("unable to determine current context"))
  130. }
  131. s, err := store.New(store.WithRoot(configDir))
  132. if err != nil {
  133. fatal(errors.Wrap(err, "unable to create context store"))
  134. }
  135. ctx = apicontext.WithCurrentContext(ctx, currentContext)
  136. ctx = store.WithContextStore(ctx, s)
  137. if err = root.ExecuteContext(ctx); err != nil {
  138. // Context should always be handled by new CLI
  139. if runningOwnCommand {
  140. fmt.Fprintln(os.Stderr, err)
  141. os.Exit(1)
  142. }
  143. execMoby(ctx)
  144. fmt.Println(err)
  145. os.Exit(1)
  146. }
  147. }
  148. func newSigContext() (context.Context, func()) {
  149. ctx, cancel := context.WithCancel(context.Background())
  150. s := make(chan os.Signal)
  151. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  152. go func() {
  153. <-s
  154. cancel()
  155. }()
  156. return ctx, cancel
  157. }
  158. func execMoby(ctx context.Context) {
  159. currentContext := apicontext.CurrentContext(ctx)
  160. s := store.ContextStore(ctx)
  161. _, err := s.Get(currentContext)
  162. // Only run original docker command if the current context is not
  163. // ours.
  164. if err != nil {
  165. cmd := exec.Command("docker-classic", os.Args[1:]...)
  166. cmd.Stdin = os.Stdin
  167. cmd.Stdout = os.Stdout
  168. cmd.Stderr = os.Stderr
  169. if err := cmd.Run(); err != nil {
  170. if exiterr, ok := err.(*exec.ExitError); ok {
  171. fmt.Fprintln(os.Stderr, exiterr.Error())
  172. os.Exit(exiterr.ExitCode())
  173. }
  174. fmt.Fprintln(os.Stderr, err)
  175. os.Exit(1)
  176. }
  177. os.Exit(0)
  178. }
  179. }
  180. func determineCurrentContext(flag string, configDir string) (string, error) {
  181. res := flag
  182. if res == "" {
  183. config, err := cliconfig.LoadFile(configDir)
  184. if err != nil {
  185. return "", err
  186. }
  187. res = config.CurrentContext
  188. }
  189. if res == "" {
  190. res = "default"
  191. }
  192. return res, nil
  193. }
  194. func fatal(err error) {
  195. fmt.Fprint(os.Stderr, err)
  196. os.Exit(1)
  197. }