main.go 5.8 KB

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