pull.go 11 KB

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