model.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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. "bufio"
  16. "context"
  17. "encoding/json"
  18. "fmt"
  19. "os"
  20. "os/exec"
  21. "slices"
  22. "strconv"
  23. "strings"
  24. "github.com/compose-spec/compose-go/v2/types"
  25. "github.com/containerd/errdefs"
  26. "github.com/docker/cli/cli-plugins/manager"
  27. "github.com/docker/compose/v2/pkg/progress"
  28. "github.com/spf13/cobra"
  29. "go.opentelemetry.io/otel"
  30. "go.opentelemetry.io/otel/propagation"
  31. "golang.org/x/sync/errgroup"
  32. )
  33. func (s *composeService) ensureModels(ctx context.Context, project *types.Project, quietPull bool) error {
  34. if len(project.Models) == 0 {
  35. return nil
  36. }
  37. dockerModel, err := manager.GetPlugin("model", s.dockerCli, &cobra.Command{})
  38. if err != nil {
  39. if errdefs.IsNotFound(err) {
  40. return fmt.Errorf("'models' support requires Docker Model plugin")
  41. }
  42. return err
  43. }
  44. cmd := exec.CommandContext(ctx, dockerModel.Path, "ls", "--json")
  45. s.setupChildProcess(ctx, cmd)
  46. output, err := cmd.CombinedOutput()
  47. if err != nil {
  48. return fmt.Errorf("error checking available models: %w", err)
  49. }
  50. type AvailableModel struct {
  51. Id string `json:"id"`
  52. Tags []string `json:"tags"`
  53. Created int `json:"created"`
  54. }
  55. models := []AvailableModel{}
  56. err = json.Unmarshal(output, &models)
  57. if err != nil {
  58. return fmt.Errorf("error unmarshalling available models: %w", err)
  59. }
  60. var availableModels []string
  61. for _, model := range models {
  62. availableModels = append(availableModels, model.Tags...)
  63. }
  64. eg, gctx := errgroup.WithContext(ctx)
  65. eg.Go(func() error {
  66. return s.setModelVariables(gctx, dockerModel, project)
  67. })
  68. for name, config := range project.Models {
  69. if config.Name == "" {
  70. config.Name = name
  71. }
  72. eg.Go(func() error {
  73. if !slices.Contains(availableModels, config.Model) {
  74. err = s.pullModel(gctx, dockerModel, config, quietPull)
  75. if err != nil {
  76. return err
  77. }
  78. }
  79. return s.configureModel(gctx, dockerModel, config)
  80. })
  81. }
  82. return eg.Wait()
  83. }
  84. func (s *composeService) pullModel(ctx context.Context, dockerModel *manager.Plugin, model types.ModelConfig, quietPull bool) error {
  85. w := progress.ContextWriter(ctx)
  86. w.Event(progress.Event{
  87. ID: model.Name,
  88. Status: progress.Working,
  89. Text: "Pulling",
  90. })
  91. cmd := exec.CommandContext(ctx, dockerModel.Path, "pull", model.Model)
  92. s.setupChildProcess(ctx, cmd)
  93. stream, err := cmd.StdoutPipe()
  94. if err != nil {
  95. return err
  96. }
  97. err = cmd.Start()
  98. if err != nil {
  99. return err
  100. }
  101. scanner := bufio.NewScanner(stream)
  102. for scanner.Scan() {
  103. msg := scanner.Text()
  104. if msg == "" {
  105. continue
  106. }
  107. if !quietPull {
  108. w.Event(progress.Event{
  109. ID: model.Name,
  110. Status: progress.Working,
  111. Text: "Pulling",
  112. StatusText: msg,
  113. })
  114. }
  115. }
  116. err = cmd.Wait()
  117. if err != nil {
  118. w.Event(progress.ErrorMessageEvent(model.Name, err.Error()))
  119. }
  120. w.Event(progress.Event{
  121. ID: model.Name,
  122. Status: progress.Working,
  123. Text: "Pulled",
  124. })
  125. return err
  126. }
  127. func (s *composeService) configureModel(ctx context.Context, dockerModel *manager.Plugin, config types.ModelConfig) error {
  128. // configure [--context-size=<n>] MODEL [-- <runtime-flags...>]
  129. args := []string{"configure"}
  130. if config.ContextSize > 0 {
  131. args = append(args, "--context-size", strconv.Itoa(config.ContextSize))
  132. }
  133. args = append(args, config.Model)
  134. if len(config.RuntimeFlags) != 0 {
  135. args = append(args, "--")
  136. args = append(args, config.RuntimeFlags...)
  137. }
  138. cmd := exec.CommandContext(ctx, dockerModel.Path, args...)
  139. s.setupChildProcess(ctx, cmd)
  140. return cmd.Run()
  141. }
  142. func (s *composeService) setModelVariables(ctx context.Context, dockerModel *manager.Plugin, project *types.Project) error {
  143. cmd := exec.CommandContext(ctx, dockerModel.Path, "status", "--json")
  144. s.setupChildProcess(ctx, cmd)
  145. statusOut, err := cmd.CombinedOutput()
  146. if err != nil {
  147. return fmt.Errorf("error checking docker-model status: %w", err)
  148. }
  149. type Status struct {
  150. Endpoint string `json:"endpoint"`
  151. }
  152. var status Status
  153. err = json.Unmarshal(statusOut, &status)
  154. if err != nil {
  155. return err
  156. }
  157. for _, service := range project.Services {
  158. for ref, modelConfig := range service.Models {
  159. model := project.Models[ref]
  160. varPrefix := strings.ReplaceAll(strings.ToUpper(ref), "-", "_")
  161. var variable string
  162. if modelConfig != nil && modelConfig.ModelVariable != "" {
  163. variable = modelConfig.ModelVariable
  164. } else {
  165. variable = varPrefix
  166. }
  167. service.Environment[variable] = &model.Model
  168. if modelConfig != nil && modelConfig.EndpointVariable != "" {
  169. variable = modelConfig.EndpointVariable
  170. } else {
  171. variable = varPrefix + "_URL"
  172. }
  173. service.Environment[variable] = &status.Endpoint
  174. }
  175. }
  176. return nil
  177. }
  178. func (s *composeService) setupChildProcess(gctx context.Context, cmd *exec.Cmd) {
  179. // exec provider command with same environment Compose is running
  180. env := types.NewMapping(os.Environ())
  181. // but remove DOCKER_CLI_PLUGIN... variable so plugin can detect it run standalone
  182. delete(env, manager.ReexecEnvvar)
  183. // propagate opentelemetry context to child process, see https://github.com/open-telemetry/oteps/blob/main/text/0258-env-context-baggage-carriers.md
  184. carrier := propagation.MapCarrier{}
  185. otel.GetTextMapPropagator().Inject(gctx, &carrier)
  186. env.Merge(types.Mapping(carrier))
  187. env["DOCKER_CONTEXT"] = s.dockerCli.CurrentContext()
  188. cmd.Env = env.Values()
  189. }
  190. type Model struct {
  191. Id string `json:"id"`
  192. Tags []string `json:"tags"`
  193. Created int `json:"created"`
  194. Config struct {
  195. Format string `json:"format"`
  196. Quantization string `json:"quantization"`
  197. Parameters string `json:"parameters"`
  198. Architecture string `json:"architecture"`
  199. Size string `json:"size"`
  200. } `json:"config"`
  201. }