main.go 6.1 KB

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