main.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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/metrics"
  32. "github.com/docker/api/cli/cmd"
  33. "github.com/docker/api/cli/cmd/compose"
  34. contextcmd "github.com/docker/api/cli/cmd/context"
  35. "github.com/docker/api/cli/cmd/login"
  36. "github.com/docker/api/cli/cmd/run"
  37. "github.com/docker/api/cli/mobycli"
  38. cliopts "github.com/docker/api/cli/options"
  39. "github.com/docker/api/config"
  40. apicontext "github.com/docker/api/context"
  41. "github.com/docker/api/context/store"
  42. )
  43. var (
  44. ownCommands = map[string]struct{}{
  45. "context": {},
  46. "login": {},
  47. "serve": {},
  48. "version": {},
  49. }
  50. )
  51. func init() {
  52. // initial hack to get the path of the project's bin dir
  53. // into the env of this cli for development
  54. path, err := filepath.Abs(filepath.Dir(os.Args[0]))
  55. if err != nil {
  56. fatal(errors.Wrap(err, "unable to get absolute bin path"))
  57. }
  58. if err := os.Setenv("PATH", fmt.Sprintf("%s:%s", os.Getenv("PATH"), path)); err != nil {
  59. panic(err)
  60. }
  61. // Seed random
  62. rand.Seed(time.Now().UnixNano())
  63. }
  64. func isOwnCommand(cmd *cobra.Command) bool {
  65. if cmd == nil {
  66. return false
  67. }
  68. if _, ok := ownCommands[cmd.Name()]; ok {
  69. return true
  70. }
  71. return isOwnCommand(cmd.Parent())
  72. }
  73. func main() {
  74. var opts cliopts.GlobalOpts
  75. root := &cobra.Command{
  76. Use: "docker",
  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. root.PersistentFlags().StringVarP(&opts.Host, "host", "H", "", "Daemon socket(s) to connect to")
  111. opts.AddConfigFlags(root.PersistentFlags())
  112. opts.AddContextFlags(root.PersistentFlags())
  113. root.Flags().BoolVarP(&opts.Version, "version", "v", false, "Print version information and quit")
  114. // populate the opts with the global flags
  115. _ = root.PersistentFlags().Parse(os.Args[1:])
  116. if opts.Debug {
  117. logrus.SetLevel(logrus.DebugLevel)
  118. }
  119. ctx, cancel := newSigContext()
  120. defer cancel()
  121. if opts.Host != "" {
  122. mobycli.ExecRegardlessContext(ctx)
  123. }
  124. if opts.Version {
  125. mobycli.ExecRegardlessContext(ctx)
  126. }
  127. if opts.Config == "" {
  128. fatal(errors.New("config path cannot be empty"))
  129. }
  130. configDir := opts.Config
  131. ctx = config.WithDir(ctx, configDir)
  132. currentContext := determineCurrentContext(opts.Context, configDir)
  133. s, err := store.New(store.WithRoot(configDir))
  134. if err != nil {
  135. fatal(errors.Wrap(err, "unable to create context store"))
  136. }
  137. ctype := store.DefaultContextType
  138. cc, _ := s.Get(currentContext)
  139. if cc != nil {
  140. ctype = cc.Type()
  141. }
  142. metrics.Track(ctype, os.Args[1:], root.PersistentFlags())
  143. ctx = apicontext.WithCurrentContext(ctx, currentContext)
  144. ctx = store.WithContextStore(ctx, s)
  145. err = root.ExecuteContext(ctx)
  146. if err != nil {
  147. // Context should always be handled by new CLI
  148. requiredCmd, _, _ := root.Find(os.Args[1:])
  149. if requiredCmd != nil && isOwnCommand(requiredCmd) {
  150. fmt.Fprintln(os.Stderr, err)
  151. os.Exit(1)
  152. }
  153. mobycli.ExecIfDefaultCtxType(ctx)
  154. checkIfUnknownCommandExistInDefaultContext(err, currentContext)
  155. fmt.Fprintln(os.Stderr, err)
  156. os.Exit(1)
  157. }
  158. }
  159. func checkIfUnknownCommandExistInDefaultContext(err error, currentContext string) {
  160. re := regexp.MustCompile(`unknown command "([^"]*)"`)
  161. submatch := re.FindSubmatch([]byte(err.Error()))
  162. if len(submatch) == 2 {
  163. dockerCommand := string(submatch[1])
  164. if mobycli.IsDefaultContextCommand(dockerCommand) {
  165. 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)
  166. os.Exit(1)
  167. }
  168. }
  169. }
  170. func newSigContext() (context.Context, func()) {
  171. ctx, cancel := context.WithCancel(context.Background())
  172. s := make(chan os.Signal)
  173. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  174. go func() {
  175. <-s
  176. cancel()
  177. }()
  178. return ctx, cancel
  179. }
  180. func determineCurrentContext(flag string, configDir string) string {
  181. res := flag
  182. if res == "" {
  183. config, err := config.LoadFile(configDir)
  184. if err != nil {
  185. fmt.Fprintln(os.Stderr, errors.Wrap(err, "WARNING"))
  186. return "default"
  187. }
  188. res = config.CurrentContext
  189. }
  190. if res == "" {
  191. res = "default"
  192. }
  193. return res
  194. }
  195. func fatal(err error) {
  196. fmt.Fprint(os.Stderr, err)
  197. os.Exit(1)
  198. }