main.go 10 KB

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