pull.go 9.0 KB

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