pull.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. "github.com/docker/docker/api/types/image"
  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, image.PullOptions{
  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. StatusText: err.Error(),
  181. })
  182. return "", WrapCategorisedComposeError(err, PullFailure)
  183. }
  184. if err != nil {
  185. w.Event(progress.Event{
  186. ID: service.Name,
  187. Status: progress.Error,
  188. Text: "Error",
  189. StatusText: err.Error(),
  190. })
  191. return "", WrapCategorisedComposeError(err, PullFailure)
  192. }
  193. dec := json.NewDecoder(stream)
  194. for {
  195. var jm jsonmessage.JSONMessage
  196. if err := dec.Decode(&jm); err != nil {
  197. if errors.Is(err, io.EOF) {
  198. break
  199. }
  200. return "", WrapCategorisedComposeError(err, PullFailure)
  201. }
  202. if jm.Error != nil {
  203. return "", WrapCategorisedComposeError(errors.New(jm.Error.Message), PullFailure)
  204. }
  205. if !quietPull {
  206. toPullProgressEvent(service.Name, jm, w)
  207. }
  208. }
  209. w.Event(progress.Event{
  210. ID: service.Name,
  211. Status: progress.Done,
  212. Text: "Pulled",
  213. })
  214. inspected, _, err := s.apiClient().ImageInspectWithRaw(ctx, service.Image)
  215. if err != nil {
  216. return "", err
  217. }
  218. return inspected.ID, nil
  219. }
  220. // ImageDigestResolver creates a func able to resolve image digest from a docker ref,
  221. func ImageDigestResolver(ctx context.Context, file *configfile.ConfigFile, apiClient client.APIClient) func(named reference.Named) (digest.Digest, error) {
  222. return func(named reference.Named) (digest.Digest, error) {
  223. auth, err := encodedAuth(named, file)
  224. if err != nil {
  225. return "", err
  226. }
  227. inspect, err := apiClient.DistributionInspect(ctx, named.String(), auth)
  228. if err != nil {
  229. return "", err
  230. }
  231. return inspect.Descriptor.Digest, nil
  232. }
  233. }
  234. func encodedAuth(ref reference.Named, configFile driver.Auth) (string, error) {
  235. repoInfo, err := registry.ParseRepositoryInfo(ref)
  236. if err != nil {
  237. return "", err
  238. }
  239. key := registry.GetAuthConfigKey(repoInfo.Index)
  240. authConfig, err := configFile.GetAuthConfig(key)
  241. if err != nil {
  242. return "", err
  243. }
  244. buf, err := json.Marshal(authConfig)
  245. if err != nil {
  246. return "", err
  247. }
  248. return base64.URLEncoding.EncodeToString(buf), nil
  249. }
  250. func (s *composeService) pullRequiredImages(ctx context.Context, project *types.Project, images map[string]string, quietPull bool) error {
  251. var needPull []types.ServiceConfig
  252. for _, service := range project.Services {
  253. if service.Image == "" {
  254. continue
  255. }
  256. switch service.PullPolicy {
  257. case "", types.PullPolicyMissing, types.PullPolicyIfNotPresent:
  258. if _, ok := images[service.Image]; ok {
  259. continue
  260. }
  261. case types.PullPolicyNever, types.PullPolicyBuild:
  262. continue
  263. case types.PullPolicyAlways:
  264. // force pull
  265. }
  266. needPull = append(needPull, service)
  267. }
  268. if len(needPull) == 0 {
  269. return nil
  270. }
  271. return progress.Run(ctx, func(ctx context.Context) error {
  272. w := progress.ContextWriter(ctx)
  273. eg, ctx := errgroup.WithContext(ctx)
  274. eg.SetLimit(s.maxConcurrency)
  275. pulledImages := make([]string, len(needPull))
  276. for i, service := range needPull {
  277. i, service := i, service
  278. eg.Go(func() error {
  279. id, err := s.pullServiceImage(ctx, service, s.configFile(), w, quietPull, project.Environment["DOCKER_DEFAULT_PLATFORM"])
  280. pulledImages[i] = id
  281. if err != nil && isServiceImageToBuild(service, project.Services) {
  282. // image can be built, so we can ignore pull failure
  283. return nil
  284. }
  285. return err
  286. })
  287. }
  288. err := eg.Wait()
  289. for i, service := range needPull {
  290. if pulledImages[i] != "" {
  291. images[service.Image] = pulledImages[i]
  292. }
  293. }
  294. return err
  295. }, s.stdinfo())
  296. }
  297. func isServiceImageToBuild(service types.ServiceConfig, services types.Services) bool {
  298. if service.Build != nil {
  299. return true
  300. }
  301. if service.Image == "" {
  302. // N.B. this should be impossible as service must have either `build` or `image` (or both)
  303. return false
  304. }
  305. // look through the other services to see if another has a build definition for the same
  306. // image name
  307. for _, svc := range services {
  308. if svc.Image == service.Image && svc.Build != nil {
  309. return true
  310. }
  311. }
  312. return false
  313. }
  314. const (
  315. PreparingPhase = "Preparing"
  316. WaitingPhase = "Waiting"
  317. PullingFsPhase = "Pulling fs layer"
  318. DownloadingPhase = "Downloading"
  319. DownloadCompletePhase = "Download complete"
  320. ExtractingPhase = "Extracting"
  321. VerifyingChecksumPhase = "Verifying Checksum"
  322. AlreadyExistsPhase = "Already exists"
  323. PullCompletePhase = "Pull complete"
  324. )
  325. func toPullProgressEvent(parent string, jm jsonmessage.JSONMessage, w progress.Writer) {
  326. if jm.ID == "" || jm.Progress == nil {
  327. return
  328. }
  329. var (
  330. text string
  331. total int64
  332. percent int
  333. current int64
  334. status = progress.Working
  335. )
  336. text = jm.Progress.String()
  337. switch jm.Status {
  338. case PreparingPhase, WaitingPhase, PullingFsPhase:
  339. percent = 0
  340. case DownloadingPhase, ExtractingPhase, VerifyingChecksumPhase:
  341. if jm.Progress != nil {
  342. current = jm.Progress.Current
  343. total = jm.Progress.Total
  344. if jm.Progress.Total > 0 {
  345. percent = int(jm.Progress.Current * 100 / jm.Progress.Total)
  346. }
  347. }
  348. case DownloadCompletePhase, AlreadyExistsPhase, PullCompletePhase:
  349. status = progress.Done
  350. percent = 100
  351. }
  352. if strings.Contains(jm.Status, "Image is up to date") ||
  353. strings.Contains(jm.Status, "Downloaded newer image") {
  354. status = progress.Done
  355. percent = 100
  356. }
  357. if jm.Error != nil {
  358. status = progress.Error
  359. text = jm.Error.Message
  360. }
  361. w.Event(progress.Event{
  362. ID: jm.ID,
  363. ParentID: parent,
  364. Current: current,
  365. Total: total,
  366. Percent: percent,
  367. Text: jm.Status,
  368. Status: status,
  369. StatusText: text,
  370. })
  371. }