main.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. contextcmd "github.com/docker/compose-cli/cli/cmd/context"
  36. "github.com/docker/compose-cli/cli/cmd/login"
  37. "github.com/docker/compose-cli/cli/cmd/logout"
  38. "github.com/docker/compose-cli/cli/cmd/run"
  39. "github.com/docker/compose-cli/cli/cmd/volume"
  40. cliconfig "github.com/docker/compose-cli/cli/config"
  41. "github.com/docker/compose-cli/cli/metrics"
  42. "github.com/docker/compose-cli/cli/mobycli"
  43. cliopts "github.com/docker/compose-cli/cli/options"
  44. compose2 "github.com/docker/compose-cli/cmd/compose"
  45. "github.com/docker/compose-cli/local"
  46. "github.com/docker/compose-cli/pkg/api"
  47. "github.com/docker/compose-cli/pkg/compose"
  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. "context": {},
  57. "login": {},
  58. "logout": {},
  59. "serve": {},
  60. "version": {},
  61. "backend-metadata": {},
  62. }
  63. unknownCommandRegexp = regexp.MustCompile(`unknown docker 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 docker 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 := cliconfig.GetCurrentContext(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. volume.Command(ctype),
  194. )
  195. if ctype != store.DefaultContextType {
  196. // On default context, "compose" is implemented by CLI Plugin
  197. proxy := api.NewServiceProxy().WithService(service.ComposeService())
  198. command := compose2.RootCommand(ctype, proxy)
  199. if ctype == store.AciContextType {
  200. customizeCliForACI(command, proxy)
  201. }
  202. root.AddCommand(command)
  203. }
  204. if err = root.ExecuteContext(ctx); err != nil {
  205. handleError(ctx, err, ctype, currentContext, cc, root)
  206. }
  207. metrics.Track(ctype, os.Args[1:], compose.SuccessStatus)
  208. }
  209. func customizeCliForACI(command *cobra.Command, proxy *api.ServiceProxy) {
  210. var domainName string
  211. for _, c := range command.Commands() {
  212. if c.Name() == "up" {
  213. c.Flags().StringVar(&domainName, "domainname", "", "Container NIS domain name")
  214. proxy.WithInterceptor(func(ctx context.Context, project *types.Project) {
  215. if domainName != "" {
  216. // arbitrarily set the domain name on the first service ; ACI backend will expose the entire project
  217. project.Services[0].DomainName = domainName
  218. }
  219. })
  220. }
  221. }
  222. }
  223. func getBackend(ctype string, configDir string, opts cliopts.GlobalOpts) (backend.Service, error) {
  224. switch ctype {
  225. case store.DefaultContextType, store.LocalContextType:
  226. return local.GetLocalBackend(configDir, opts)
  227. }
  228. service, err := backend.Get(ctype)
  229. if api.IsNotFoundError(err) {
  230. return service, nil
  231. }
  232. return service, err
  233. }
  234. func handleError(ctx context.Context, err error, ctype string, currentContext string, cc *store.DockerContext, root *cobra.Command) {
  235. // if user canceled request, simply exit without any error message
  236. if api.IsErrCanceled(err) || errors.Is(ctx.Err(), context.Canceled) {
  237. metrics.Track(ctype, os.Args[1:], compose.CanceledStatus)
  238. os.Exit(130)
  239. }
  240. if ctype == store.AwsContextType {
  241. exit(currentContext, errors.Errorf(`%q context type has been renamed. Recreate the context by running:
  242. $ docker context create %s <name>`, cc.Type(), store.EcsContextType), ctype)
  243. }
  244. // Context should always be handled by new CLI
  245. requiredCmd, _, _ := root.Find(os.Args[1:])
  246. if requiredCmd != nil && isContextAgnosticCommand(requiredCmd) {
  247. exit(currentContext, err, ctype)
  248. }
  249. mobycli.ExecIfDefaultCtxType(ctx, root)
  250. checkIfUnknownCommandExistInDefaultContext(err, currentContext, ctype)
  251. exit(currentContext, err, ctype)
  252. }
  253. func exit(ctx string, err error, ctype string) {
  254. if exit, ok := err.(cli.StatusError); ok {
  255. metrics.Track(ctype, os.Args[1:], compose.SuccessStatus)
  256. os.Exit(exit.StatusCode)
  257. }
  258. var composeErr compose.Error
  259. metricsStatus := compose.FailureStatus
  260. exitCode := 1
  261. if errors.As(err, &composeErr) {
  262. metricsStatus = composeErr.GetMetricsFailureCategory().MetricsStatus
  263. exitCode = composeErr.GetMetricsFailureCategory().ExitCode
  264. }
  265. if strings.HasPrefix(err.Error(), "unknown shorthand flag:") || strings.HasPrefix(err.Error(), "unknown flag:") || strings.HasPrefix(err.Error(), "unknown docker command:") {
  266. metricsStatus = compose.CommandSyntaxFailure.MetricsStatus
  267. exitCode = compose.CommandSyntaxFailure.ExitCode
  268. }
  269. metrics.Track(ctype, os.Args[1:], metricsStatus)
  270. if errors.Is(err, api.ErrLoginRequired) {
  271. fmt.Fprintln(os.Stderr, err)
  272. os.Exit(api.ExitCodeLoginRequired)
  273. }
  274. if compose2.Warning != "" {
  275. logrus.Warn(err)
  276. fmt.Fprintln(os.Stderr, compose2.Warning)
  277. }
  278. if errors.Is(err, api.ErrNotImplemented) {
  279. name := metrics.GetCommand(os.Args[1:])
  280. fmt.Fprintf(os.Stderr, "Command %q not available in current context (%s)\n", name, ctx)
  281. os.Exit(1)
  282. }
  283. fmt.Fprintln(os.Stderr, err)
  284. os.Exit(exitCode)
  285. }
  286. func fatal(err error) {
  287. fmt.Fprintln(os.Stderr, err)
  288. os.Exit(1)
  289. }
  290. func checkIfUnknownCommandExistInDefaultContext(err error, currentContext string, contextType string) {
  291. submatch := unknownCommandRegexp.FindSubmatch([]byte(err.Error()))
  292. if len(submatch) == 2 {
  293. dockerCommand := string(submatch[1])
  294. if mobycli.IsDefaultContextCommand(dockerCommand) {
  295. 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)
  296. metrics.Track(contextType, os.Args[1:], compose.FailureStatus)
  297. os.Exit(1)
  298. }
  299. }
  300. }
  301. func newSigContext() (context.Context, func()) {
  302. ctx, cancel := context.WithCancel(context.Background())
  303. s := make(chan os.Signal, 1)
  304. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  305. go func() {
  306. <-s
  307. cancel()
  308. }()
  309. return ctx, cancel
  310. }
  311. func walk(c *cobra.Command, f func(*cobra.Command)) {
  312. f(c)
  313. for _, c := range c.Commands() {
  314. walk(c, f)
  315. }
  316. }