main.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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/docker/compose-cli/cli/cmd/compose"
  25. "github.com/docker/compose-cli/cli/cmd/logout"
  26. "github.com/docker/compose-cli/errdefs"
  27. "github.com/pkg/errors"
  28. "github.com/sirupsen/logrus"
  29. "github.com/spf13/cobra"
  30. // Backend registrations
  31. _ "github.com/docker/compose-cli/aci"
  32. _ "github.com/docker/compose-cli/ecs"
  33. _ "github.com/docker/compose-cli/ecs/local"
  34. _ "github.com/docker/compose-cli/example"
  35. _ "github.com/docker/compose-cli/local"
  36. "github.com/docker/compose-cli/metrics"
  37. "github.com/docker/compose-cli/cli/cmd"
  38. contextcmd "github.com/docker/compose-cli/cli/cmd/context"
  39. "github.com/docker/compose-cli/cli/cmd/login"
  40. "github.com/docker/compose-cli/cli/cmd/run"
  41. "github.com/docker/compose-cli/cli/mobycli"
  42. cliopts "github.com/docker/compose-cli/cli/options"
  43. "github.com/docker/compose-cli/config"
  44. apicontext "github.com/docker/compose-cli/context"
  45. "github.com/docker/compose-cli/context/store"
  46. )
  47. var (
  48. version = "dev"
  49. )
  50. var (
  51. ownCommands = map[string]struct{}{
  52. "compose": {},
  53. "context": {},
  54. "login": {},
  55. "logout": {},
  56. "serve": {},
  57. "version": {},
  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", fmt.Sprintf("%s:%s", os.Getenv("PATH"), path)); err != nil {
  69. panic(err)
  70. }
  71. // Seed random
  72. rand.Seed(time.Now().UnixNano())
  73. }
  74. func isOwnCommand(cmd *cobra.Command) bool {
  75. if cmd == nil {
  76. return false
  77. }
  78. if _, ok := ownCommands[cmd.Name()]; ok {
  79. return true
  80. }
  81. return isOwnCommand(cmd.Parent())
  82. }
  83. func main() {
  84. var opts cliopts.GlobalOpts
  85. root := &cobra.Command{
  86. Use: "docker",
  87. SilenceErrors: true,
  88. SilenceUsage: true,
  89. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  90. if !isOwnCommand(cmd) {
  91. mobycli.ExecIfDefaultCtxType(cmd.Context())
  92. }
  93. return nil
  94. },
  95. RunE: func(cmd *cobra.Command, args []string) error {
  96. return cmd.Help()
  97. },
  98. }
  99. root.AddCommand(
  100. contextcmd.Command(),
  101. cmd.PsCommand(),
  102. cmd.ServeCommand(),
  103. run.Command(),
  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.SecretCommand(),
  114. compose.Command(),
  115. // Place holders
  116. cmd.EcsCommand(),
  117. )
  118. helpFunc := root.HelpFunc()
  119. root.SetHelpFunc(func(cmd *cobra.Command, args []string) {
  120. if !isOwnCommand(cmd) {
  121. mobycli.ExecIfDefaultCtxType(cmd.Context())
  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. // populate the opts with the global flags
  131. _ = root.PersistentFlags().Parse(os.Args[1:])
  132. if opts.Debug {
  133. logrus.SetLevel(logrus.DebugLevel)
  134. }
  135. ctx, cancel := newSigContext()
  136. defer cancel()
  137. // --host and --version should immediately be forwarded to the original cli
  138. if opts.Host != "" || opts.Version {
  139. mobycli.Exec()
  140. }
  141. if opts.Config == "" {
  142. fatal(errors.New("config path cannot be empty"))
  143. }
  144. configDir := opts.Config
  145. ctx = config.WithDir(ctx, configDir)
  146. currentContext := determineCurrentContext(opts.Context, configDir)
  147. s, err := store.New(store.WithRoot(configDir))
  148. if err != nil {
  149. fatal(errors.Wrap(err, "unable to create context store"))
  150. }
  151. ctype := store.DefaultContextType
  152. cc, _ := s.Get(currentContext)
  153. if cc != nil {
  154. ctype = cc.Type()
  155. }
  156. if ctype == store.AwsContextType {
  157. exit(root, currentContext, errors.Errorf(`%q context type has been renamed. Recreate the context by running:
  158. $ docker context create %s <name>`, cc.Type(), store.EcsContextType))
  159. }
  160. metrics.Track(ctype, os.Args[1:], root.PersistentFlags())
  161. ctx = apicontext.WithCurrentContext(ctx, currentContext)
  162. ctx = store.WithContextStore(ctx, s)
  163. if err = root.ExecuteContext(ctx); err != nil {
  164. // if user canceled request, simply exit without any error message
  165. if errors.Is(ctx.Err(), context.Canceled) {
  166. os.Exit(130)
  167. }
  168. // Context should always be handled by new CLI
  169. requiredCmd, _, _ := root.Find(os.Args[1:])
  170. if requiredCmd != nil && isOwnCommand(requiredCmd) {
  171. exit(root, currentContext, err)
  172. }
  173. mobycli.ExecIfDefaultCtxType(ctx)
  174. checkIfUnknownCommandExistInDefaultContext(err, currentContext)
  175. exit(root, currentContext, err)
  176. }
  177. }
  178. func exit(cmd *cobra.Command, ctx string, err error) {
  179. if errors.Is(err, errdefs.ErrLoginRequired) {
  180. fmt.Fprintln(os.Stderr, err)
  181. os.Exit(errdefs.ExitCodeLoginRequired)
  182. }
  183. if errors.Is(err, errdefs.ErrNotImplemented) {
  184. cmd, _, _ := cmd.Traverse(os.Args[1:])
  185. name := cmd.Name()
  186. parent := cmd.Parent()
  187. if parent != nil && parent.Parent() != nil {
  188. name = parent.Name() + " " + name
  189. }
  190. fmt.Fprintf(os.Stderr, "Command %q not available in current context (%s)\n", name, ctx)
  191. os.Exit(1)
  192. }
  193. fatal(err)
  194. }
  195. func fatal(err error) {
  196. fmt.Fprintln(os.Stderr, err)
  197. os.Exit(1)
  198. }
  199. func checkIfUnknownCommandExistInDefaultContext(err error, currentContext string) {
  200. submatch := unknownCommandRegexp.FindSubmatch([]byte(err.Error()))
  201. if len(submatch) == 2 {
  202. dockerCommand := string(submatch[1])
  203. if mobycli.IsDefaultContextCommand(dockerCommand) {
  204. 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)
  205. os.Exit(1)
  206. }
  207. }
  208. }
  209. func newSigContext() (context.Context, func()) {
  210. ctx, cancel := context.WithCancel(context.Background())
  211. s := make(chan os.Signal, 1)
  212. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  213. go func() {
  214. <-s
  215. cancel()
  216. }()
  217. return ctx, cancel
  218. }
  219. func determineCurrentContext(flag string, configDir string) string {
  220. res := flag
  221. if res == "" {
  222. config, err := config.LoadFile(configDir)
  223. if err != nil {
  224. fmt.Fprintln(os.Stderr, errors.Wrap(err, "WARNING"))
  225. return "default"
  226. }
  227. res = config.CurrentContext
  228. }
  229. if res == "" {
  230. res = "default"
  231. }
  232. return res
  233. }