main.go 7.1 KB

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