main.go 5.4 KB

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