main.go 6.8 KB

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