main.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. /*
  2. Copyright 2020 Docker, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package main
  14. import (
  15. "context"
  16. "fmt"
  17. "math/rand"
  18. "os"
  19. "os/signal"
  20. "path/filepath"
  21. "regexp"
  22. "syscall"
  23. "time"
  24. "github.com/pkg/errors"
  25. "github.com/sirupsen/logrus"
  26. "github.com/spf13/cobra"
  27. // Backend registrations
  28. _ "github.com/docker/api/azure"
  29. _ "github.com/docker/api/example"
  30. _ "github.com/docker/api/local"
  31. "github.com/docker/api/cli/cmd"
  32. "github.com/docker/api/cli/cmd/compose"
  33. contextcmd "github.com/docker/api/cli/cmd/context"
  34. "github.com/docker/api/cli/cmd/login"
  35. "github.com/docker/api/cli/cmd/run"
  36. "github.com/docker/api/cli/mobycli"
  37. cliopts "github.com/docker/api/cli/options"
  38. "github.com/docker/api/config"
  39. apicontext "github.com/docker/api/context"
  40. "github.com/docker/api/context/store"
  41. )
  42. var (
  43. ownCommands = map[string]struct{}{
  44. "context": {},
  45. "login": {},
  46. "serve": {},
  47. "version": {},
  48. }
  49. )
  50. func init() {
  51. // initial hack to get the path of the project's bin dir
  52. // into the env of this cli for development
  53. path, err := filepath.Abs(filepath.Dir(os.Args[0]))
  54. if err != nil {
  55. fatal(errors.Wrap(err, "unable to get absolute bin path"))
  56. }
  57. if err := os.Setenv("PATH", fmt.Sprintf("%s:%s", os.Getenv("PATH"), path)); err != nil {
  58. panic(err)
  59. }
  60. // Seed random
  61. rand.Seed(time.Now().UnixNano())
  62. }
  63. func isOwnCommand(cmd *cobra.Command) bool {
  64. if cmd == nil {
  65. return false
  66. }
  67. if _, ok := ownCommands[cmd.Name()]; ok {
  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. if !isOwnCommand(cmd) {
  81. mobycli.ExecIfDefaultCtxType(cmd.Context())
  82. }
  83. return nil
  84. },
  85. RunE: func(cmd *cobra.Command, args []string) error {
  86. return cmd.Help()
  87. },
  88. }
  89. root.AddCommand(
  90. contextcmd.Command(),
  91. cmd.PsCommand(),
  92. cmd.ServeCommand(),
  93. run.Command(),
  94. cmd.ExecCommand(),
  95. cmd.LogsCommand(),
  96. cmd.RmCommand(),
  97. cmd.InspectCommand(),
  98. compose.Command(),
  99. login.Command(),
  100. cmd.VersionCommand(),
  101. )
  102. helpFunc := root.HelpFunc()
  103. root.SetHelpFunc(func(cmd *cobra.Command, args []string) {
  104. if !isOwnCommand(cmd) {
  105. mobycli.ExecIfDefaultCtxType(cmd.Context())
  106. }
  107. helpFunc(cmd, args)
  108. })
  109. root.PersistentFlags().BoolVarP(&opts.Debug, "debug", "d", false, "enable debug output in the logs")
  110. opts.AddConfigFlags(root.PersistentFlags())
  111. opts.AddContextFlags(root.PersistentFlags())
  112. // populate the opts with the global flags
  113. _ = root.PersistentFlags().Parse(os.Args[1:])
  114. if opts.Debug {
  115. logrus.SetLevel(logrus.DebugLevel)
  116. }
  117. ctx, cancel := newSigContext()
  118. defer cancel()
  119. if opts.Config == "" {
  120. fatal(errors.New("config path cannot be empty"))
  121. }
  122. configDir := opts.Config
  123. ctx = config.WithDir(ctx, configDir)
  124. currentContext := determineCurrentContext(opts.Context, configDir)
  125. s, err := store.New(store.WithRoot(configDir))
  126. if err != nil {
  127. fatal(errors.Wrap(err, "unable to create context store"))
  128. }
  129. ctx = apicontext.WithCurrentContext(ctx, currentContext)
  130. ctx = store.WithContextStore(ctx, s)
  131. err = root.ExecuteContext(ctx)
  132. if err != nil {
  133. // Context should always be handled by new CLI
  134. requiredCmd, _, _ := root.Find(os.Args[1:])
  135. if requiredCmd != nil && isOwnCommand(requiredCmd) {
  136. fmt.Fprintln(os.Stderr, err)
  137. os.Exit(1)
  138. }
  139. mobycli.ExecIfDefaultCtxType(ctx)
  140. checkIfUnknownCommandExistInDefaultContext(err, currentContext)
  141. fmt.Fprintln(os.Stderr, err)
  142. os.Exit(1)
  143. }
  144. }
  145. func checkIfUnknownCommandExistInDefaultContext(err error, currentContext string) {
  146. re := regexp.MustCompile(`unknown command "([^"]*)"`)
  147. submatch := re.FindSubmatch([]byte(err.Error()))
  148. if len(submatch) == 2 {
  149. dockerCommand := string(submatch[1])
  150. if mobycli.IsDefaultContextCommand(dockerCommand) {
  151. fmt.Fprintf(os.Stderr, "Command \"%s\" not available in current context (%s), you can use the \"default\" context to run this command\n", dockerCommand, currentContext)
  152. os.Exit(1)
  153. }
  154. }
  155. }
  156. func newSigContext() (context.Context, func()) {
  157. ctx, cancel := context.WithCancel(context.Background())
  158. s := make(chan os.Signal)
  159. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  160. go func() {
  161. <-s
  162. cancel()
  163. }()
  164. return ctx, cancel
  165. }
  166. func determineCurrentContext(flag string, configDir string) string {
  167. res := flag
  168. if res == "" {
  169. config, err := config.LoadFile(configDir)
  170. if err != nil {
  171. fmt.Fprintln(os.Stderr, errors.Wrap(err, "WARNING"))
  172. return "default"
  173. }
  174. res = config.CurrentContext
  175. }
  176. if res == "" {
  177. res = "default"
  178. }
  179. return res
  180. }
  181. func fatal(err error) {
  182. fmt.Fprint(os.Stderr, err)
  183. os.Exit(1)
  184. }