main.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. "log"
  29. "os"
  30. "os/exec"
  31. "path/filepath"
  32. "strings"
  33. "github.com/docker/api/cli/cmd"
  34. apicontext "github.com/docker/api/context"
  35. "github.com/docker/api/context/store"
  36. "github.com/docker/api/util"
  37. "github.com/sirupsen/logrus"
  38. "github.com/spf13/cobra"
  39. )
  40. type mainOpts struct {
  41. apicontext.ContextFlags
  42. debug bool
  43. }
  44. func init() {
  45. // initial hack to get the path of the project's bin dir
  46. // into the env of this cli for development
  47. path, err := filepath.Abs(filepath.Dir(os.Args[0]))
  48. if err != nil {
  49. log.Fatal(err)
  50. }
  51. if err := os.Setenv("PATH", fmt.Sprintf("%s:%s", os.Getenv("PATH"), path)); err != nil {
  52. panic(err)
  53. }
  54. }
  55. func isContextCommand(cmd *cobra.Command) bool {
  56. if cmd == nil {
  57. return false
  58. }
  59. if cmd.Name() == "context" {
  60. return true
  61. }
  62. return isContextCommand(cmd.Parent())
  63. }
  64. func main() {
  65. var opts mainOpts
  66. root := &cobra.Command{
  67. Use: "docker",
  68. Long: "docker for the 2020s",
  69. SilenceErrors: true,
  70. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  71. if !isContextCommand(cmd) {
  72. execMoby(cmd.Context())
  73. }
  74. return nil
  75. },
  76. RunE: func(cmd *cobra.Command, args []string) error {
  77. return cmd.Help()
  78. },
  79. }
  80. helpFunc := root.HelpFunc()
  81. root.SetHelpFunc(func(cmd *cobra.Command, args []string) {
  82. if !isContextCommand(cmd) {
  83. execMoby(cmd.Context())
  84. }
  85. helpFunc(cmd, args)
  86. })
  87. root.PersistentFlags().BoolVarP(&opts.debug, "debug", "d", false, "enable debug output in the logs")
  88. opts.AddFlags(root.PersistentFlags())
  89. // populate the opts with the global flags
  90. _ = root.PersistentFlags().Parse(os.Args[1:])
  91. if opts.debug {
  92. logrus.SetLevel(logrus.DebugLevel)
  93. }
  94. root.AddCommand(
  95. cmd.ContextCommand(),
  96. &cmd.ExampleCommand,
  97. )
  98. ctx, cancel := util.NewSigContext()
  99. defer cancel()
  100. ctx, err := withCurrentContext(ctx, opts)
  101. if err != nil {
  102. logrus.Fatal(err)
  103. }
  104. s, err := store.New(opts.Config)
  105. if err != nil {
  106. logrus.Fatal(err)
  107. }
  108. ctx = store.WithContextStore(ctx, s)
  109. if err = root.ExecuteContext(ctx); err != nil {
  110. if strings.Contains(err.Error(), "unknown command") {
  111. execMoby(ctx)
  112. }
  113. fmt.Println(err)
  114. os.Exit(1)
  115. }
  116. }
  117. type currentContextKey struct{}
  118. func withCurrentContext(ctx context.Context, opts mainOpts) (context.Context, error) {
  119. config, err := apicontext.LoadConfigFile(opts.Config, "config.json")
  120. if err != nil {
  121. return ctx, err
  122. }
  123. currentContext := opts.Context
  124. if currentContext == "" {
  125. currentContext = config.CurrentContext
  126. }
  127. if currentContext == "" {
  128. currentContext = "default"
  129. }
  130. logrus.Debugf("Current context %q", currentContext)
  131. return context.WithValue(ctx, currentContextKey{}, currentContext), nil
  132. }
  133. // CurrentContext returns the current context name
  134. func CurrentContext(ctx context.Context) string {
  135. cc, _ := ctx.Value(currentContextKey{}).(string)
  136. return cc
  137. }
  138. func execMoby(ctx context.Context) {
  139. currentContext := CurrentContext(ctx)
  140. s := store.ContextStore(ctx)
  141. cc, err := s.Get(currentContext)
  142. if err != nil {
  143. logrus.Fatal(err)
  144. }
  145. // Only run original docker command if the current context is not
  146. // ours.
  147. _, ok := cc.Metadata.(store.TypeContext)
  148. if !ok {
  149. cmd := exec.Command("docker", os.Args[1:]...)
  150. cmd.Stdin = os.Stdin
  151. cmd.Stdout = os.Stdout
  152. cmd.Stderr = os.Stderr
  153. if err := cmd.Run(); err != nil {
  154. if err != nil {
  155. if exiterr, ok := err.(*exec.ExitError); ok {
  156. os.Exit(exiterr.ExitCode())
  157. }
  158. os.Exit(1)
  159. }
  160. }
  161. os.Exit(0)
  162. }
  163. }