main.go 6.1 KB

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