main.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. SilenceErrors: true,
  77. SilenceUsage: true,
  78. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  79. if !isOwnCommand(cmd) {
  80. mobycli.ExecIfDefaultCtxType(cmd.Context())
  81. }
  82. return nil
  83. },
  84. RunE: func(cmd *cobra.Command, args []string) error {
  85. return cmd.Help()
  86. },
  87. }
  88. root.AddCommand(
  89. contextcmd.Command(),
  90. cmd.PsCommand(),
  91. cmd.ServeCommand(),
  92. run.Command(),
  93. cmd.ExecCommand(),
  94. cmd.LogsCommand(),
  95. cmd.RmCommand(),
  96. cmd.InspectCommand(),
  97. compose.Command(),
  98. login.Command(),
  99. cmd.VersionCommand(),
  100. )
  101. helpFunc := root.HelpFunc()
  102. root.SetHelpFunc(func(cmd *cobra.Command, args []string) {
  103. if !isOwnCommand(cmd) {
  104. mobycli.ExecIfDefaultCtxType(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. configDir := opts.Config
  122. ctx = config.WithDir(ctx, configDir)
  123. currentContext := determineCurrentContext(opts.Context, configDir)
  124. s, err := store.New(store.WithRoot(configDir))
  125. if err != nil {
  126. fatal(errors.Wrap(err, "unable to create context store"))
  127. }
  128. ctx = apicontext.WithCurrentContext(ctx, currentContext)
  129. ctx = store.WithContextStore(ctx, s)
  130. err = root.ExecuteContext(ctx)
  131. if err != nil {
  132. // Context should always be handled by new CLI
  133. requiredCmd, _, _ := root.Find(os.Args[1:])
  134. if requiredCmd != nil && isOwnCommand(requiredCmd) {
  135. fmt.Fprintln(os.Stderr, err)
  136. os.Exit(1)
  137. }
  138. mobycli.ExecIfDefaultCtxType(ctx)
  139. checkIfUnknownCommandExistInDefaultContext(err, currentContext)
  140. fmt.Fprintln(os.Stderr, err)
  141. os.Exit(1)
  142. }
  143. }
  144. func checkIfUnknownCommandExistInDefaultContext(err error, currentContext string) {
  145. re := regexp.MustCompile(`unknown command "([^"]*)"`)
  146. submatch := re.FindSubmatch([]byte(err.Error()))
  147. if len(submatch) == 2 {
  148. dockerCommand := string(submatch[1])
  149. if mobycli.IsDefaultContextCommand(dockerCommand) {
  150. 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)
  151. os.Exit(1)
  152. }
  153. }
  154. }
  155. func newSigContext() (context.Context, func()) {
  156. ctx, cancel := context.WithCancel(context.Background())
  157. s := make(chan os.Signal)
  158. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  159. go func() {
  160. <-s
  161. cancel()
  162. }()
  163. return ctx, cancel
  164. }
  165. func determineCurrentContext(flag string, configDir string) string {
  166. res := flag
  167. if res == "" {
  168. config, err := config.LoadFile(configDir)
  169. if err != nil {
  170. fmt.Fprintln(os.Stderr, errors.Wrap(err, "WARNING"))
  171. return "default"
  172. }
  173. res = config.CurrentContext
  174. }
  175. if res == "" {
  176. res = "default"
  177. }
  178. return res
  179. }
  180. func fatal(err error) {
  181. fmt.Fprint(os.Stderr, err)
  182. os.Exit(1)
  183. }