pull_v1.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. package distribution
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "net"
  8. "net/url"
  9. "os"
  10. "strings"
  11. "time"
  12. "github.com/docker/distribution/reference"
  13. "github.com/docker/distribution/registry/client/auth"
  14. "github.com/docker/distribution/registry/client/transport"
  15. "github.com/docker/docker/distribution/metadata"
  16. "github.com/docker/docker/distribution/xfer"
  17. "github.com/docker/docker/dockerversion"
  18. "github.com/docker/docker/image"
  19. "github.com/docker/docker/image/v1"
  20. "github.com/docker/docker/layer"
  21. "github.com/docker/docker/pkg/ioutils"
  22. "github.com/docker/docker/pkg/progress"
  23. "github.com/docker/docker/pkg/stringid"
  24. "github.com/docker/docker/registry"
  25. "github.com/sirupsen/logrus"
  26. "golang.org/x/net/context"
  27. )
  28. type v1Puller struct {
  29. v1IDService *metadata.V1IDService
  30. endpoint registry.APIEndpoint
  31. config *ImagePullConfig
  32. repoInfo *registry.RepositoryInfo
  33. session *registry.Session
  34. }
  35. func (p *v1Puller) Pull(ctx context.Context, ref reference.Named, platform string) error {
  36. if _, isCanonical := ref.(reference.Canonical); isCanonical {
  37. // Allowing fallback, because HTTPS v1 is before HTTP v2
  38. return fallbackError{err: ErrNoSupport{Err: errors.New("Cannot pull by digest with v1 registry")}}
  39. }
  40. tlsConfig, err := p.config.RegistryService.TLSConfig(p.repoInfo.Index.Name)
  41. if err != nil {
  42. return err
  43. }
  44. // Adds Docker-specific headers as well as user-specified headers (metaHeaders)
  45. tr := transport.NewTransport(
  46. // TODO(tiborvass): was ReceiveTimeout
  47. registry.NewTransport(tlsConfig),
  48. registry.Headers(dockerversion.DockerUserAgent(ctx), p.config.MetaHeaders)...,
  49. )
  50. client := registry.HTTPClient(tr)
  51. v1Endpoint := p.endpoint.ToV1Endpoint(dockerversion.DockerUserAgent(ctx), p.config.MetaHeaders)
  52. p.session, err = registry.NewSession(client, p.config.AuthConfig, v1Endpoint)
  53. if err != nil {
  54. // TODO(dmcgowan): Check if should fallback
  55. logrus.Debugf("Fallback from error: %s", err)
  56. return fallbackError{err: err}
  57. }
  58. if err := p.pullRepository(ctx, ref); err != nil {
  59. // TODO(dmcgowan): Check if should fallback
  60. return err
  61. }
  62. progress.Message(p.config.ProgressOutput, "", p.repoInfo.Name.Name()+": this image was pulled from a legacy registry. Important: This registry version will not be supported in future versions of docker.")
  63. return nil
  64. }
  65. // Note use auth.Scope rather than reference.Named due to this warning causing Jenkins CI to fail:
  66. // warning: ref can be github.com/docker/docker/vendor/github.com/docker/distribution/registry/client/auth.Scope (interfacer)
  67. func (p *v1Puller) pullRepository(ctx context.Context, ref auth.Scope) error {
  68. progress.Message(p.config.ProgressOutput, "", "Pulling repository "+p.repoInfo.Name.Name())
  69. tagged, isTagged := ref.(reference.NamedTagged)
  70. repoData, err := p.session.GetRepositoryData(p.repoInfo.Name)
  71. if err != nil {
  72. if strings.Contains(err.Error(), "HTTP code: 404") {
  73. if isTagged {
  74. return fmt.Errorf("Error: image %s:%s not found", reference.Path(p.repoInfo.Name), tagged.Tag())
  75. }
  76. return fmt.Errorf("Error: image %s not found", reference.Path(p.repoInfo.Name))
  77. }
  78. // Unexpected HTTP error
  79. return err
  80. }
  81. logrus.Debug("Retrieving the tag list")
  82. var tagsList map[string]string
  83. if !isTagged {
  84. tagsList, err = p.session.GetRemoteTags(repoData.Endpoints, p.repoInfo.Name)
  85. } else {
  86. var tagID string
  87. tagsList = make(map[string]string)
  88. tagID, err = p.session.GetRemoteTag(repoData.Endpoints, p.repoInfo.Name, tagged.Tag())
  89. if err == registry.ErrRepoNotFound {
  90. return fmt.Errorf("Tag %s not found in repository %s", tagged.Tag(), p.repoInfo.Name.Name())
  91. }
  92. tagsList[tagged.Tag()] = tagID
  93. }
  94. if err != nil {
  95. logrus.Errorf("unable to get remote tags: %s", err)
  96. return err
  97. }
  98. for tag, id := range tagsList {
  99. repoData.ImgList[id] = &registry.ImgData{
  100. ID: id,
  101. Tag: tag,
  102. Checksum: "",
  103. }
  104. }
  105. layersDownloaded := false
  106. for _, imgData := range repoData.ImgList {
  107. if isTagged && imgData.Tag != tagged.Tag() {
  108. continue
  109. }
  110. err := p.downloadImage(ctx, repoData, imgData, &layersDownloaded)
  111. if err != nil {
  112. return err
  113. }
  114. }
  115. writeStatus(reference.FamiliarString(ref), p.config.ProgressOutput, layersDownloaded)
  116. return nil
  117. }
  118. func (p *v1Puller) downloadImage(ctx context.Context, repoData *registry.RepositoryData, img *registry.ImgData, layersDownloaded *bool) error {
  119. if img.Tag == "" {
  120. logrus.Debugf("Image (id: %s) present in this repository but untagged, skipping", img.ID)
  121. return nil
  122. }
  123. localNameRef, err := reference.WithTag(p.repoInfo.Name, img.Tag)
  124. if err != nil {
  125. retErr := fmt.Errorf("Image (id: %s) has invalid tag: %s", img.ID, img.Tag)
  126. logrus.Debug(retErr.Error())
  127. return retErr
  128. }
  129. if err := v1.ValidateID(img.ID); err != nil {
  130. return err
  131. }
  132. progress.Updatef(p.config.ProgressOutput, stringid.TruncateID(img.ID), "Pulling image (%s) from %s", img.Tag, p.repoInfo.Name.Name())
  133. success := false
  134. var lastErr error
  135. for _, ep := range p.repoInfo.Index.Mirrors {
  136. ep += "v1/"
  137. progress.Updatef(p.config.ProgressOutput, stringid.TruncateID(img.ID), fmt.Sprintf("Pulling image (%s) from %s, mirror: %s", img.Tag, p.repoInfo.Name.Name(), ep))
  138. if err = p.pullImage(ctx, img.ID, ep, localNameRef, layersDownloaded); err != nil {
  139. // Don't report errors when pulling from mirrors.
  140. logrus.Debugf("Error pulling image (%s) from %s, mirror: %s, %s", img.Tag, p.repoInfo.Name.Name(), ep, err)
  141. continue
  142. }
  143. success = true
  144. break
  145. }
  146. if !success {
  147. for _, ep := range repoData.Endpoints {
  148. progress.Updatef(p.config.ProgressOutput, stringid.TruncateID(img.ID), "Pulling image (%s) from %s, endpoint: %s", img.Tag, p.repoInfo.Name.Name(), ep)
  149. if err = p.pullImage(ctx, img.ID, ep, localNameRef, layersDownloaded); err != nil {
  150. // It's not ideal that only the last error is returned, it would be better to concatenate the errors.
  151. // As the error is also given to the output stream the user will see the error.
  152. lastErr = err
  153. progress.Updatef(p.config.ProgressOutput, stringid.TruncateID(img.ID), "Error pulling image (%s) from %s, endpoint: %s, %s", img.Tag, p.repoInfo.Name.Name(), ep, err)
  154. continue
  155. }
  156. success = true
  157. break
  158. }
  159. }
  160. if !success {
  161. err := fmt.Errorf("Error pulling image (%s) from %s, %v", img.Tag, p.repoInfo.Name.Name(), lastErr)
  162. progress.Update(p.config.ProgressOutput, stringid.TruncateID(img.ID), err.Error())
  163. return err
  164. }
  165. return nil
  166. }
  167. func (p *v1Puller) pullImage(ctx context.Context, v1ID, endpoint string, localNameRef reference.Named, layersDownloaded *bool) (err error) {
  168. var history []string
  169. history, err = p.session.GetRemoteHistory(v1ID, endpoint)
  170. if err != nil {
  171. return err
  172. }
  173. if len(history) < 1 {
  174. return fmt.Errorf("empty history for image %s", v1ID)
  175. }
  176. progress.Update(p.config.ProgressOutput, stringid.TruncateID(v1ID), "Pulling dependent layers")
  177. var (
  178. descriptors []xfer.DownloadDescriptor
  179. newHistory []image.History
  180. imgJSON []byte
  181. imgSize int64
  182. )
  183. // Iterate over layers, in order from bottom-most to top-most. Download
  184. // config for all layers and create descriptors.
  185. for i := len(history) - 1; i >= 0; i-- {
  186. v1LayerID := history[i]
  187. imgJSON, imgSize, err = p.downloadLayerConfig(v1LayerID, endpoint)
  188. if err != nil {
  189. return err
  190. }
  191. // Create a new-style config from the legacy configs
  192. h, err := v1.HistoryFromConfig(imgJSON, false)
  193. if err != nil {
  194. return err
  195. }
  196. newHistory = append(newHistory, h)
  197. layerDescriptor := &v1LayerDescriptor{
  198. v1LayerID: v1LayerID,
  199. indexName: p.repoInfo.Index.Name,
  200. endpoint: endpoint,
  201. v1IDService: p.v1IDService,
  202. layersDownloaded: layersDownloaded,
  203. layerSize: imgSize,
  204. session: p.session,
  205. }
  206. descriptors = append(descriptors, layerDescriptor)
  207. }
  208. rootFS := image.NewRootFS()
  209. resultRootFS, release, err := p.config.DownloadManager.Download(ctx, *rootFS, "", descriptors, p.config.ProgressOutput)
  210. if err != nil {
  211. return err
  212. }
  213. defer release()
  214. config, err := v1.MakeConfigFromV1Config(imgJSON, &resultRootFS, newHistory)
  215. if err != nil {
  216. return err
  217. }
  218. imageID, err := p.config.ImageStore.Put(config)
  219. if err != nil {
  220. return err
  221. }
  222. if p.config.ReferenceStore != nil {
  223. if err := p.config.ReferenceStore.AddTag(localNameRef, imageID, true); err != nil {
  224. return err
  225. }
  226. }
  227. return nil
  228. }
  229. func (p *v1Puller) downloadLayerConfig(v1LayerID, endpoint string) (imgJSON []byte, imgSize int64, err error) {
  230. progress.Update(p.config.ProgressOutput, stringid.TruncateID(v1LayerID), "Pulling metadata")
  231. retries := 5
  232. for j := 1; j <= retries; j++ {
  233. imgJSON, imgSize, err := p.session.GetRemoteImageJSON(v1LayerID, endpoint)
  234. if err != nil && j == retries {
  235. progress.Update(p.config.ProgressOutput, stringid.TruncateID(v1LayerID), "Error pulling layer metadata")
  236. return nil, 0, err
  237. } else if err != nil {
  238. time.Sleep(time.Duration(j) * 500 * time.Millisecond)
  239. continue
  240. }
  241. return imgJSON, imgSize, nil
  242. }
  243. // not reached
  244. return nil, 0, nil
  245. }
  246. type v1LayerDescriptor struct {
  247. v1LayerID string
  248. indexName string
  249. endpoint string
  250. v1IDService *metadata.V1IDService
  251. layersDownloaded *bool
  252. layerSize int64
  253. session *registry.Session
  254. tmpFile *os.File
  255. }
  256. func (ld *v1LayerDescriptor) Key() string {
  257. return "v1:" + ld.v1LayerID
  258. }
  259. func (ld *v1LayerDescriptor) ID() string {
  260. return stringid.TruncateID(ld.v1LayerID)
  261. }
  262. func (ld *v1LayerDescriptor) DiffID() (layer.DiffID, error) {
  263. return ld.v1IDService.Get(ld.v1LayerID, ld.indexName)
  264. }
  265. func (ld *v1LayerDescriptor) Download(ctx context.Context, progressOutput progress.Output) (io.ReadCloser, int64, error) {
  266. progress.Update(progressOutput, ld.ID(), "Pulling fs layer")
  267. layerReader, err := ld.session.GetRemoteImageLayer(ld.v1LayerID, ld.endpoint, ld.layerSize)
  268. if err != nil {
  269. progress.Update(progressOutput, ld.ID(), "Error pulling dependent layers")
  270. if uerr, ok := err.(*url.Error); ok {
  271. err = uerr.Err
  272. }
  273. if terr, ok := err.(net.Error); ok && terr.Timeout() {
  274. return nil, 0, err
  275. }
  276. return nil, 0, xfer.DoNotRetry{Err: err}
  277. }
  278. *ld.layersDownloaded = true
  279. ld.tmpFile, err = ioutil.TempFile("", "GetImageBlob")
  280. if err != nil {
  281. layerReader.Close()
  282. return nil, 0, err
  283. }
  284. reader := progress.NewProgressReader(ioutils.NewCancelReadCloser(ctx, layerReader), progressOutput, ld.layerSize, ld.ID(), "Downloading")
  285. defer reader.Close()
  286. _, err = io.Copy(ld.tmpFile, reader)
  287. if err != nil {
  288. ld.Close()
  289. return nil, 0, err
  290. }
  291. progress.Update(progressOutput, ld.ID(), "Download complete")
  292. logrus.Debugf("Downloaded %s to tempfile %s", ld.ID(), ld.tmpFile.Name())
  293. ld.tmpFile.Seek(0, 0)
  294. // hand off the temporary file to the download manager, so it will only
  295. // be closed once
  296. tmpFile := ld.tmpFile
  297. ld.tmpFile = nil
  298. return ioutils.NewReadCloserWrapper(tmpFile, func() error {
  299. tmpFile.Close()
  300. err := os.RemoveAll(tmpFile.Name())
  301. if err != nil {
  302. logrus.Errorf("Failed to remove temp file: %s", tmpFile.Name())
  303. }
  304. return err
  305. }), ld.layerSize, nil
  306. }
  307. func (ld *v1LayerDescriptor) Close() {
  308. if ld.tmpFile != nil {
  309. ld.tmpFile.Close()
  310. if err := os.RemoveAll(ld.tmpFile.Name()); err != nil {
  311. logrus.Errorf("Failed to remove temp file: %s", ld.tmpFile.Name())
  312. }
  313. ld.tmpFile = nil
  314. }
  315. }
  316. func (ld *v1LayerDescriptor) Registered(diffID layer.DiffID) {
  317. // Cache mapping from this layer's DiffID to the blobsum
  318. ld.v1IDService.Set(ld.v1LayerID, ld.indexName, diffID)
  319. }