plugins.go 5.1 KB

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