exec.go 4.1 KB

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