pull.go 9.9 KB

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