pull.go 8.3 KB

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