main.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. )
  114. helpFunc := root.HelpFunc()
  115. root.SetHelpFunc(func(cmd *cobra.Command, args []string) {
  116. if !isOwnCommand(cmd) {
  117. mobycli.ExecIfDefaultCtxType(cmd.Context())
  118. }
  119. helpFunc(cmd, args)
  120. })
  121. root.PersistentFlags().BoolVarP(&opts.Debug, "debug", "D", false, "enable debug output in the logs")
  122. root.PersistentFlags().StringVarP(&opts.Host, "host", "H", "", "Daemon socket(s) to connect to")
  123. opts.AddConfigFlags(root.PersistentFlags())
  124. opts.AddContextFlags(root.PersistentFlags())
  125. root.Flags().BoolVarP(&opts.Version, "version", "v", false, "Print version information and quit")
  126. // populate the opts with the global flags
  127. _ = root.PersistentFlags().Parse(os.Args[1:])
  128. if opts.Debug {
  129. logrus.SetLevel(logrus.DebugLevel)
  130. }
  131. ctx, cancel := newSigContext()
  132. defer cancel()
  133. // --host and --version should immediately be forwarded to the original cli
  134. if opts.Host != "" || opts.Version {
  135. mobycli.Exec()
  136. }
  137. if opts.Config == "" {
  138. fatal(errors.New("config path cannot be empty"))
  139. }
  140. configDir := opts.Config
  141. ctx = config.WithDir(ctx, configDir)
  142. currentContext := determineCurrentContext(opts.Context, configDir)
  143. s, err := store.New(store.WithRoot(configDir))
  144. if err != nil {
  145. fatal(errors.Wrap(err, "unable to create context store"))
  146. }
  147. ctype := store.DefaultContextType
  148. cc, _ := s.Get(currentContext)
  149. if cc != nil {
  150. ctype = cc.Type()
  151. }
  152. if ctype == store.AwsContextType {
  153. exit(root, currentContext, errors.Errorf(`%q context type has been renamed. Recreate the context by running:
  154. $ docker context create %s <name>`, cc.Type(), store.EcsContextType))
  155. }
  156. metrics.Track(ctype, os.Args[1:], root.PersistentFlags())
  157. ctx = apicontext.WithCurrentContext(ctx, currentContext)
  158. ctx = store.WithContextStore(ctx, s)
  159. if err = root.ExecuteContext(ctx); err != nil {
  160. // if user canceled request, simply exit without any error message
  161. if errors.Is(ctx.Err(), context.Canceled) {
  162. os.Exit(130)
  163. }
  164. // Context should always be handled by new CLI
  165. requiredCmd, _, _ := root.Find(os.Args[1:])
  166. if requiredCmd != nil && isOwnCommand(requiredCmd) {
  167. exit(root, currentContext, err)
  168. }
  169. mobycli.ExecIfDefaultCtxType(ctx)
  170. checkIfUnknownCommandExistInDefaultContext(err, currentContext)
  171. exit(root, currentContext, err)
  172. }
  173. }
  174. func exit(cmd *cobra.Command, ctx string, err error) {
  175. if errors.Is(err, errdefs.ErrLoginRequired) {
  176. fmt.Fprintln(os.Stderr, err)
  177. os.Exit(errdefs.ExitCodeLoginRequired)
  178. }
  179. if errors.Is(err, errdefs.ErrNotImplemented) {
  180. cmd, _, _ := cmd.Traverse(os.Args[1:])
  181. name := cmd.Name()
  182. parent := cmd.Parent()
  183. if parent != nil && parent.Parent() != nil {
  184. name = parent.Name() + " " + name
  185. }
  186. fmt.Fprintf(os.Stderr, "Command %q not available in current context (%s)\n", name, ctx)
  187. os.Exit(1)
  188. }
  189. fatal(err)
  190. }
  191. func fatal(err error) {
  192. fmt.Fprintln(os.Stderr, err)
  193. os.Exit(1)
  194. }
  195. func checkIfUnknownCommandExistInDefaultContext(err error, currentContext string) {
  196. submatch := unknownCommandRegexp.FindSubmatch([]byte(err.Error()))
  197. if len(submatch) == 2 {
  198. dockerCommand := string(submatch[1])
  199. if mobycli.IsDefaultContextCommand(dockerCommand) {
  200. 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)
  201. os.Exit(1)
  202. }
  203. }
  204. }
  205. func newSigContext() (context.Context, func()) {
  206. ctx, cancel := context.WithCancel(context.Background())
  207. s := make(chan os.Signal, 1)
  208. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  209. go func() {
  210. <-s
  211. cancel()
  212. }()
  213. return ctx, cancel
  214. }
  215. func determineCurrentContext(flag string, configDir string) string {
  216. res := flag
  217. if res == "" {
  218. config, err := config.LoadFile(configDir)
  219. if err != nil {
  220. fmt.Fprintln(os.Stderr, errors.Wrap(err, "WARNING"))
  221. return "default"
  222. }
  223. res = config.CurrentContext
  224. }
  225. if res == "" {
  226. res = "default"
  227. }
  228. return res
  229. }