main.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. cliflags "github.com/docker/cli/cli/flags"
  43. // Backend registrations
  44. _ "github.com/docker/compose-cli/aci"
  45. _ "github.com/docker/compose-cli/ecs"
  46. _ "github.com/docker/compose-cli/ecs/local"
  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. TraverseChildren: true,
  96. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  97. if !isContextAgnosticCommand(cmd) {
  98. mobycli.ExecIfDefaultCtxType(cmd.Context(), cmd.Root())
  99. }
  100. return nil
  101. },
  102. RunE: func(cmd *cobra.Command, args []string) error {
  103. if len(args) == 0 {
  104. return cmd.Help()
  105. }
  106. return fmt.Errorf("unknown command %q", args[0])
  107. },
  108. }
  109. root.AddCommand(
  110. contextcmd.Command(),
  111. cmd.PsCommand(),
  112. cmd.ServeCommand(),
  113. cmd.ExecCommand(),
  114. cmd.LogsCommand(),
  115. cmd.RmCommand(),
  116. cmd.StartCommand(),
  117. cmd.InspectCommand(),
  118. login.Command(),
  119. logout.Command(),
  120. cmd.VersionCommand(),
  121. cmd.StopCommand(),
  122. cmd.KillCommand(),
  123. cmd.SecretCommand(),
  124. cmd.PruneCommand(),
  125. cmd.MetadataCommand(),
  126. // Place holders
  127. cmd.EcsCommand(),
  128. )
  129. helpFunc := root.HelpFunc()
  130. root.SetHelpFunc(func(cmd *cobra.Command, args []string) {
  131. if !isContextAgnosticCommand(cmd) {
  132. mobycli.ExecIfDefaultCtxType(cmd.Context(), cmd.Root())
  133. }
  134. helpFunc(cmd, args)
  135. })
  136. flags := root.Flags()
  137. opts.InstallFlags(flags)
  138. opts.AddConfigFlags(flags)
  139. flags.BoolVarP(&opts.Version, "version", "v", false, "Print version information and quit")
  140. flags.SetInterspersed(false)
  141. walk(root, func(c *cobra.Command) {
  142. c.Flags().BoolP("help", "h", false, "Help for "+c.Name())
  143. })
  144. // populate the opts with the global flags
  145. flags.Parse(os.Args[1:]) //nolint: errcheck
  146. level, err := logrus.ParseLevel(opts.LogLevel)
  147. if err != nil {
  148. fmt.Fprintf(os.Stderr, "Unable to parse logging level: %s\n", opts.LogLevel)
  149. os.Exit(1)
  150. }
  151. logrus.SetFormatter(&logrus.TextFormatter{
  152. DisableTimestamp: true,
  153. DisableLevelTruncation: true,
  154. })
  155. logrus.SetLevel(level)
  156. if opts.Debug {
  157. logrus.SetLevel(logrus.DebugLevel)
  158. }
  159. ctx, cancel := newSigContext()
  160. defer cancel()
  161. // --version should immediately be forwarded to the original cli
  162. if opts.Version {
  163. mobycli.Exec(root)
  164. }
  165. if opts.Config == "" {
  166. fatal(errors.New("config path cannot be empty"))
  167. }
  168. configDir := opts.Config
  169. ctx = config.WithDir(ctx, configDir)
  170. currentContext := determineCurrentContext(opts.Context, configDir)
  171. s, err := store.New(configDir)
  172. if err != nil {
  173. mobycli.Exec(root)
  174. }
  175. ctype := store.DefaultContextType
  176. cc, _ := s.Get(currentContext)
  177. if cc != nil {
  178. ctype = cc.Type()
  179. }
  180. root.AddCommand(
  181. run.Command(ctype),
  182. compose.Command(ctype),
  183. volume.Command(ctype),
  184. )
  185. if ctype == store.DefaultContextType || ctype == store.LocalContextType {
  186. if len(opts.Hosts) > 0 {
  187. opts.Context = ""
  188. currentContext = "default"
  189. }
  190. cnxOptions := cliflags.CommonOptions{
  191. Context: opts.Context,
  192. Debug: opts.Debug,
  193. Hosts: opts.Hosts,
  194. LogLevel: opts.LogLevel,
  195. TLS: opts.TLS,
  196. TLSVerify: opts.TLSVerify,
  197. }
  198. if opts.TLSVerify {
  199. cnxOptions.TLSOptions = opts.TLSOptions
  200. }
  201. ctx = apicontext.WithCliOptions(ctx, cnxOptions)
  202. }
  203. ctx = apicontext.WithCurrentContext(ctx, currentContext)
  204. ctx = store.WithContextStore(ctx, s)
  205. if err = root.ExecuteContext(ctx); err != nil {
  206. handleError(ctx, err, ctype, currentContext, cc, root)
  207. }
  208. metrics.Track(ctype, os.Args[1:], metrics.SuccessStatus)
  209. }
  210. func handleError(ctx context.Context, err error, ctype string, currentContext string, cc *store.DockerContext, root *cobra.Command) {
  211. // if user canceled request, simply exit without any error message
  212. if errdefs.IsErrCanceled(err) || errors.Is(ctx.Err(), context.Canceled) {
  213. metrics.Track(ctype, os.Args[1:], metrics.CanceledStatus)
  214. os.Exit(130)
  215. }
  216. if ctype == store.AwsContextType {
  217. exit(currentContext, errors.Errorf(`%q context type has been renamed. Recreate the context by running:
  218. $ docker context create %s <name>`, cc.Type(), store.EcsContextType), ctype)
  219. }
  220. // Context should always be handled by new CLI
  221. requiredCmd, _, _ := root.Find(os.Args[1:])
  222. if requiredCmd != nil && isContextAgnosticCommand(requiredCmd) {
  223. exit(currentContext, err, ctype)
  224. }
  225. mobycli.ExecIfDefaultCtxType(ctx, root)
  226. checkIfUnknownCommandExistInDefaultContext(err, currentContext, ctype)
  227. exit(currentContext, err, ctype)
  228. }
  229. func exit(ctx string, err error, ctype string) {
  230. if exit, ok := err.(cmd.ExitCodeError); ok {
  231. metrics.Track(ctype, os.Args[1:], metrics.SuccessStatus)
  232. os.Exit(exit.ExitCode)
  233. }
  234. metrics.Track(ctype, os.Args[1:], metrics.FailureStatus)
  235. if errors.Is(err, errdefs.ErrLoginRequired) {
  236. fmt.Fprintln(os.Stderr, err)
  237. os.Exit(errdefs.ExitCodeLoginRequired)
  238. }
  239. if compose.Warning != "" {
  240. fmt.Fprintln(os.Stderr, compose.Warning)
  241. }
  242. if errors.Is(err, errdefs.ErrNotImplemented) {
  243. name := metrics.GetCommand(os.Args[1:])
  244. fmt.Fprintf(os.Stderr, "Command %q not available in current context (%s)\n", name, ctx)
  245. os.Exit(1)
  246. }
  247. fatal(err)
  248. }
  249. func fatal(err error) {
  250. fmt.Fprintln(os.Stderr, err)
  251. os.Exit(1)
  252. }
  253. func checkIfUnknownCommandExistInDefaultContext(err error, currentContext string, contextType string) {
  254. submatch := unknownCommandRegexp.FindSubmatch([]byte(err.Error()))
  255. if len(submatch) == 2 {
  256. dockerCommand := string(submatch[1])
  257. if mobycli.IsDefaultContextCommand(dockerCommand) {
  258. 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)
  259. metrics.Track(contextType, os.Args[1:], metrics.FailureStatus)
  260. os.Exit(1)
  261. }
  262. }
  263. }
  264. func newSigContext() (context.Context, func()) {
  265. ctx, cancel := context.WithCancel(context.Background())
  266. s := make(chan os.Signal, 1)
  267. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  268. go func() {
  269. <-s
  270. cancel()
  271. }()
  272. return ctx, cancel
  273. }
  274. func determineCurrentContext(flag string, configDir string) string {
  275. res := flag
  276. if res == "" {
  277. config, err := config.LoadFile(configDir)
  278. if err != nil {
  279. fmt.Fprintln(os.Stderr, errors.Wrap(err, "WARNING"))
  280. return "default"
  281. }
  282. res = config.CurrentContext
  283. }
  284. if res == "" {
  285. res = "default"
  286. }
  287. return res
  288. }
  289. func walk(c *cobra.Command, f func(*cobra.Command)) {
  290. f(c)
  291. for _, c := range c.Commands() {
  292. walk(c, f)
  293. }
  294. }