main.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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/pkg/errors"
  25. "github.com/sirupsen/logrus"
  26. "github.com/spf13/cobra"
  27. "github.com/docker/compose-cli/cli/cmd/compose"
  28. "github.com/docker/compose-cli/cli/cmd/logout"
  29. volume "github.com/docker/compose-cli/cli/cmd/volume"
  30. "github.com/docker/compose-cli/errdefs"
  31. // Backend registrations
  32. _ "github.com/docker/compose-cli/aci"
  33. "github.com/docker/compose-cli/cli/cmd"
  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/run"
  37. "github.com/docker/compose-cli/cli/mobycli"
  38. cliopts "github.com/docker/compose-cli/cli/options"
  39. "github.com/docker/compose-cli/config"
  40. apicontext "github.com/docker/compose-cli/context"
  41. "github.com/docker/compose-cli/context/store"
  42. _ "github.com/docker/compose-cli/ecs"
  43. _ "github.com/docker/compose-cli/ecs/local"
  44. _ "github.com/docker/compose-cli/example"
  45. _ "github.com/docker/compose-cli/local"
  46. "github.com/docker/compose-cli/metrics"
  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. run.Command(),
  105. cmd.ExecCommand(),
  106. cmd.LogsCommand(),
  107. cmd.RmCommand(),
  108. cmd.StartCommand(),
  109. cmd.InspectCommand(),
  110. login.Command(),
  111. logout.Command(),
  112. cmd.VersionCommand(version),
  113. cmd.StopCommand(),
  114. cmd.KillCommand(),
  115. cmd.SecretCommand(),
  116. compose.Command(),
  117. // Place holders
  118. cmd.EcsCommand(),
  119. )
  120. helpFunc := root.HelpFunc()
  121. root.SetHelpFunc(func(cmd *cobra.Command, args []string) {
  122. if !isContextAgnosticCommand(cmd) {
  123. mobycli.ExecIfDefaultCtxType(cmd.Context(), cmd.Root())
  124. }
  125. helpFunc(cmd, args)
  126. })
  127. root.PersistentFlags().BoolVarP(&opts.Debug, "debug", "D", false, "enable debug output in the logs")
  128. root.PersistentFlags().StringVarP(&opts.Host, "host", "H", "", "Daemon socket(s) to connect to")
  129. opts.AddConfigFlags(root.PersistentFlags())
  130. opts.AddContextFlags(root.PersistentFlags())
  131. root.Flags().BoolVarP(&opts.Version, "version", "v", false, "Print version information and quit")
  132. // populate the opts with the global flags
  133. _ = root.PersistentFlags().Parse(os.Args[1:])
  134. if opts.Debug {
  135. logrus.SetLevel(logrus.DebugLevel)
  136. }
  137. ctx, cancel := newSigContext()
  138. defer cancel()
  139. // --host and --version should immediately be forwarded to the original cli
  140. if opts.Host != "" || opts.Version {
  141. mobycli.Exec(root)
  142. }
  143. if opts.Config == "" {
  144. fatal(errors.New("config path cannot be empty"))
  145. }
  146. configDir := opts.Config
  147. ctx = config.WithDir(ctx, configDir)
  148. currentContext := determineCurrentContext(opts.Context, configDir)
  149. s, err := store.New(configDir)
  150. if err != nil {
  151. mobycli.Exec(root)
  152. }
  153. ctype := store.DefaultContextType
  154. cc, _ := s.Get(currentContext)
  155. if cc != nil {
  156. ctype = cc.Type()
  157. }
  158. if ctype == store.AciContextType {
  159. // we can also pass ctype as a parameter to the volume command and customize subcommands, flags, etc. when we have other backend implementations
  160. root.AddCommand(volume.ACICommand())
  161. }
  162. ctx = apicontext.WithCurrentContext(ctx, currentContext)
  163. ctx = store.WithContextStore(ctx, s)
  164. if err = root.ExecuteContext(ctx); err != nil {
  165. // if user canceled request, simply exit without any error message
  166. if errdefs.IsErrCanceled(err) || errors.Is(ctx.Err(), context.Canceled) {
  167. metrics.Track(ctype, os.Args[1:], root.PersistentFlags(), metrics.CanceledStatus)
  168. os.Exit(130)
  169. }
  170. if ctype == store.AwsContextType {
  171. exit(root, currentContext, errors.Errorf(`%q context type has been renamed. Recreate the context by running:
  172. $ docker context create %s <name>`, cc.Type(), store.EcsContextType), ctype)
  173. }
  174. // Context should always be handled by new CLI
  175. requiredCmd, _, _ := root.Find(os.Args[1:])
  176. if requiredCmd != nil && isContextAgnosticCommand(requiredCmd) {
  177. exit(root, currentContext, err, ctype)
  178. }
  179. mobycli.ExecIfDefaultCtxType(ctx, root)
  180. checkIfUnknownCommandExistInDefaultContext(err, currentContext, root)
  181. exit(root, currentContext, err, ctype)
  182. }
  183. metrics.Track(ctype, os.Args[1:], root.PersistentFlags(), metrics.SuccessStatus)
  184. }
  185. func exit(root *cobra.Command, ctx string, err error, ctype string) {
  186. metrics.Track(ctype, os.Args[1:], root.PersistentFlags(), metrics.FailureStatus)
  187. if errors.Is(err, errdefs.ErrLoginRequired) {
  188. fmt.Fprintln(os.Stderr, err)
  189. os.Exit(errdefs.ExitCodeLoginRequired)
  190. }
  191. if errors.Is(err, errdefs.ErrNotImplemented) {
  192. cmd, _, _ := root.Traverse(os.Args[1:])
  193. name := cmd.Name()
  194. parent := cmd.Parent()
  195. if parent != nil && parent.Parent() != nil {
  196. name = parent.Name() + " " + name
  197. }
  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, root *cobra.Command) {
  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(currentContext, os.Args[1:], root.PersistentFlags(), 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. }