plugins.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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 compose
  14. import (
  15. "context"
  16. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "io"
  20. "os"
  21. "os/exec"
  22. "strings"
  23. "github.com/compose-spec/compose-go/v2/types"
  24. "github.com/docker/cli/cli-plugins/manager"
  25. "github.com/docker/cli/cli-plugins/socket"
  26. "github.com/docker/compose/v2/pkg/progress"
  27. "github.com/spf13/cobra"
  28. "go.opentelemetry.io/otel"
  29. "go.opentelemetry.io/otel/propagation"
  30. "golang.org/x/sync/errgroup"
  31. )
  32. type JsonMessage struct {
  33. Type string `json:"type"`
  34. Message string `json:"message"`
  35. }
  36. const (
  37. ErrorType = "error"
  38. InfoType = "info"
  39. SetEnvType = "setenv"
  40. )
  41. func (s *composeService) runPlugin(ctx context.Context, project *types.Project, service types.ServiceConfig, command string) error {
  42. provider := *service.Provider
  43. plugin, err := s.getPluginBinaryPath(provider.Type)
  44. if err != nil {
  45. return err
  46. }
  47. cmd := s.setupPluginCommand(ctx, project, service, plugin, command)
  48. variables, err := s.executePlugin(ctx, cmd, command, service)
  49. if err != nil {
  50. return err
  51. }
  52. for name, s := range project.Services {
  53. if _, ok := s.DependsOn[service.Name]; ok {
  54. prefix := strings.ToUpper(service.Name) + "_"
  55. for key, val := range variables {
  56. s.Environment[prefix+key] = &val
  57. }
  58. project.Services[name] = s
  59. }
  60. }
  61. return nil
  62. }
  63. func (s *composeService) executePlugin(ctx context.Context, cmd *exec.Cmd, command string, service types.ServiceConfig) (types.Mapping, error) {
  64. eg := errgroup.Group{}
  65. stdout, err := cmd.StdoutPipe()
  66. if err != nil {
  67. return nil, err
  68. }
  69. err = cmd.Start()
  70. if err != nil {
  71. return nil, err
  72. }
  73. eg.Go(cmd.Wait)
  74. decoder := json.NewDecoder(stdout)
  75. defer func() { _ = stdout.Close() }()
  76. variables := types.Mapping{}
  77. pw := progress.ContextWriter(ctx)
  78. var action string
  79. switch command {
  80. case "up":
  81. pw.Event(progress.CreatingEvent(service.Name))
  82. action = "create"
  83. case "down":
  84. pw.Event(progress.RemovingEvent(service.Name))
  85. action = "remove"
  86. default:
  87. return nil, fmt.Errorf("unsupported plugin command: %s", command)
  88. }
  89. for {
  90. var msg JsonMessage
  91. err = decoder.Decode(&msg)
  92. if errors.Is(err, io.EOF) {
  93. break
  94. }
  95. if err != nil {
  96. return nil, err
  97. }
  98. switch msg.Type {
  99. case ErrorType:
  100. pw.Event(progress.ErrorMessageEvent(service.Name, "error"))
  101. return nil, errors.New(msg.Message)
  102. case InfoType:
  103. pw.Event(progress.ErrorMessageEvent(service.Name, msg.Message))
  104. case SetEnvType:
  105. key, val, found := strings.Cut(msg.Message, "=")
  106. if !found {
  107. return nil, fmt.Errorf("invalid response from plugin: %s", msg.Message)
  108. }
  109. variables[key] = val
  110. default:
  111. return nil, fmt.Errorf("invalid response from plugin: %s", msg.Type)
  112. }
  113. }
  114. err = eg.Wait()
  115. if err != nil {
  116. pw.Event(progress.ErrorMessageEvent(service.Name, err.Error()))
  117. return nil, fmt.Errorf("failed to %s external service: %s", action, err.Error())
  118. }
  119. switch command {
  120. case "up":
  121. pw.Event(progress.CreatedEvent(service.Name))
  122. case "down":
  123. pw.Event(progress.RemovedEvent(service.Name))
  124. }
  125. return variables, nil
  126. }
  127. func (s *composeService) getPluginBinaryPath(provider string) (path string, err error) {
  128. if provider == "compose" {
  129. return "", errors.New("'compose' is not a valid provider type")
  130. }
  131. plugin, err := manager.GetPlugin(provider, s.dockerCli, &cobra.Command{})
  132. if err == nil {
  133. path = plugin.Path
  134. }
  135. if manager.IsNotFound(err) {
  136. path, err = exec.LookPath(provider)
  137. }
  138. return path, err
  139. }
  140. func (s *composeService) setupPluginCommand(ctx context.Context, project *types.Project, service types.ServiceConfig, path, command string) *exec.Cmd {
  141. provider := *service.Provider
  142. args := []string{"compose", "--project-name", project.Name, command}
  143. for k, v := range provider.Options {
  144. args = append(args, fmt.Sprintf("--%s=%s", k, v))
  145. }
  146. args = append(args, service.Name)
  147. cmd := exec.CommandContext(ctx, path, args...)
  148. // Remove DOCKER_CLI_PLUGIN... variable so plugin can detect it run standalone
  149. cmd.Env = filter(os.Environ(), manager.ReexecEnvvar)
  150. // Use docker/cli mechanism to propagate termination signal to child process
  151. server, err := socket.NewPluginServer(nil)
  152. if err == nil {
  153. defer server.Close() //nolint:errcheck
  154. cmd.Cancel = server.Close
  155. cmd.Env = replace(cmd.Env, socket.EnvKey, server.Addr().String())
  156. }
  157. cmd.Env = append(cmd.Env, fmt.Sprintf("DOCKER_CONTEXT=%s", s.dockerCli.CurrentContext()))
  158. // propagate opentelemetry context to child process, see https://github.com/open-telemetry/oteps/blob/main/text/0258-env-context-baggage-carriers.md
  159. carrier := propagation.MapCarrier{}
  160. otel.GetTextMapPropagator().Inject(ctx, &carrier)
  161. cmd.Env = append(cmd.Env, types.Mapping(carrier).Values()...)
  162. return cmd
  163. }