main.go 10.0 KB

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