main.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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/compose-cli/cli/cmd/logout"
  25. "github.com/docker/compose-cli/errdefs"
  26. "github.com/pkg/errors"
  27. "github.com/sirupsen/logrus"
  28. "github.com/spf13/cobra"
  29. // Backend registrations
  30. _ "github.com/docker/compose-cli/aci"
  31. _ "github.com/docker/compose-cli/ecs"
  32. _ "github.com/docker/compose-cli/example"
  33. _ "github.com/docker/compose-cli/local"
  34. "github.com/docker/compose-cli/metrics"
  35. "github.com/docker/compose-cli/cli/cmd"
  36. "github.com/docker/compose-cli/cli/cmd/compose"
  37. contextcmd "github.com/docker/compose-cli/cli/cmd/context"
  38. "github.com/docker/compose-cli/cli/cmd/login"
  39. "github.com/docker/compose-cli/cli/cmd/run"
  40. "github.com/docker/compose-cli/cli/mobycli"
  41. cliopts "github.com/docker/compose-cli/cli/options"
  42. "github.com/docker/compose-cli/config"
  43. apicontext "github.com/docker/compose-cli/context"
  44. "github.com/docker/compose-cli/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.StartCommand(),
  107. cmd.InspectCommand(),
  108. compose.Command(),
  109. login.Command(),
  110. logout.Command(),
  111. cmd.VersionCommand(version),
  112. cmd.StopCommand(),
  113. cmd.SecretCommand(),
  114. // Place holders
  115. cmd.EcsCommand(),
  116. )
  117. helpFunc := root.HelpFunc()
  118. root.SetHelpFunc(func(cmd *cobra.Command, args []string) {
  119. if !isOwnCommand(cmd) {
  120. mobycli.ExecIfDefaultCtxType(cmd.Context())
  121. }
  122. helpFunc(cmd, args)
  123. })
  124. root.PersistentFlags().BoolVarP(&opts.Debug, "debug", "D", false, "enable debug output in the logs")
  125. root.PersistentFlags().StringVarP(&opts.Host, "host", "H", "", "Daemon socket(s) to connect to")
  126. opts.AddConfigFlags(root.PersistentFlags())
  127. opts.AddContextFlags(root.PersistentFlags())
  128. root.Flags().BoolVarP(&opts.Version, "version", "v", false, "Print version information and quit")
  129. // populate the opts with the global flags
  130. _ = root.PersistentFlags().Parse(os.Args[1:])
  131. if opts.Debug {
  132. logrus.SetLevel(logrus.DebugLevel)
  133. }
  134. ctx, cancel := newSigContext()
  135. defer cancel()
  136. // --host and --version should immediately be forwarded to the original cli
  137. if opts.Host != "" || opts.Version {
  138. mobycli.Exec()
  139. }
  140. if opts.Config == "" {
  141. fatal(errors.New("config path cannot be empty"))
  142. }
  143. configDir := opts.Config
  144. ctx = config.WithDir(ctx, configDir)
  145. currentContext := determineCurrentContext(opts.Context, configDir)
  146. s, err := store.New(store.WithRoot(configDir))
  147. if err != nil {
  148. fatal(errors.Wrap(err, "unable to create context store"))
  149. }
  150. ctype := store.DefaultContextType
  151. cc, _ := s.Get(currentContext)
  152. if cc != nil {
  153. ctype = cc.Type()
  154. }
  155. if ctype == store.AwsContextType {
  156. exit(root, currentContext, errors.Errorf(`%q context type has been renamed. Recreate the context by running:
  157. $ docker context create %s <name>`, cc.Type(), store.EcsContextType))
  158. }
  159. metrics.Track(ctype, os.Args[1:], root.PersistentFlags())
  160. ctx = apicontext.WithCurrentContext(ctx, currentContext)
  161. ctx = store.WithContextStore(ctx, s)
  162. if err = root.ExecuteContext(ctx); err != nil {
  163. // if user canceled request, simply exit without any error message
  164. if errors.Is(ctx.Err(), context.Canceled) {
  165. os.Exit(130)
  166. }
  167. // Context should always be handled by new CLI
  168. requiredCmd, _, _ := root.Find(os.Args[1:])
  169. if requiredCmd != nil && isOwnCommand(requiredCmd) {
  170. exit(root, currentContext, err)
  171. }
  172. mobycli.ExecIfDefaultCtxType(ctx)
  173. checkIfUnknownCommandExistInDefaultContext(err, currentContext)
  174. exit(root, currentContext, err)
  175. }
  176. }
  177. func exit(cmd *cobra.Command, ctx string, err error) {
  178. if errors.Is(err, errdefs.ErrLoginRequired) {
  179. fmt.Fprintln(os.Stderr, err)
  180. os.Exit(errdefs.ExitCodeLoginRequired)
  181. }
  182. if errors.Is(err, errdefs.ErrNotImplemented) {
  183. cmd, _, _ := cmd.Traverse(os.Args[1:])
  184. name := cmd.Name()
  185. parent := cmd.Parent()
  186. if parent != nil && parent.Parent() != nil {
  187. name = parent.Name() + " " + name
  188. }
  189. fmt.Fprintf(os.Stderr, "Command %q not available in current context (%s)\n", name, ctx)
  190. os.Exit(1)
  191. }
  192. fatal(err)
  193. }
  194. func fatal(err error) {
  195. fmt.Fprintln(os.Stderr, err)
  196. os.Exit(1)
  197. }
  198. func checkIfUnknownCommandExistInDefaultContext(err error, currentContext string) {
  199. submatch := unknownCommandRegexp.FindSubmatch([]byte(err.Error()))
  200. if len(submatch) == 2 {
  201. dockerCommand := string(submatch[1])
  202. if mobycli.IsDefaultContextCommand(dockerCommand) {
  203. 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)
  204. os.Exit(1)
  205. }
  206. }
  207. }
  208. func newSigContext() (context.Context, func()) {
  209. ctx, cancel := context.WithCancel(context.Background())
  210. s := make(chan os.Signal, 1)
  211. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  212. go func() {
  213. <-s
  214. cancel()
  215. }()
  216. return ctx, cancel
  217. }
  218. func determineCurrentContext(flag string, configDir string) string {
  219. res := flag
  220. if res == "" {
  221. config, err := config.LoadFile(configDir)
  222. if err != nil {
  223. fmt.Fprintln(os.Stderr, errors.Wrap(err, "WARNING"))
  224. return "default"
  225. }
  226. res = config.CurrentContext
  227. }
  228. if res == "" {
  229. res = "default"
  230. }
  231. return res
  232. }