pull.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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 imageAlreadyPresent(service.Image, images) {
  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 imageAlreadyPresent(serviceImage string, localImages map[string]string) bool {
  114. normalizedImage, err := reference.ParseDockerRef(serviceImage)
  115. if err != nil {
  116. return false
  117. }
  118. tagged, ok := normalizedImage.(reference.NamedTagged)
  119. if !ok {
  120. return false
  121. }
  122. _, ok = localImages[serviceImage]
  123. return ok && tagged.Tag() != "latest"
  124. }
  125. func (s *composeService) pullServiceImage(ctx context.Context, service types.ServiceConfig, info moby.Info, configFile driver.Auth, w progress.Writer, quietPull bool) (string, error) {
  126. w.Event(progress.Event{
  127. ID: service.Name,
  128. Status: progress.Working,
  129. Text: "Pulling",
  130. })
  131. ref, err := reference.ParseNormalizedNamed(service.Image)
  132. if err != nil {
  133. return "", err
  134. }
  135. repoInfo, err := registry.ParseRepositoryInfo(ref)
  136. if err != nil {
  137. return "", err
  138. }
  139. key := repoInfo.Index.Name
  140. if repoInfo.Index.Official {
  141. key = info.IndexServerAddress
  142. }
  143. authConfig, err := configFile.GetAuthConfig(key)
  144. if err != nil {
  145. return "", err
  146. }
  147. buf, err := json.Marshal(authConfig)
  148. if err != nil {
  149. return "", err
  150. }
  151. stream, err := s.apiClient().ImagePull(ctx, service.Image, moby.ImagePullOptions{
  152. RegistryAuth: base64.URLEncoding.EncodeToString(buf),
  153. Platform: service.Platform,
  154. })
  155. if err != nil {
  156. w.Event(progress.Event{
  157. ID: service.Name,
  158. Status: progress.Error,
  159. Text: "Error",
  160. })
  161. return "", WrapCategorisedComposeError(err, PullFailure)
  162. }
  163. dec := json.NewDecoder(stream)
  164. for {
  165. var jm jsonmessage.JSONMessage
  166. if err := dec.Decode(&jm); err != nil {
  167. if err == io.EOF {
  168. break
  169. }
  170. return "", WrapCategorisedComposeError(err, PullFailure)
  171. }
  172. if jm.Error != nil {
  173. return "", WrapCategorisedComposeError(errors.New(jm.Error.Message), PullFailure)
  174. }
  175. if !quietPull {
  176. toPullProgressEvent(service.Name, jm, w)
  177. }
  178. }
  179. w.Event(progress.Event{
  180. ID: service.Name,
  181. Status: progress.Done,
  182. Text: "Pulled",
  183. })
  184. inspected, _, err := s.dockerCli.Client().ImageInspectWithRaw(ctx, service.Image)
  185. if err != nil {
  186. return "", err
  187. }
  188. return inspected.ID, nil
  189. }
  190. func (s *composeService) pullRequiredImages(ctx context.Context, project *types.Project, images map[string]string, quietPull bool) error {
  191. info, err := s.apiClient().Info(ctx)
  192. if err != nil {
  193. return err
  194. }
  195. if info.IndexServerAddress == "" {
  196. info.IndexServerAddress = registry.IndexServer
  197. }
  198. var needPull []types.ServiceConfig
  199. for _, service := range project.Services {
  200. if service.Image == "" {
  201. continue
  202. }
  203. switch service.PullPolicy {
  204. case "", types.PullPolicyMissing, types.PullPolicyIfNotPresent:
  205. if _, ok := images[service.Image]; ok {
  206. continue
  207. }
  208. case types.PullPolicyNever, types.PullPolicyBuild:
  209. continue
  210. case types.PullPolicyAlways:
  211. // force pull
  212. }
  213. needPull = append(needPull, service)
  214. }
  215. if len(needPull) == 0 {
  216. return nil
  217. }
  218. return progress.Run(ctx, func(ctx context.Context) error {
  219. w := progress.ContextWriter(ctx)
  220. eg, ctx := errgroup.WithContext(ctx)
  221. pulledImages := make([]string, len(needPull))
  222. for i, service := range needPull {
  223. i, service := i, service
  224. eg.Go(func() error {
  225. id, err := s.pullServiceImage(ctx, service, info, s.configFile(), w, quietPull)
  226. pulledImages[i] = id
  227. if err != nil && service.Build != nil {
  228. // image can be built, so we can ignore pull failure
  229. return nil
  230. }
  231. return err
  232. })
  233. }
  234. for i, service := range needPull {
  235. if pulledImages[i] != "" {
  236. images[service.Image] = pulledImages[i]
  237. }
  238. }
  239. err := eg.Wait()
  240. if err != nil {
  241. return err
  242. }
  243. return err
  244. })
  245. }
  246. func toPullProgressEvent(parent string, jm jsonmessage.JSONMessage, w progress.Writer) {
  247. if jm.ID == "" || jm.Progress == nil {
  248. return
  249. }
  250. var (
  251. text string
  252. status = progress.Working
  253. )
  254. text = jm.Progress.String()
  255. if jm.Status == "Pull complete" ||
  256. jm.Status == "Already exists" ||
  257. strings.Contains(jm.Status, "Image is up to date") ||
  258. strings.Contains(jm.Status, "Downloaded newer image") {
  259. status = progress.Done
  260. }
  261. if jm.Error != nil {
  262. status = progress.Error
  263. text = jm.Error.Message
  264. }
  265. w.Event(progress.Event{
  266. ID: jm.ID,
  267. ParentID: parent,
  268. Text: jm.Status,
  269. Status: status,
  270. StatusText: text,
  271. })
  272. }