1
0

plugins.go 5.5 KB

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