plugins.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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. if err := s.checkPluginEnabledInDD(ctx, plugin); err != nil {
  48. return err
  49. }
  50. cmd := s.setupPluginCommand(ctx, project, provider, plugin.Path, command)
  51. eg := errgroup.Group{}
  52. stdout, err := cmd.StdoutPipe()
  53. if err != nil {
  54. return err
  55. }
  56. err = cmd.Start()
  57. if err != nil {
  58. return err
  59. }
  60. eg.Go(cmd.Wait)
  61. decoder := json.NewDecoder(stdout)
  62. defer func() { _ = stdout.Close() }()
  63. variables := types.Mapping{}
  64. pw := progress.ContextWriter(ctx)
  65. pw.Event(progress.CreatingEvent(service.Name))
  66. for {
  67. var msg JsonMessage
  68. err = decoder.Decode(&msg)
  69. if errors.Is(err, io.EOF) {
  70. break
  71. }
  72. if err != nil {
  73. return err
  74. }
  75. switch msg.Type {
  76. case ErrorType:
  77. pw.Event(progress.ErrorMessageEvent(service.Name, "error"))
  78. return errors.New(msg.Message)
  79. case InfoType:
  80. pw.Event(progress.ErrorMessageEvent(service.Name, msg.Message))
  81. case SetEnvType:
  82. key, val, found := strings.Cut(msg.Message, "=")
  83. if !found {
  84. return fmt.Errorf("invalid response from plugin: %s", msg.Message)
  85. }
  86. variables[key] = val
  87. default:
  88. return fmt.Errorf("invalid response from plugin: %s", msg.Type)
  89. }
  90. }
  91. err = eg.Wait()
  92. if err != nil {
  93. pw.Event(progress.ErrorMessageEvent(service.Name, err.Error()))
  94. return fmt.Errorf("failed to create external service: %s", err.Error())
  95. }
  96. pw.Event(progress.CreatedEvent(service.Name))
  97. prefix := strings.ToUpper(service.Name) + "_"
  98. for name, s := range project.Services {
  99. if _, ok := s.DependsOn[service.Name]; ok {
  100. for key, val := range variables {
  101. s.Environment[prefix+key] = &val
  102. }
  103. project.Services[name] = s
  104. }
  105. }
  106. return nil
  107. }
  108. func (s *composeService) getPluginBinaryPath(providerType string) (*manager.Plugin, error) {
  109. // Only support Docker CLI plugins for first iteration. Could support any binary from PATH
  110. return manager.GetPlugin(providerType, s.dockerCli, &cobra.Command{})
  111. }
  112. func (s *composeService) setupPluginCommand(ctx context.Context, project *types.Project, provider types.ServiceProviderConfig, path, command string) *exec.Cmd {
  113. args := []string{"compose", "--project-name", project.Name, command}
  114. for k, v := range provider.Options {
  115. args = append(args, fmt.Sprintf("--%s=%s", k, v))
  116. }
  117. cmd := exec.CommandContext(ctx, path, args...)
  118. // Remove DOCKER_CLI_PLUGIN... variable so plugin can detect it run standalone
  119. cmd.Env = filter(os.Environ(), manager.ReexecEnvvar)
  120. // Use docker/cli mechanism to propagate termination signal to child process
  121. server, err := socket.NewPluginServer(nil)
  122. if err == nil {
  123. defer server.Close() //nolint:errcheck
  124. cmd.Cancel = server.Close
  125. cmd.Env = replace(cmd.Env, socket.EnvKey, server.Addr().String())
  126. }
  127. cmd.Env = append(cmd.Env, fmt.Sprintf("DOCKER_CONTEXT=%s", s.dockerCli.CurrentContext()))
  128. // propagate opentelemetry context to child process, see https://github.com/open-telemetry/oteps/blob/main/text/0258-env-context-baggage-carriers.md
  129. carrier := propagation.MapCarrier{}
  130. otel.GetTextMapPropagator().Inject(ctx, &carrier)
  131. cmd.Env = append(cmd.Env, types.Mapping(carrier).Values()...)
  132. return cmd
  133. }
  134. func (s *composeService) checkPluginEnabledInDD(ctx context.Context, plugin *manager.Plugin) error {
  135. if integrationEnabled := s.isDesktopIntegrationActive(); !integrationEnabled {
  136. return fmt.Errorf("you should enable Docker Desktop integration to use %q provider services", plugin.Name)
  137. }
  138. // Until we support more use cases, check explicitly status of model runner
  139. if plugin.Name == "model" {
  140. cmd := exec.CommandContext(ctx, "docker", "model", "status")
  141. _, err := cmd.CombinedOutput()
  142. if err != nil {
  143. var exitErr *exec.ExitError
  144. if errors.As(err, &exitErr) && exitErr.ExitCode() == 1 {
  145. return fmt.Errorf("you should enable model runner to use %q provider services: %s", plugin.Name, err.Error())
  146. }
  147. }
  148. } else {
  149. return fmt.Errorf("unsupported provider %q", plugin.Name)
  150. }
  151. return nil
  152. }