pull.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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/base64"
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "io"
  21. "strings"
  22. "github.com/compose-spec/compose-go/types"
  23. "github.com/distribution/distribution/v3/reference"
  24. "github.com/docker/buildx/driver"
  25. moby "github.com/docker/docker/api/types"
  26. "github.com/docker/docker/pkg/jsonmessage"
  27. "github.com/docker/docker/registry"
  28. "golang.org/x/sync/errgroup"
  29. "github.com/docker/compose/v2/pkg/api"
  30. "github.com/docker/compose/v2/pkg/progress"
  31. )
  32. func (s *composeService) Pull(ctx context.Context, project *types.Project, options api.PullOptions) error {
  33. if options.Quiet {
  34. return s.pull(ctx, project, options)
  35. }
  36. return progress.Run(ctx, func(ctx context.Context) error {
  37. return s.pull(ctx, project, options)
  38. })
  39. }
  40. func (s *composeService) pull(ctx context.Context, project *types.Project, opts api.PullOptions) error {
  41. info, err := s.apiClient().Info(ctx)
  42. if err != nil {
  43. return err
  44. }
  45. if info.IndexServerAddress == "" {
  46. info.IndexServerAddress = registry.IndexServer
  47. }
  48. images, err := s.getLocalImagesDigests(ctx, project)
  49. if err != nil {
  50. return err
  51. }
  52. w := progress.ContextWriter(ctx)
  53. eg, ctx := errgroup.WithContext(ctx)
  54. var mustBuild []string
  55. imagesBeingPulled := map[string]string{}
  56. for _, service := range project.Services {
  57. service := service
  58. if service.Image == "" {
  59. w.Event(progress.Event{
  60. ID: service.Name,
  61. Status: progress.Done,
  62. Text: "Skipped - No image to be pulled",
  63. })
  64. continue
  65. }
  66. switch service.PullPolicy {
  67. case types.PullPolicyNever, types.PullPolicyBuild:
  68. w.Event(progress.Event{
  69. ID: service.Name,
  70. Status: progress.Done,
  71. Text: "Skipped",
  72. })
  73. continue
  74. case types.PullPolicyMissing, types.PullPolicyIfNotPresent:
  75. if _, ok := images[service.Image]; ok {
  76. w.Event(progress.Event{
  77. ID: service.Name,
  78. Status: progress.Done,
  79. Text: "Skipped - Image is already present locally",
  80. })
  81. continue
  82. }
  83. }
  84. if s, ok := imagesBeingPulled[service.Image]; ok {
  85. w.Event(progress.Event{
  86. ID: service.Name,
  87. Status: progress.Done,
  88. Text: fmt.Sprintf("Skipped - Image is already being pulled by %v", s),
  89. })
  90. continue
  91. }
  92. imagesBeingPulled[service.Image] = service.Name
  93. eg.Go(func() error {
  94. _, err := s.pullServiceImage(ctx, service, info, s.configFile(), w, false)
  95. if err != nil {
  96. if !opts.IgnoreFailures {
  97. if service.Build != nil {
  98. mustBuild = append(mustBuild, service.Name)
  99. }
  100. return err
  101. }
  102. w.TailMsgf("Pulling %s: %s", service.Name, err.Error())
  103. }
  104. return nil
  105. })
  106. }
  107. err = eg.Wait()
  108. if !opts.IgnoreFailures && len(mustBuild) > 0 {
  109. w.TailMsgf("WARNING: Some service image(s) must be built from source by running:\n docker compose build %s", strings.Join(mustBuild, " "))
  110. }
  111. return err
  112. }
  113. func (s *composeService) pullServiceImage(ctx context.Context, service types.ServiceConfig, info moby.Info, configFile driver.Auth, w progress.Writer, quietPull bool) (string, error) {
  114. w.Event(progress.Event{
  115. ID: service.Name,
  116. Status: progress.Working,
  117. Text: "Pulling",
  118. })
  119. ref, err := reference.ParseNormalizedNamed(service.Image)
  120. if err != nil {
  121. return "", err
  122. }
  123. repoInfo, err := registry.ParseRepositoryInfo(ref)
  124. if err != nil {
  125. return "", err
  126. }
  127. key := repoInfo.Index.Name
  128. if repoInfo.Index.Official {
  129. key = info.IndexServerAddress
  130. }
  131. authConfig, err := configFile.GetAuthConfig(key)
  132. if err != nil {
  133. return "", err
  134. }
  135. buf, err := json.Marshal(authConfig)
  136. if err != nil {
  137. return "", err
  138. }
  139. stream, err := s.apiClient().ImagePull(ctx, service.Image, moby.ImagePullOptions{
  140. RegistryAuth: base64.URLEncoding.EncodeToString(buf),
  141. Platform: service.Platform,
  142. })
  143. if err != nil {
  144. w.Event(progress.Event{
  145. ID: service.Name,
  146. Status: progress.Error,
  147. Text: "Error",
  148. })
  149. return "", WrapCategorisedComposeError(err, PullFailure)
  150. }
  151. dec := json.NewDecoder(stream)
  152. for {
  153. var jm jsonmessage.JSONMessage
  154. if err := dec.Decode(&jm); err != nil {
  155. if err == io.EOF {
  156. break
  157. }
  158. return "", WrapCategorisedComposeError(err, PullFailure)
  159. }
  160. if jm.Error != nil {
  161. return "", WrapCategorisedComposeError(errors.New(jm.Error.Message), PullFailure)
  162. }
  163. if !quietPull {
  164. toPullProgressEvent(service.Name, jm, w)
  165. }
  166. }
  167. w.Event(progress.Event{
  168. ID: service.Name,
  169. Status: progress.Done,
  170. Text: "Pulled",
  171. })
  172. inspected, _, err := s.dockerCli.Client().ImageInspectWithRaw(ctx, service.Image)
  173. if err != nil {
  174. return "", err
  175. }
  176. return inspected.ID, nil
  177. }
  178. func (s *composeService) pullRequiredImages(ctx context.Context, project *types.Project, images map[string]string, quietPull bool) error {
  179. info, err := s.apiClient().Info(ctx)
  180. if err != nil {
  181. return err
  182. }
  183. if info.IndexServerAddress == "" {
  184. info.IndexServerAddress = registry.IndexServer
  185. }
  186. var needPull []types.ServiceConfig
  187. for _, service := range project.Services {
  188. if service.Image == "" {
  189. continue
  190. }
  191. switch service.PullPolicy {
  192. case "", types.PullPolicyMissing, types.PullPolicyIfNotPresent:
  193. if _, ok := images[service.Image]; ok {
  194. continue
  195. }
  196. case types.PullPolicyNever, types.PullPolicyBuild:
  197. continue
  198. case types.PullPolicyAlways:
  199. // force pull
  200. }
  201. needPull = append(needPull, service)
  202. }
  203. if len(needPull) == 0 {
  204. return nil
  205. }
  206. return progress.Run(ctx, func(ctx context.Context) error {
  207. w := progress.ContextWriter(ctx)
  208. eg, ctx := errgroup.WithContext(ctx)
  209. pulledImages := make([]string, len(needPull))
  210. for i, service := range needPull {
  211. i, service := i, service
  212. eg.Go(func() error {
  213. id, err := s.pullServiceImage(ctx, service, info, s.configFile(), w, quietPull)
  214. pulledImages[i] = id
  215. if err != nil && service.Build != nil {
  216. // image can be built, so we can ignore pull failure
  217. return nil
  218. }
  219. return err
  220. })
  221. }
  222. for i, service := range needPull {
  223. if pulledImages[i] != "" {
  224. images[service.Image] = pulledImages[i]
  225. }
  226. }
  227. err := eg.Wait()
  228. if err != nil {
  229. return err
  230. }
  231. return err
  232. })
  233. }
  234. func toPullProgressEvent(parent string, jm jsonmessage.JSONMessage, w progress.Writer) {
  235. if jm.ID == "" || jm.Progress == nil {
  236. return
  237. }
  238. var (
  239. text string
  240. status = progress.Working
  241. )
  242. text = jm.Progress.String()
  243. if jm.Status == "Pull complete" ||
  244. jm.Status == "Already exists" ||
  245. strings.Contains(jm.Status, "Image is up to date") ||
  246. strings.Contains(jm.Status, "Downloaded newer image") {
  247. status = progress.Done
  248. }
  249. if jm.Error != nil {
  250. status = progress.Error
  251. text = jm.Error.Message
  252. }
  253. w.Event(progress.Event{
  254. ID: jm.ID,
  255. ParentID: parent,
  256. Text: jm.Status,
  257. Status: status,
  258. StatusText: text,
  259. })
  260. }