pull.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. // check if has error and the service has a build section
  156. // then the status should be warning instead of error
  157. if err != nil && service.Build != nil {
  158. w.Event(progress.Event{
  159. ID: service.Name,
  160. Status: progress.Warning,
  161. Text: "Warning",
  162. })
  163. return "", WrapCategorisedComposeError(err, PullFailure)
  164. }
  165. if err != nil {
  166. w.Event(progress.Event{
  167. ID: service.Name,
  168. Status: progress.Error,
  169. Text: "Error",
  170. })
  171. return "", WrapCategorisedComposeError(err, PullFailure)
  172. }
  173. dec := json.NewDecoder(stream)
  174. for {
  175. var jm jsonmessage.JSONMessage
  176. if err := dec.Decode(&jm); err != nil {
  177. if err == io.EOF {
  178. break
  179. }
  180. return "", WrapCategorisedComposeError(err, PullFailure)
  181. }
  182. if jm.Error != nil {
  183. return "", WrapCategorisedComposeError(errors.New(jm.Error.Message), PullFailure)
  184. }
  185. if !quietPull {
  186. toPullProgressEvent(service.Name, jm, w)
  187. }
  188. }
  189. w.Event(progress.Event{
  190. ID: service.Name,
  191. Status: progress.Done,
  192. Text: "Pulled",
  193. })
  194. inspected, _, err := s.dockerCli.Client().ImageInspectWithRaw(ctx, service.Image)
  195. if err != nil {
  196. return "", err
  197. }
  198. return inspected.ID, nil
  199. }
  200. func (s *composeService) pullRequiredImages(ctx context.Context, project *types.Project, images map[string]string, quietPull bool) error {
  201. info, err := s.apiClient().Info(ctx)
  202. if err != nil {
  203. return err
  204. }
  205. if info.IndexServerAddress == "" {
  206. info.IndexServerAddress = registry.IndexServer
  207. }
  208. var needPull []types.ServiceConfig
  209. for _, service := range project.Services {
  210. if service.Image == "" {
  211. continue
  212. }
  213. switch service.PullPolicy {
  214. case "", types.PullPolicyMissing, types.PullPolicyIfNotPresent:
  215. if _, ok := images[service.Image]; ok {
  216. continue
  217. }
  218. case types.PullPolicyNever, types.PullPolicyBuild:
  219. continue
  220. case types.PullPolicyAlways:
  221. // force pull
  222. }
  223. needPull = append(needPull, service)
  224. }
  225. if len(needPull) == 0 {
  226. return nil
  227. }
  228. return progress.Run(ctx, func(ctx context.Context) error {
  229. w := progress.ContextWriter(ctx)
  230. eg, ctx := errgroup.WithContext(ctx)
  231. pulledImages := make([]string, len(needPull))
  232. for i, service := range needPull {
  233. i, service := i, service
  234. eg.Go(func() error {
  235. id, err := s.pullServiceImage(ctx, service, info, s.configFile(), w, quietPull)
  236. pulledImages[i] = id
  237. if err != nil && service.Build != nil {
  238. // image can be built, so we can ignore pull failure
  239. return nil
  240. }
  241. return err
  242. })
  243. }
  244. for i, service := range needPull {
  245. if pulledImages[i] != "" {
  246. images[service.Image] = pulledImages[i]
  247. }
  248. }
  249. err := eg.Wait()
  250. if err != nil {
  251. return err
  252. }
  253. return err
  254. })
  255. }
  256. func toPullProgressEvent(parent string, jm jsonmessage.JSONMessage, w progress.Writer) {
  257. if jm.ID == "" || jm.Progress == nil {
  258. return
  259. }
  260. var (
  261. text string
  262. status = progress.Working
  263. )
  264. text = jm.Progress.String()
  265. if jm.Status == "Pull complete" ||
  266. jm.Status == "Already exists" ||
  267. strings.Contains(jm.Status, "Image is up to date") ||
  268. strings.Contains(jm.Status, "Downloaded newer image") {
  269. status = progress.Done
  270. }
  271. if jm.Error != nil {
  272. status = progress.Error
  273. text = jm.Error.Message
  274. }
  275. w.Event(progress.Event{
  276. ID: jm.ID,
  277. ParentID: parent,
  278. Text: jm.Status,
  279. Status: status,
  280. StatusText: text,
  281. })
  282. }