main.go 7.8 KB

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