pull_v1.go 11 KB

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