main.go 5.7 KB

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