main.go 7.8 KB

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