main.go 6.1 KB

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