main.go 7.7 KB

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