main.go 7.8 KB

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