main.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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/docker/cli/cli/command"
  26. cliconfig "github.com/docker/cli/cli/config"
  27. cliflags "github.com/docker/cli/cli/flags"
  28. "github.com/pkg/errors"
  29. "github.com/sirupsen/logrus"
  30. "github.com/spf13/cobra"
  31. "github.com/docker/compose-cli/api/backend"
  32. "github.com/docker/compose-cli/api/config"
  33. apicontext "github.com/docker/compose-cli/api/context"
  34. "github.com/docker/compose-cli/api/context/store"
  35. "github.com/docker/compose-cli/api/errdefs"
  36. "github.com/docker/compose-cli/cli/cmd"
  37. "github.com/docker/compose-cli/cli/cmd/compose"
  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/logout"
  41. "github.com/docker/compose-cli/cli/cmd/run"
  42. "github.com/docker/compose-cli/cli/cmd/volume"
  43. "github.com/docker/compose-cli/cli/metrics"
  44. "github.com/docker/compose-cli/cli/mobycli"
  45. cliopts "github.com/docker/compose-cli/cli/options"
  46. "github.com/docker/compose-cli/local"
  47. // Backend registrations
  48. _ "github.com/docker/compose-cli/aci"
  49. _ "github.com/docker/compose-cli/ecs"
  50. _ "github.com/docker/compose-cli/ecs/local"
  51. _ "github.com/docker/compose-cli/local"
  52. )
  53. var (
  54. contextAgnosticCommands = map[string]struct{}{
  55. "compose": {},
  56. "context": {},
  57. "login": {},
  58. "logout": {},
  59. "serve": {},
  60. "version": {},
  61. "backend-metadata": {},
  62. }
  63. unknownCommandRegexp = regexp.MustCompile(`unknown command "([^"]*)"`)
  64. )
  65. func init() {
  66. // initial hack to get the path of the project's bin dir
  67. // into the env of this cli for development
  68. path, err := filepath.Abs(filepath.Dir(os.Args[0]))
  69. if err != nil {
  70. fatal(errors.Wrap(err, "unable to get absolute bin path"))
  71. }
  72. if err := os.Setenv("PATH", appendPaths(os.Getenv("PATH"), path)); err != nil {
  73. panic(err)
  74. }
  75. // Seed random
  76. rand.Seed(time.Now().UnixNano())
  77. }
  78. func appendPaths(envPath string, path string) string {
  79. if envPath == "" {
  80. return path
  81. }
  82. return strings.Join([]string{envPath, path}, string(os.PathListSeparator))
  83. }
  84. func isContextAgnosticCommand(cmd *cobra.Command) bool {
  85. if cmd == nil {
  86. return false
  87. }
  88. if _, ok := contextAgnosticCommands[cmd.Name()]; ok {
  89. return true
  90. }
  91. return isContextAgnosticCommand(cmd.Parent())
  92. }
  93. func main() {
  94. var opts cliopts.GlobalOpts
  95. root := &cobra.Command{
  96. Use: "docker",
  97. SilenceErrors: true,
  98. SilenceUsage: true,
  99. TraverseChildren: true,
  100. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  101. if !isContextAgnosticCommand(cmd) {
  102. mobycli.ExecIfDefaultCtxType(cmd.Context(), cmd.Root())
  103. }
  104. return nil
  105. },
  106. RunE: func(cmd *cobra.Command, args []string) error {
  107. if len(args) == 0 {
  108. return cmd.Help()
  109. }
  110. return fmt.Errorf("unknown command %q", args[0])
  111. },
  112. }
  113. root.AddCommand(
  114. contextcmd.Command(),
  115. cmd.PsCommand(),
  116. cmd.ServeCommand(),
  117. cmd.ExecCommand(),
  118. cmd.LogsCommand(),
  119. cmd.RmCommand(),
  120. cmd.StartCommand(),
  121. cmd.InspectCommand(),
  122. login.Command(),
  123. logout.Command(),
  124. cmd.VersionCommand(),
  125. cmd.StopCommand(),
  126. cmd.KillCommand(),
  127. cmd.SecretCommand(),
  128. cmd.PruneCommand(),
  129. cmd.MetadataCommand(),
  130. // Place holders
  131. cmd.EcsCommand(),
  132. )
  133. helpFunc := root.HelpFunc()
  134. root.SetHelpFunc(func(cmd *cobra.Command, args []string) {
  135. if !isContextAgnosticCommand(cmd) {
  136. mobycli.ExecIfDefaultCtxType(cmd.Context(), cmd.Root())
  137. }
  138. helpFunc(cmd, args)
  139. })
  140. flags := root.Flags()
  141. opts.InstallFlags(flags)
  142. opts.AddConfigFlags(flags)
  143. flags.BoolVarP(&opts.Version, "version", "v", false, "Print version information and quit")
  144. flags.SetInterspersed(false)
  145. walk(root, func(c *cobra.Command) {
  146. c.Flags().BoolP("help", "h", false, "Help for "+c.Name())
  147. })
  148. // populate the opts with the global flags
  149. flags.Parse(os.Args[1:]) //nolint: errcheck
  150. level, err := logrus.ParseLevel(opts.LogLevel)
  151. if err != nil {
  152. fmt.Fprintf(os.Stderr, "Unable to parse logging level: %s\n", opts.LogLevel)
  153. os.Exit(1)
  154. }
  155. logrus.SetFormatter(&logrus.TextFormatter{
  156. DisableTimestamp: true,
  157. DisableLevelTruncation: true,
  158. })
  159. logrus.SetLevel(level)
  160. if opts.Debug {
  161. logrus.SetLevel(logrus.DebugLevel)
  162. }
  163. ctx, cancel := newSigContext()
  164. defer cancel()
  165. // --version should immediately be forwarded to the original cli
  166. if opts.Version {
  167. mobycli.Exec(root)
  168. }
  169. if opts.Config == "" {
  170. fatal(errors.New("config path cannot be empty"))
  171. }
  172. configDir := opts.Config
  173. config.WithDir(configDir)
  174. currentContext := determineCurrentContext(opts.Context, configDir, opts.Hosts)
  175. apicontext.WithCurrentContext(currentContext)
  176. s, err := store.New(configDir)
  177. if err != nil {
  178. mobycli.Exec(root)
  179. }
  180. store.WithContextStore(s)
  181. ctype := store.DefaultContextType
  182. cc, _ := s.Get(currentContext)
  183. if cc != nil {
  184. ctype = cc.Type()
  185. }
  186. service, err := getBackend(ctype, configDir, opts)
  187. if err != nil {
  188. fatal(err)
  189. }
  190. backend.WithBackend(service)
  191. root.AddCommand(
  192. run.Command(ctype),
  193. compose.Command(ctype),
  194. volume.Command(ctype),
  195. )
  196. if err = root.ExecuteContext(ctx); err != nil {
  197. handleError(ctx, err, ctype, currentContext, cc, root)
  198. }
  199. metrics.Track(ctype, os.Args[1:], metrics.SuccessStatus)
  200. }
  201. func getBackend(ctype string, configDir string, opts cliopts.GlobalOpts) (backend.Service, error) {
  202. switch ctype {
  203. case store.DefaultContextType, store.LocalContextType:
  204. configFile, err := cliconfig.Load(configDir)
  205. if err != nil {
  206. return nil, err
  207. }
  208. options := cliflags.CommonOptions{
  209. Context: opts.Context,
  210. Debug: opts.Debug,
  211. Hosts: opts.Hosts,
  212. LogLevel: opts.LogLevel,
  213. }
  214. if opts.TLSVerify {
  215. options.TLS = opts.TLS
  216. options.TLSVerify = opts.TLSVerify
  217. options.TLSOptions = opts.TLSOptions
  218. }
  219. apiClient, err := command.NewAPIClientFromFlags(&options, configFile)
  220. if err != nil {
  221. return nil, err
  222. }
  223. return local.NewService(apiClient), nil
  224. }
  225. service, err := backend.Get(ctype)
  226. if errdefs.IsNotFoundError(err) {
  227. return service, nil
  228. }
  229. return service, err
  230. }
  231. func handleError(ctx context.Context, err error, ctype string, currentContext string, cc *store.DockerContext, root *cobra.Command) {
  232. // if user canceled request, simply exit without any error message
  233. if errdefs.IsErrCanceled(err) || errors.Is(ctx.Err(), context.Canceled) {
  234. metrics.Track(ctype, os.Args[1:], metrics.CanceledStatus)
  235. os.Exit(130)
  236. }
  237. if ctype == store.AwsContextType {
  238. exit(currentContext, errors.Errorf(`%q context type has been renamed. Recreate the context by running:
  239. $ docker context create %s <name>`, cc.Type(), store.EcsContextType), ctype)
  240. }
  241. // Context should always be handled by new CLI
  242. requiredCmd, _, _ := root.Find(os.Args[1:])
  243. if requiredCmd != nil && isContextAgnosticCommand(requiredCmd) {
  244. exit(currentContext, err, ctype)
  245. }
  246. mobycli.ExecIfDefaultCtxType(ctx, root)
  247. checkIfUnknownCommandExistInDefaultContext(err, currentContext, ctype)
  248. exit(currentContext, err, ctype)
  249. }
  250. func exit(ctx string, err error, ctype string) {
  251. if exit, ok := err.(cmd.ExitCodeError); ok {
  252. metrics.Track(ctype, os.Args[1:], metrics.SuccessStatus)
  253. os.Exit(exit.ExitCode)
  254. }
  255. metrics.Track(ctype, os.Args[1:], metrics.FailureStatus)
  256. if errors.Is(err, errdefs.ErrLoginRequired) {
  257. fmt.Fprintln(os.Stderr, err)
  258. os.Exit(errdefs.ExitCodeLoginRequired)
  259. }
  260. if compose.Warning != "" {
  261. fmt.Fprintln(os.Stderr, compose.Warning)
  262. }
  263. if errors.Is(err, errdefs.ErrNotImplemented) {
  264. name := metrics.GetCommand(os.Args[1:])
  265. fmt.Fprintf(os.Stderr, "Command %q not available in current context (%s)\n", name, ctx)
  266. os.Exit(1)
  267. }
  268. fatal(err)
  269. }
  270. func fatal(err error) {
  271. fmt.Fprintln(os.Stderr, err)
  272. os.Exit(1)
  273. }
  274. func checkIfUnknownCommandExistInDefaultContext(err error, currentContext string, contextType string) {
  275. submatch := unknownCommandRegexp.FindSubmatch([]byte(err.Error()))
  276. if len(submatch) == 2 {
  277. dockerCommand := string(submatch[1])
  278. if mobycli.IsDefaultContextCommand(dockerCommand) {
  279. 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)
  280. metrics.Track(contextType, os.Args[1:], metrics.FailureStatus)
  281. os.Exit(1)
  282. }
  283. }
  284. }
  285. func newSigContext() (context.Context, func()) {
  286. ctx, cancel := context.WithCancel(context.Background())
  287. s := make(chan os.Signal, 1)
  288. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  289. go func() {
  290. <-s
  291. cancel()
  292. }()
  293. return ctx, cancel
  294. }
  295. func determineCurrentContext(flag string, configDir string, hosts []string) string {
  296. // host and context flags cannot be both set at the same time -- the local backend enforces this when resolving hostname
  297. // -H flag disables context --> set default as current
  298. if len(hosts) > 0 {
  299. return "default"
  300. }
  301. // DOCKER_HOST disables context --> set default as current
  302. if _, present := os.LookupEnv("DOCKER_HOST"); present {
  303. return "default"
  304. }
  305. res := flag
  306. if res == "" {
  307. // check if DOCKER_CONTEXT env variable was set
  308. if _, present := os.LookupEnv("DOCKER_CONTEXT"); present {
  309. res = os.Getenv("DOCKER_CONTEXT")
  310. }
  311. if res == "" {
  312. config, err := config.LoadFile(configDir)
  313. if err != nil {
  314. fmt.Fprintln(os.Stderr, errors.Wrap(err, "WARNING"))
  315. return "default"
  316. }
  317. res = config.CurrentContext
  318. }
  319. }
  320. if res == "" {
  321. res = "default"
  322. }
  323. return res
  324. }
  325. func walk(c *cobra.Command, f func(*cobra.Command)) {
  326. f(c)
  327. for _, c := range c.Commands() {
  328. walk(c, f)
  329. }
  330. }