main.go 11 KB

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