pull.go 12 KB

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