pull.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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/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. for i, service := range project.Services {
  55. i, service := i, service
  56. if service.Image == "" {
  57. w.Event(progress.Event{
  58. ID: service.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: service.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: service.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: service.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: service.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. eg.Go(func() error {
  100. _, err := s.pullServiceImage(ctx, service, s.configFile(), w, false, project.Environment["DOCKER_DEFAULT_PLATFORM"])
  101. if err != nil {
  102. pullErrors[i] = err
  103. if service.Build != nil {
  104. mustBuild = append(mustBuild, service.Name)
  105. }
  106. if !opts.IgnoreFailures && service.Build == nil {
  107. if s.dryRun {
  108. w.Event(progress.Event{
  109. ID: service.Name,
  110. Status: progress.Error,
  111. Text: fmt.Sprintf(" - Pull error for image: %s", service.Image),
  112. })
  113. }
  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,
  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, 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 errors.Is(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, configFile driver.Auth) (string, error) {
  214. repoInfo, err := registry.ParseRepositoryInfo(ref)
  215. if err != nil {
  216. return "", err
  217. }
  218. key := registry.GetAuthConfigKey(repoInfo.Index)
  219. authConfig, err := configFile.GetAuthConfig(key)
  220. if err != nil {
  221. return "", err
  222. }
  223. buf, err := json.Marshal(authConfig)
  224. if err != nil {
  225. return "", err
  226. }
  227. return base64.URLEncoding.EncodeToString(buf), nil
  228. }
  229. func (s *composeService) pullRequiredImages(ctx context.Context, project *types.Project, images map[string]string, quietPull bool) error {
  230. var needPull types.Services
  231. for _, service := range project.Services {
  232. if service.Image == "" {
  233. continue
  234. }
  235. switch service.PullPolicy {
  236. case "", types.PullPolicyMissing, types.PullPolicyIfNotPresent:
  237. if _, ok := images[service.Image]; ok {
  238. continue
  239. }
  240. case types.PullPolicyNever, types.PullPolicyBuild:
  241. continue
  242. case types.PullPolicyAlways:
  243. // force pull
  244. }
  245. needPull = append(needPull, service)
  246. }
  247. if len(needPull) == 0 {
  248. return nil
  249. }
  250. return progress.Run(ctx, func(ctx context.Context) error {
  251. w := progress.ContextWriter(ctx)
  252. eg, ctx := errgroup.WithContext(ctx)
  253. eg.SetLimit(s.maxConcurrency)
  254. pulledImages := make([]string, len(needPull))
  255. for i, service := range needPull {
  256. i, service := i, service
  257. eg.Go(func() error {
  258. id, err := s.pullServiceImage(ctx, service, s.configFile(), w, quietPull, project.Environment["DOCKER_DEFAULT_PLATFORM"])
  259. pulledImages[i] = id
  260. if err != nil && isServiceImageToBuild(service, project.Services) {
  261. // image can be built, so we can ignore pull failure
  262. return nil
  263. }
  264. return err
  265. })
  266. }
  267. err := eg.Wait()
  268. for i, service := range needPull {
  269. if pulledImages[i] != "" {
  270. images[service.Image] = pulledImages[i]
  271. }
  272. }
  273. return err
  274. }, s.stdinfo())
  275. }
  276. func isServiceImageToBuild(service types.ServiceConfig, services types.Services) bool {
  277. if service.Build != nil {
  278. return true
  279. }
  280. if service.Image == "" {
  281. // N.B. this should be impossible as service must have either `build` or `image` (or both)
  282. return false
  283. }
  284. // look through the other services to see if another has a build definition for the same
  285. // image name
  286. for _, svc := range services {
  287. if svc.Image == service.Image && svc.Build != nil {
  288. return true
  289. }
  290. }
  291. return false
  292. }
  293. const (
  294. PreparingPhase = "Preparing"
  295. WaitingPhase = "Waiting"
  296. PullingFsPhase = "Pulling fs layer"
  297. DownloadingPhase = "Downloading"
  298. DownloadCompletePhase = "Download complete"
  299. ExtractingPhase = "Extracting"
  300. VerifyingChecksumPhase = "Verifying Checksum"
  301. AlreadyExistsPhase = "Already exists"
  302. PullCompletePhase = "Pull complete"
  303. )
  304. func toPullProgressEvent(parent string, jm jsonmessage.JSONMessage, w progress.Writer) {
  305. if jm.ID == "" || jm.Progress == nil {
  306. return
  307. }
  308. var (
  309. text string
  310. total int64
  311. percent int
  312. current int64
  313. status = progress.Working
  314. )
  315. text = jm.Progress.String()
  316. switch jm.Status {
  317. case PreparingPhase, WaitingPhase, PullingFsPhase:
  318. percent = 0
  319. case DownloadingPhase, ExtractingPhase, VerifyingChecksumPhase:
  320. if jm.Progress != nil {
  321. current = jm.Progress.Current
  322. total = jm.Progress.Total
  323. if jm.Progress.Total > 0 {
  324. percent = int(jm.Progress.Current * 100 / jm.Progress.Total)
  325. }
  326. }
  327. case DownloadCompletePhase, AlreadyExistsPhase, PullCompletePhase:
  328. status = progress.Done
  329. percent = 100
  330. }
  331. if strings.Contains(jm.Status, "Image is up to date") ||
  332. strings.Contains(jm.Status, "Downloaded newer image") {
  333. status = progress.Done
  334. percent = 100
  335. }
  336. if jm.Error != nil {
  337. status = progress.Error
  338. text = jm.Error.Message
  339. }
  340. w.Event(progress.Event{
  341. ID: jm.ID,
  342. ParentID: parent,
  343. Current: current,
  344. Total: total,
  345. Percent: percent,
  346. Text: jm.Status,
  347. Status: status,
  348. StatusText: text,
  349. })
  350. }