exec.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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. "path/filepath"
  21. "regexp"
  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/spf13/cobra"
  27. "github.com/docker/compose-cli/pkg/compose"
  28. "github.com/docker/compose-cli/pkg/utils"
  29. )
  30. var delegatedContextTypes = []string{store.DefaultContextType}
  31. // ComDockerCli name of the classic cli binary
  32. const ComDockerCli = "com.docker.cli"
  33. // ExecIfDefaultCtxType delegates to com.docker.cli if on moby context
  34. func ExecIfDefaultCtxType(ctx context.Context, root *cobra.Command) {
  35. currentContext := apicontext.Current()
  36. s := store.Instance()
  37. currentCtx, err := s.Get(currentContext)
  38. // Only run original docker command if the current context is not ours.
  39. if err != nil || mustDelegateToMoby(currentCtx.Type()) {
  40. Exec(root)
  41. }
  42. }
  43. func mustDelegateToMoby(ctxType string) bool {
  44. for _, ctype := range delegatedContextTypes {
  45. if ctxType == ctype {
  46. return true
  47. }
  48. }
  49. return false
  50. }
  51. // Exec delegates to com.docker.cli if on moby context
  52. func Exec(root *cobra.Command) {
  53. childExit := make(chan bool)
  54. err := RunDocker(childExit, os.Args[1:]...)
  55. childExit <- true
  56. if err != nil {
  57. if exiterr, ok := err.(*exec.ExitError); ok {
  58. exitCode := exiterr.ExitCode()
  59. metrics.Track(store.DefaultContextType, os.Args[1:], compose.ByExitCode(exitCode).MetricsStatus)
  60. os.Exit(exitCode)
  61. }
  62. metrics.Track(store.DefaultContextType, os.Args[1:], compose.FailureStatus)
  63. fmt.Fprintln(os.Stderr, err)
  64. os.Exit(1)
  65. }
  66. commandArgs := os.Args[1:]
  67. command := metrics.GetCommand(commandArgs)
  68. if command == "build" && !metrics.HasQuietFlag(commandArgs) {
  69. utils.DisplayScanSuggestMsg()
  70. }
  71. if command == "login" && !metrics.HasQuietFlag(commandArgs) {
  72. displayPATSuggestMsg(commandArgs)
  73. }
  74. metrics.Track(store.DefaultContextType, os.Args[1:], compose.SuccessStatus)
  75. os.Exit(0)
  76. }
  77. // RunDocker runs a docker command, and forward signals to the shellout command (stops listening to signals when an event is sent to childExit)
  78. func RunDocker(childExit chan bool, args ...string) error {
  79. execBinary, err := resolvepath.LookPath(ComDockerCli)
  80. if err != nil {
  81. execBinary = findBinary(ComDockerCli)
  82. if execBinary == "" {
  83. fmt.Fprintln(os.Stderr, err)
  84. fmt.Fprintln(os.Stderr, "Current PATH : "+os.Getenv("PATH"))
  85. os.Exit(1)
  86. }
  87. }
  88. cmd := exec.Command(execBinary, args...)
  89. cmd.Stdin = os.Stdin
  90. cmd.Stdout = os.Stdout
  91. cmd.Stderr = os.Stderr
  92. signals := make(chan os.Signal, 1)
  93. signal.Notify(signals) // catch all signals
  94. go func() {
  95. for {
  96. select {
  97. case sig := <-signals:
  98. if cmd.Process == nil {
  99. continue // can happen if receiving signal before the process is actually started
  100. }
  101. // In go1.14+, the go runtime issues SIGURG as an interrupt to
  102. // support preemptable system calls on Linux. Since we can't
  103. // forward that along we'll check that here.
  104. if isRuntimeSig(sig) {
  105. continue
  106. }
  107. _ = cmd.Process.Signal(sig)
  108. case <-childExit:
  109. return
  110. }
  111. }
  112. }()
  113. return cmd.Run()
  114. }
  115. func findBinary(filename string) string {
  116. currentBinaryPath, err := os.Executable()
  117. if err != nil {
  118. return ""
  119. }
  120. currentBinaryPath, err = filepath.EvalSymlinks(currentBinaryPath)
  121. if err != nil {
  122. return ""
  123. }
  124. binaryPath := filepath.Join(filepath.Dir(currentBinaryPath), filename)
  125. if _, err := os.Stat(binaryPath); err != nil {
  126. return ""
  127. }
  128. return binaryPath
  129. }
  130. // IsDefaultContextCommand checks if the command exists in the classic cli (issues a shellout --help)
  131. func IsDefaultContextCommand(dockerCommand string) bool {
  132. cmd := exec.Command(ComDockerCli, dockerCommand, "--help")
  133. b, e := cmd.CombinedOutput()
  134. if e != nil {
  135. fmt.Println(e)
  136. }
  137. return regexp.MustCompile("Usage:\\s*docker\\s*" + dockerCommand).Match(b)
  138. }
  139. // ExecSilent executes a command and do redirect output to stdOut, return output
  140. func ExecSilent(ctx context.Context, args ...string) ([]byte, error) {
  141. if len(args) == 0 {
  142. args = os.Args[1:]
  143. }
  144. cmd := exec.CommandContext(ctx, ComDockerCli, args...)
  145. cmd.Stderr = os.Stderr
  146. return cmd.Output()
  147. }