pull_v1.go 11 KB

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