pull.go 8.8 KB

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