exec.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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 mobycli
  14. import (
  15. "context"
  16. "fmt"
  17. "os"
  18. "os/exec"
  19. "os/signal"
  20. "regexp"
  21. "github.com/spf13/cobra"
  22. apicontext "github.com/docker/compose-cli/api/context"
  23. "github.com/docker/compose-cli/api/context/store"
  24. "github.com/docker/compose-cli/cli/metrics"
  25. "github.com/docker/compose-cli/cli/mobycli/resolvepath"
  26. "github.com/docker/compose-cli/utils"
  27. )
  28. var delegatedContextTypes = []string{store.DefaultContextType}
  29. // ComDockerCli name of the classic cli binary
  30. const ComDockerCli = "com.docker.cli"
  31. // ExecIfDefaultCtxType delegates to com.docker.cli if on moby context
  32. func ExecIfDefaultCtxType(ctx context.Context, root *cobra.Command) {
  33. currentContext := apicontext.Current()
  34. s := store.Instance()
  35. currentCtx, err := s.Get(currentContext)
  36. // Only run original docker command if the current context is not ours.
  37. if err != nil || mustDelegateToMoby(currentCtx.Type()) {
  38. Exec(root)
  39. }
  40. }
  41. func mustDelegateToMoby(ctxType string) bool {
  42. for _, ctype := range delegatedContextTypes {
  43. if ctxType == ctype {
  44. return true
  45. }
  46. }
  47. return false
  48. }
  49. // Exec delegates to com.docker.cli if on moby context
  50. func Exec(root *cobra.Command) {
  51. childExit := make(chan bool)
  52. err := RunDocker(childExit, os.Args[1:]...)
  53. childExit <- true
  54. if err != nil {
  55. if exiterr, ok := err.(*exec.ExitError); ok {
  56. exitCode := exiterr.ExitCode()
  57. if exitCode == 130 {
  58. metrics.Track(store.DefaultContextType, os.Args[1:], metrics.CanceledStatus)
  59. } else {
  60. metrics.Track(store.DefaultContextType, os.Args[1:], metrics.FailureStatus)
  61. }
  62. os.Exit(exiterr.ExitCode())
  63. }
  64. metrics.Track(store.DefaultContextType, os.Args[1:], metrics.FailureStatus)
  65. fmt.Fprintln(os.Stderr, err)
  66. os.Exit(1)
  67. }
  68. command := metrics.GetCommand(os.Args[1:])
  69. if command == "build" && !metrics.HasQuietFlag(os.Args[1:]) {
  70. utils.DisplayScanSuggestMsg()
  71. }
  72. metrics.Track(store.DefaultContextType, os.Args[1:], metrics.SuccessStatus)
  73. os.Exit(0)
  74. }
  75. // RunDocker runs a docker command, and forward signals to the shellout command (stops listening to signals when an event is sent to childExit)
  76. func RunDocker(childExit chan bool, args ...string) error {
  77. execBinary, err := resolvepath.LookPath(ComDockerCli)
  78. if err != nil {
  79. fmt.Fprintln(os.Stderr, err)
  80. os.Exit(1)
  81. }
  82. cmd := exec.Command(execBinary, args...)
  83. cmd.Stdin = os.Stdin
  84. cmd.Stdout = os.Stdout
  85. cmd.Stderr = os.Stderr
  86. signals := make(chan os.Signal, 1)
  87. signal.Notify(signals) // catch all signals
  88. go func() {
  89. for {
  90. select {
  91. case sig := <-signals:
  92. if cmd.Process == nil {
  93. continue // can happen if receiving signal before the process is actually started
  94. }
  95. // nolint errcheck
  96. cmd.Process.Signal(sig)
  97. case <-childExit:
  98. return
  99. }
  100. }
  101. }()
  102. return cmd.Run()
  103. }
  104. // IsDefaultContextCommand checks if the command exists in the classic cli (issues a shellout --help)
  105. func IsDefaultContextCommand(dockerCommand string) bool {
  106. cmd := exec.Command(ComDockerCli, dockerCommand, "--help")
  107. b, e := cmd.CombinedOutput()
  108. if e != nil {
  109. fmt.Println(e)
  110. }
  111. return regexp.MustCompile("Usage:\\s*docker\\s*" + dockerCommand).Match(b)
  112. }
  113. // ExecSilent executes a command and do redirect output to stdOut, return output
  114. func ExecSilent(ctx context.Context, args ...string) ([]byte, error) {
  115. if len(args) == 0 {
  116. args = os.Args[1:]
  117. }
  118. cmd := exec.CommandContext(ctx, ComDockerCli, args...)
  119. cmd.Stderr = os.Stderr
  120. return cmd.Output()
  121. }