model.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. w := progress.ContextWriter(gctx)
  74. if !slices.Contains(availableModels, config.Model) {
  75. err = s.pullModel(gctx, dockerModel, config, quietPull, w)
  76. if err != nil {
  77. return err
  78. }
  79. }
  80. err = s.configureModel(gctx, dockerModel, config, w)
  81. if err != nil {
  82. return err
  83. }
  84. w.Event(progress.CreatedEvent(config.Name))
  85. return nil
  86. })
  87. }
  88. return eg.Wait()
  89. }
  90. func (s *composeService) pullModel(ctx context.Context, dockerModel *manager.Plugin, model types.ModelConfig, quietPull bool, w progress.Writer) error {
  91. w.Event(progress.Event{
  92. ID: model.Name,
  93. Status: progress.Working,
  94. Text: "Pulling",
  95. })
  96. cmd := exec.CommandContext(ctx, dockerModel.Path, "pull", model.Model)
  97. s.setupChildProcess(ctx, cmd)
  98. stream, err := cmd.StdoutPipe()
  99. if err != nil {
  100. return err
  101. }
  102. err = cmd.Start()
  103. if err != nil {
  104. return err
  105. }
  106. scanner := bufio.NewScanner(stream)
  107. for scanner.Scan() {
  108. msg := scanner.Text()
  109. if msg == "" {
  110. continue
  111. }
  112. if !quietPull {
  113. w.Event(progress.Event{
  114. ID: model.Name,
  115. Status: progress.Working,
  116. Text: "Pulling",
  117. StatusText: msg,
  118. })
  119. }
  120. }
  121. err = cmd.Wait()
  122. if err != nil {
  123. w.Event(progress.ErrorMessageEvent(model.Name, err.Error()))
  124. }
  125. w.Event(progress.Event{
  126. ID: model.Name,
  127. Status: progress.Working,
  128. Text: "Pulled",
  129. })
  130. return err
  131. }
  132. func (s *composeService) configureModel(ctx context.Context, dockerModel *manager.Plugin, config types.ModelConfig, w progress.Writer) error {
  133. w.Event(progress.Event{
  134. ID: config.Name,
  135. Status: progress.Working,
  136. Text: "Configuring",
  137. })
  138. // configure [--context-size=<n>] MODEL [-- <runtime-flags...>]
  139. args := []string{"configure"}
  140. if config.ContextSize > 0 {
  141. args = append(args, "--context-size", strconv.Itoa(config.ContextSize))
  142. }
  143. args = append(args, config.Model)
  144. if len(config.RuntimeFlags) != 0 {
  145. args = append(args, "--")
  146. args = append(args, config.RuntimeFlags...)
  147. }
  148. cmd := exec.CommandContext(ctx, dockerModel.Path, args...)
  149. s.setupChildProcess(ctx, cmd)
  150. return cmd.Run()
  151. }
  152. func (s *composeService) setModelVariables(ctx context.Context, dockerModel *manager.Plugin, project *types.Project) error {
  153. cmd := exec.CommandContext(ctx, dockerModel.Path, "status", "--json")
  154. s.setupChildProcess(ctx, cmd)
  155. statusOut, err := cmd.CombinedOutput()
  156. if err != nil {
  157. return fmt.Errorf("error checking docker-model status: %w", err)
  158. }
  159. type Status struct {
  160. Endpoint string `json:"endpoint"`
  161. }
  162. var status Status
  163. err = json.Unmarshal(statusOut, &status)
  164. if err != nil {
  165. return err
  166. }
  167. for _, service := range project.Services {
  168. for ref, modelConfig := range service.Models {
  169. model := project.Models[ref]
  170. varPrefix := strings.ReplaceAll(strings.ToUpper(ref), "-", "_")
  171. var variable string
  172. if modelConfig != nil && modelConfig.ModelVariable != "" {
  173. variable = modelConfig.ModelVariable
  174. } else {
  175. variable = varPrefix
  176. }
  177. service.Environment[variable] = &model.Model
  178. if modelConfig != nil && modelConfig.EndpointVariable != "" {
  179. variable = modelConfig.EndpointVariable
  180. } else {
  181. variable = varPrefix + "_URL"
  182. }
  183. service.Environment[variable] = &status.Endpoint
  184. }
  185. }
  186. return nil
  187. }
  188. func (s *composeService) setupChildProcess(gctx context.Context, cmd *exec.Cmd) {
  189. // exec provider command with same environment Compose is running
  190. env := types.NewMapping(os.Environ())
  191. // but remove DOCKER_CLI_PLUGIN... variable so plugin can detect it run standalone
  192. delete(env, manager.ReexecEnvvar)
  193. // propagate opentelemetry context to child process, see https://github.com/open-telemetry/oteps/blob/main/text/0258-env-context-baggage-carriers.md
  194. carrier := propagation.MapCarrier{}
  195. otel.GetTextMapPropagator().Inject(gctx, &carrier)
  196. env.Merge(types.Mapping(carrier))
  197. env["DOCKER_CONTEXT"] = s.dockerCli.CurrentContext()
  198. cmd.Env = env.Values()
  199. }
  200. type Model struct {
  201. Id string `json:"id"`
  202. Tags []string `json:"tags"`
  203. Created int `json:"created"`
  204. Config struct {
  205. Format string `json:"format"`
  206. Quantization string `json:"quantization"`
  207. Parameters string `json:"parameters"`
  208. Architecture string `json:"architecture"`
  209. Size string `json:"size"`
  210. } `json:"config"`
  211. }