pull.go 8.5 KB

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