pull.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. eg.SetLimit(s.maxConcurrency)
  55. var mustBuild []string
  56. imagesBeingPulled := map[string]string{}
  57. for _, service := range project.Services {
  58. service := service
  59. if service.Image == "" {
  60. w.Event(progress.Event{
  61. ID: service.Name,
  62. Status: progress.Done,
  63. Text: "Skipped - No image to be pulled",
  64. })
  65. continue
  66. }
  67. switch service.PullPolicy {
  68. case types.PullPolicyNever, types.PullPolicyBuild:
  69. w.Event(progress.Event{
  70. ID: service.Name,
  71. Status: progress.Done,
  72. Text: "Skipped",
  73. })
  74. continue
  75. case types.PullPolicyMissing, types.PullPolicyIfNotPresent:
  76. if imageAlreadyPresent(service.Image, images) {
  77. w.Event(progress.Event{
  78. ID: service.Name,
  79. Status: progress.Done,
  80. Text: "Skipped - Image is already present locally",
  81. })
  82. continue
  83. }
  84. }
  85. if s, ok := imagesBeingPulled[service.Image]; ok {
  86. w.Event(progress.Event{
  87. ID: service.Name,
  88. Status: progress.Done,
  89. Text: fmt.Sprintf("Skipped - Image is already being pulled by %v", s),
  90. })
  91. continue
  92. }
  93. imagesBeingPulled[service.Image] = service.Name
  94. eg.Go(func() error {
  95. _, err := s.pullServiceImage(ctx, service, info, s.configFile(), w, false, project.Environment["DOCKER_DEFAULT_PLATFORM"])
  96. if err != nil {
  97. if !opts.IgnoreFailures {
  98. if service.Build != nil {
  99. mustBuild = append(mustBuild, service.Name)
  100. }
  101. return err
  102. }
  103. w.TailMsgf("Pulling %s: %s", service.Name, err.Error())
  104. }
  105. return nil
  106. })
  107. }
  108. err = eg.Wait()
  109. if !opts.IgnoreFailures && len(mustBuild) > 0 {
  110. w.TailMsgf("WARNING: Some service image(s) must be built from source by running:\n docker compose build %s", strings.Join(mustBuild, " "))
  111. }
  112. return err
  113. }
  114. func imageAlreadyPresent(serviceImage string, localImages map[string]string) bool {
  115. normalizedImage, err := reference.ParseDockerRef(serviceImage)
  116. if err != nil {
  117. return false
  118. }
  119. tagged, ok := normalizedImage.(reference.NamedTagged)
  120. if !ok {
  121. return false
  122. }
  123. _, ok = localImages[serviceImage]
  124. return ok && tagged.Tag() != "latest"
  125. }
  126. func (s *composeService) pullServiceImage(ctx context.Context, service types.ServiceConfig, info moby.Info,
  127. configFile driver.Auth, w progress.Writer, quietPull bool, defaultPlatform string) (string, error) {
  128. w.Event(progress.Event{
  129. ID: service.Name,
  130. Status: progress.Working,
  131. Text: "Pulling",
  132. })
  133. ref, err := reference.ParseNormalizedNamed(service.Image)
  134. if err != nil {
  135. return "", err
  136. }
  137. encodedAuth, err := encodedAuth(ref, info, configFile)
  138. if err != nil {
  139. return "", err
  140. }
  141. platform := service.Platform
  142. if platform == "" {
  143. platform = defaultPlatform
  144. }
  145. stream, err := s.apiClient().ImagePull(ctx, service.Image, moby.ImagePullOptions{
  146. RegistryAuth: encodedAuth,
  147. Platform: platform,
  148. })
  149. // check if has error and the service has a build section
  150. // then the status should be warning instead of error
  151. if err != nil && service.Build != nil {
  152. w.Event(progress.Event{
  153. ID: service.Name,
  154. Status: progress.Warning,
  155. Text: "Warning",
  156. })
  157. return "", WrapCategorisedComposeError(err, PullFailure)
  158. }
  159. if err != nil {
  160. w.Event(progress.Event{
  161. ID: service.Name,
  162. Status: progress.Error,
  163. Text: "Error",
  164. })
  165. return "", WrapCategorisedComposeError(err, PullFailure)
  166. }
  167. dec := json.NewDecoder(stream)
  168. for {
  169. var jm jsonmessage.JSONMessage
  170. if err := dec.Decode(&jm); err != nil {
  171. if err == io.EOF {
  172. break
  173. }
  174. return "", WrapCategorisedComposeError(err, PullFailure)
  175. }
  176. if jm.Error != nil {
  177. return "", WrapCategorisedComposeError(errors.New(jm.Error.Message), PullFailure)
  178. }
  179. if !quietPull {
  180. toPullProgressEvent(service.Name, jm, w)
  181. }
  182. }
  183. w.Event(progress.Event{
  184. ID: service.Name,
  185. Status: progress.Done,
  186. Text: "Pulled",
  187. })
  188. inspected, _, err := s.dockerCli.Client().ImageInspectWithRaw(ctx, service.Image)
  189. if err != nil {
  190. return "", err
  191. }
  192. return inspected.ID, nil
  193. }
  194. func encodedAuth(ref reference.Named, info moby.Info, configFile driver.Auth) (string, error) {
  195. repoInfo, err := registry.ParseRepositoryInfo(ref)
  196. if err != nil {
  197. return "", err
  198. }
  199. key := repoInfo.Index.Name
  200. if repoInfo.Index.Official {
  201. key = info.IndexServerAddress
  202. }
  203. authConfig, err := configFile.GetAuthConfig(key)
  204. if err != nil {
  205. return "", err
  206. }
  207. buf, err := json.Marshal(authConfig)
  208. if err != nil {
  209. return "", err
  210. }
  211. return base64.URLEncoding.EncodeToString(buf), nil
  212. }
  213. func (s *composeService) pullRequiredImages(ctx context.Context, project *types.Project, images map[string]string, quietPull bool) error {
  214. info, err := s.apiClient().Info(ctx)
  215. if err != nil {
  216. return err
  217. }
  218. if info.IndexServerAddress == "" {
  219. info.IndexServerAddress = registry.IndexServer
  220. }
  221. var needPull []types.ServiceConfig
  222. for _, service := range project.Services {
  223. if service.Image == "" {
  224. continue
  225. }
  226. switch service.PullPolicy {
  227. case "", types.PullPolicyMissing, types.PullPolicyIfNotPresent:
  228. if _, ok := images[service.Image]; ok {
  229. continue
  230. }
  231. case types.PullPolicyNever, types.PullPolicyBuild:
  232. continue
  233. case types.PullPolicyAlways:
  234. // force pull
  235. }
  236. needPull = append(needPull, service)
  237. }
  238. if len(needPull) == 0 {
  239. return nil
  240. }
  241. return progress.Run(ctx, func(ctx context.Context) error {
  242. w := progress.ContextWriter(ctx)
  243. eg, ctx := errgroup.WithContext(ctx)
  244. eg.SetLimit(s.maxConcurrency)
  245. pulledImages := make([]string, len(needPull))
  246. for i, service := range needPull {
  247. i, service := i, service
  248. eg.Go(func() error {
  249. id, err := s.pullServiceImage(ctx, service, info, s.configFile(), w, quietPull, project.Environment["DOCKER_DEFAULT_PLATFORM"])
  250. pulledImages[i] = id
  251. if err != nil && isServiceImageToBuild(service, project.Services) {
  252. // image can be built, so we can ignore pull failure
  253. return nil
  254. }
  255. return err
  256. })
  257. }
  258. err := eg.Wait()
  259. for i, service := range needPull {
  260. if pulledImages[i] != "" {
  261. images[service.Image] = pulledImages[i]
  262. }
  263. }
  264. return err
  265. })
  266. }
  267. func isServiceImageToBuild(service types.ServiceConfig, services []types.ServiceConfig) bool {
  268. if service.Build != nil {
  269. return true
  270. }
  271. for _, depService := range services {
  272. if depService.Image == service.Image && depService.Build != nil {
  273. return true
  274. }
  275. }
  276. return false
  277. }
  278. func toPullProgressEvent(parent string, jm jsonmessage.JSONMessage, w progress.Writer) {
  279. if jm.ID == "" || jm.Progress == nil {
  280. return
  281. }
  282. var (
  283. text string
  284. status = progress.Working
  285. )
  286. text = jm.Progress.String()
  287. if jm.Status == "Pull complete" ||
  288. jm.Status == "Already exists" ||
  289. strings.Contains(jm.Status, "Image is up to date") ||
  290. strings.Contains(jm.Status, "Downloaded newer image") {
  291. status = progress.Done
  292. }
  293. if jm.Error != nil {
  294. status = progress.Error
  295. text = jm.Error.Message
  296. }
  297. w.Event(progress.Event{
  298. ID: jm.ID,
  299. ParentID: parent,
  300. Text: jm.Status,
  301. Status: status,
  302. StatusText: text,
  303. })
  304. }