main.go 7.7 KB

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