push_v1.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. package distribution
  2. import (
  3. "fmt"
  4. "sync"
  5. "github.com/docker/distribution/reference"
  6. "github.com/docker/distribution/registry/client/transport"
  7. "github.com/docker/docker/distribution/metadata"
  8. "github.com/docker/docker/dockerversion"
  9. "github.com/docker/docker/image"
  10. "github.com/docker/docker/image/v1"
  11. "github.com/docker/docker/layer"
  12. "github.com/docker/docker/pkg/ioutils"
  13. "github.com/docker/docker/pkg/progress"
  14. "github.com/docker/docker/pkg/stringid"
  15. "github.com/docker/docker/registry"
  16. "github.com/opencontainers/go-digest"
  17. "github.com/sirupsen/logrus"
  18. "golang.org/x/net/context"
  19. )
  20. type v1Pusher struct {
  21. v1IDService *metadata.V1IDService
  22. endpoint registry.APIEndpoint
  23. ref reference.Named
  24. repoInfo *registry.RepositoryInfo
  25. config *ImagePushConfig
  26. session *registry.Session
  27. }
  28. func (p *v1Pusher) Push(ctx context.Context) error {
  29. tlsConfig, err := p.config.RegistryService.TLSConfig(p.repoInfo.Index.Name)
  30. if err != nil {
  31. return err
  32. }
  33. // Adds Docker-specific headers as well as user-specified headers (metaHeaders)
  34. tr := transport.NewTransport(
  35. // TODO(tiborvass): was NoTimeout
  36. registry.NewTransport(tlsConfig),
  37. registry.DockerHeaders(dockerversion.DockerUserAgent(ctx), p.config.MetaHeaders)...,
  38. )
  39. client := registry.HTTPClient(tr)
  40. v1Endpoint := p.endpoint.ToV1Endpoint(dockerversion.DockerUserAgent(ctx), p.config.MetaHeaders)
  41. p.session, err = registry.NewSession(client, p.config.AuthConfig, v1Endpoint)
  42. if err != nil {
  43. // TODO(dmcgowan): Check if should fallback
  44. return fallbackError{err: err}
  45. }
  46. if err := p.pushRepository(ctx); err != nil {
  47. // TODO(dmcgowan): Check if should fallback
  48. return err
  49. }
  50. return nil
  51. }
  52. // v1Image exposes the configuration, filesystem layer ID, and a v1 ID for an
  53. // image being pushed to a v1 registry.
  54. type v1Image interface {
  55. Config() []byte
  56. Layer() layer.Layer
  57. V1ID() string
  58. }
  59. type v1ImageCommon struct {
  60. layer layer.Layer
  61. config []byte
  62. v1ID string
  63. }
  64. func (common *v1ImageCommon) Config() []byte {
  65. return common.config
  66. }
  67. func (common *v1ImageCommon) V1ID() string {
  68. return common.v1ID
  69. }
  70. func (common *v1ImageCommon) Layer() layer.Layer {
  71. return common.layer
  72. }
  73. // v1TopImage defines a runnable (top layer) image being pushed to a v1
  74. // registry.
  75. type v1TopImage struct {
  76. v1ImageCommon
  77. imageID image.ID
  78. }
  79. func newV1TopImage(imageID image.ID, img *image.Image, l layer.Layer, parent *v1DependencyImage) (*v1TopImage, error) {
  80. v1ID := imageID.Digest().Hex()
  81. parentV1ID := ""
  82. if parent != nil {
  83. parentV1ID = parent.V1ID()
  84. }
  85. config, err := v1.MakeV1ConfigFromConfig(img, v1ID, parentV1ID, false)
  86. if err != nil {
  87. return nil, err
  88. }
  89. return &v1TopImage{
  90. v1ImageCommon: v1ImageCommon{
  91. v1ID: v1ID,
  92. config: config,
  93. layer: l,
  94. },
  95. imageID: imageID,
  96. }, nil
  97. }
  98. // v1DependencyImage defines a dependency layer being pushed to a v1 registry.
  99. type v1DependencyImage struct {
  100. v1ImageCommon
  101. }
  102. func newV1DependencyImage(l layer.Layer, parent *v1DependencyImage) *v1DependencyImage {
  103. v1ID := digest.Digest(l.ChainID()).Hex()
  104. var config string
  105. if parent != nil {
  106. config = fmt.Sprintf(`{"id":"%s","parent":"%s"}`, v1ID, parent.V1ID())
  107. } else {
  108. config = fmt.Sprintf(`{"id":"%s"}`, v1ID)
  109. }
  110. return &v1DependencyImage{
  111. v1ImageCommon: v1ImageCommon{
  112. v1ID: v1ID,
  113. config: []byte(config),
  114. layer: l,
  115. },
  116. }
  117. }
  118. // Retrieve the all the images to be uploaded in the correct order
  119. func (p *v1Pusher) getImageList() (imageList []v1Image, tagsByImage map[image.ID][]string, referencedLayers []PushLayer, err error) {
  120. tagsByImage = make(map[image.ID][]string)
  121. // Ignore digest references
  122. if _, isCanonical := p.ref.(reference.Canonical); isCanonical {
  123. return
  124. }
  125. tagged, isTagged := p.ref.(reference.NamedTagged)
  126. if isTagged {
  127. // Push a specific tag
  128. var imgID image.ID
  129. var dgst digest.Digest
  130. dgst, err = p.config.ReferenceStore.Get(p.ref)
  131. if err != nil {
  132. return
  133. }
  134. imgID = image.IDFromDigest(dgst)
  135. imageList, err = p.imageListForTag(imgID, nil, &referencedLayers)
  136. if err != nil {
  137. return
  138. }
  139. tagsByImage[imgID] = []string{tagged.Tag()}
  140. return
  141. }
  142. imagesSeen := make(map[digest.Digest]struct{})
  143. dependenciesSeen := make(map[layer.ChainID]*v1DependencyImage)
  144. associations := p.config.ReferenceStore.ReferencesByName(p.ref)
  145. for _, association := range associations {
  146. if tagged, isTagged = association.Ref.(reference.NamedTagged); !isTagged {
  147. // Ignore digest references.
  148. continue
  149. }
  150. imgID := image.IDFromDigest(association.ID)
  151. tagsByImage[imgID] = append(tagsByImage[imgID], tagged.Tag())
  152. if _, present := imagesSeen[association.ID]; present {
  153. // Skip generating image list for already-seen image
  154. continue
  155. }
  156. imagesSeen[association.ID] = struct{}{}
  157. imageListForThisTag, err := p.imageListForTag(imgID, dependenciesSeen, &referencedLayers)
  158. if err != nil {
  159. return nil, nil, nil, err
  160. }
  161. // append to main image list
  162. imageList = append(imageList, imageListForThisTag...)
  163. }
  164. if len(imageList) == 0 {
  165. return nil, nil, nil, fmt.Errorf("No images found for the requested repository / tag")
  166. }
  167. logrus.Debugf("Image list: %v", imageList)
  168. logrus.Debugf("Tags by image: %v", tagsByImage)
  169. return
  170. }
  171. func (p *v1Pusher) imageListForTag(imgID image.ID, dependenciesSeen map[layer.ChainID]*v1DependencyImage, referencedLayers *[]PushLayer) (imageListForThisTag []v1Image, err error) {
  172. ics, ok := p.config.ImageStore.(*imageConfigStore)
  173. if !ok {
  174. return nil, fmt.Errorf("only image store images supported for v1 push")
  175. }
  176. img, err := ics.Store.Get(imgID)
  177. if err != nil {
  178. return nil, err
  179. }
  180. topLayerID := img.RootFS.ChainID()
  181. pl, err := p.config.LayerStore.Get(topLayerID)
  182. *referencedLayers = append(*referencedLayers, pl)
  183. if err != nil {
  184. return nil, fmt.Errorf("failed to get top layer from image: %v", err)
  185. }
  186. // V1 push is deprecated, only support existing layerstore layers
  187. lsl, ok := pl.(*storeLayer)
  188. if !ok {
  189. return nil, fmt.Errorf("only layer store layers supported for v1 push")
  190. }
  191. l := lsl.Layer
  192. dependencyImages, parent := generateDependencyImages(l.Parent(), dependenciesSeen)
  193. topImage, err := newV1TopImage(imgID, img, l, parent)
  194. if err != nil {
  195. return nil, err
  196. }
  197. imageListForThisTag = append(dependencyImages, topImage)
  198. return
  199. }
  200. func generateDependencyImages(l layer.Layer, dependenciesSeen map[layer.ChainID]*v1DependencyImage) (imageListForThisTag []v1Image, parent *v1DependencyImage) {
  201. if l == nil {
  202. return nil, nil
  203. }
  204. imageListForThisTag, parent = generateDependencyImages(l.Parent(), dependenciesSeen)
  205. if dependenciesSeen != nil {
  206. if dependencyImage, present := dependenciesSeen[l.ChainID()]; present {
  207. // This layer is already on the list, we can ignore it
  208. // and all its parents.
  209. return imageListForThisTag, dependencyImage
  210. }
  211. }
  212. dependencyImage := newV1DependencyImage(l, parent)
  213. imageListForThisTag = append(imageListForThisTag, dependencyImage)
  214. if dependenciesSeen != nil {
  215. dependenciesSeen[l.ChainID()] = dependencyImage
  216. }
  217. return imageListForThisTag, dependencyImage
  218. }
  219. // createImageIndex returns an index of an image's layer IDs and tags.
  220. func createImageIndex(images []v1Image, tags map[image.ID][]string) []*registry.ImgData {
  221. var imageIndex []*registry.ImgData
  222. for _, img := range images {
  223. v1ID := img.V1ID()
  224. if topImage, isTopImage := img.(*v1TopImage); isTopImage {
  225. if tags, hasTags := tags[topImage.imageID]; hasTags {
  226. // If an image has tags you must add an entry in the image index
  227. // for each tag
  228. for _, tag := range tags {
  229. imageIndex = append(imageIndex, &registry.ImgData{
  230. ID: v1ID,
  231. Tag: tag,
  232. })
  233. }
  234. continue
  235. }
  236. }
  237. // If the image does not have a tag it still needs to be sent to the
  238. // registry with an empty tag so that it is associated with the repository
  239. imageIndex = append(imageIndex, &registry.ImgData{
  240. ID: v1ID,
  241. Tag: "",
  242. })
  243. }
  244. return imageIndex
  245. }
  246. // lookupImageOnEndpoint checks the specified endpoint to see if an image exists
  247. // and if it is absent then it sends the image id to the channel to be pushed.
  248. func (p *v1Pusher) lookupImageOnEndpoint(wg *sync.WaitGroup, endpoint string, images chan v1Image, imagesToPush chan string) {
  249. defer wg.Done()
  250. for image := range images {
  251. v1ID := image.V1ID()
  252. truncID := stringid.TruncateID(image.Layer().DiffID().String())
  253. if err := p.session.LookupRemoteImage(v1ID, endpoint); err != nil {
  254. logrus.Errorf("Error in LookupRemoteImage: %s", err)
  255. imagesToPush <- v1ID
  256. progress.Update(p.config.ProgressOutput, truncID, "Waiting")
  257. } else {
  258. progress.Update(p.config.ProgressOutput, truncID, "Already exists")
  259. }
  260. }
  261. }
  262. func (p *v1Pusher) pushImageToEndpoint(ctx context.Context, endpoint string, imageList []v1Image, tags map[image.ID][]string, repo *registry.RepositoryData) error {
  263. workerCount := len(imageList)
  264. // start a maximum of 5 workers to check if images exist on the specified endpoint.
  265. if workerCount > 5 {
  266. workerCount = 5
  267. }
  268. var (
  269. wg = &sync.WaitGroup{}
  270. imageData = make(chan v1Image, workerCount*2)
  271. imagesToPush = make(chan string, workerCount*2)
  272. pushes = make(chan map[string]struct{}, 1)
  273. )
  274. for i := 0; i < workerCount; i++ {
  275. wg.Add(1)
  276. go p.lookupImageOnEndpoint(wg, endpoint, imageData, imagesToPush)
  277. }
  278. // start a go routine that consumes the images to push
  279. go func() {
  280. shouldPush := make(map[string]struct{})
  281. for id := range imagesToPush {
  282. shouldPush[id] = struct{}{}
  283. }
  284. pushes <- shouldPush
  285. }()
  286. for _, v1Image := range imageList {
  287. imageData <- v1Image
  288. }
  289. // close the channel to notify the workers that there will be no more images to check.
  290. close(imageData)
  291. wg.Wait()
  292. close(imagesToPush)
  293. // wait for all the images that require pushes to be collected into a consumable map.
  294. shouldPush := <-pushes
  295. // finish by pushing any images and tags to the endpoint. The order that the images are pushed
  296. // is very important that is why we are still iterating over the ordered list of imageIDs.
  297. for _, img := range imageList {
  298. v1ID := img.V1ID()
  299. if _, push := shouldPush[v1ID]; push {
  300. if _, err := p.pushImage(ctx, img, endpoint); err != nil {
  301. // FIXME: Continue on error?
  302. return err
  303. }
  304. }
  305. if topImage, isTopImage := img.(*v1TopImage); isTopImage {
  306. for _, tag := range tags[topImage.imageID] {
  307. progress.Messagef(p.config.ProgressOutput, "", "Pushing tag for rev [%s] on {%s}", stringid.TruncateID(v1ID), endpoint+"repositories/"+reference.Path(p.repoInfo.Name)+"/tags/"+tag)
  308. if err := p.session.PushRegistryTag(p.repoInfo.Name, v1ID, tag, endpoint); err != nil {
  309. return err
  310. }
  311. }
  312. }
  313. }
  314. return nil
  315. }
  316. // pushRepository pushes layers that do not already exist on the registry.
  317. func (p *v1Pusher) pushRepository(ctx context.Context) error {
  318. imgList, tags, referencedLayers, err := p.getImageList()
  319. defer func() {
  320. for _, l := range referencedLayers {
  321. l.Release()
  322. }
  323. }()
  324. if err != nil {
  325. return err
  326. }
  327. imageIndex := createImageIndex(imgList, tags)
  328. for _, data := range imageIndex {
  329. logrus.Debugf("Pushing ID: %s with Tag: %s", data.ID, data.Tag)
  330. }
  331. // Register all the images in a repository with the registry
  332. // If an image is not in this list it will not be associated with the repository
  333. repoData, err := p.session.PushImageJSONIndex(p.repoInfo.Name, imageIndex, false, nil)
  334. if err != nil {
  335. return err
  336. }
  337. // push the repository to each of the endpoints only if it does not exist.
  338. for _, endpoint := range repoData.Endpoints {
  339. if err := p.pushImageToEndpoint(ctx, endpoint, imgList, tags, repoData); err != nil {
  340. return err
  341. }
  342. }
  343. _, err = p.session.PushImageJSONIndex(p.repoInfo.Name, imageIndex, true, repoData.Endpoints)
  344. return err
  345. }
  346. func (p *v1Pusher) pushImage(ctx context.Context, v1Image v1Image, ep string) (checksum string, err error) {
  347. l := v1Image.Layer()
  348. v1ID := v1Image.V1ID()
  349. truncID := stringid.TruncateID(l.DiffID().String())
  350. jsonRaw := v1Image.Config()
  351. progress.Update(p.config.ProgressOutput, truncID, "Pushing")
  352. // General rule is to use ID for graph accesses and compatibilityID for
  353. // calls to session.registry()
  354. imgData := &registry.ImgData{
  355. ID: v1ID,
  356. }
  357. // Send the json
  358. if err := p.session.PushImageJSONRegistry(imgData, jsonRaw, ep); err != nil {
  359. if err == registry.ErrAlreadyExists {
  360. progress.Update(p.config.ProgressOutput, truncID, "Image already pushed, skipping")
  361. return "", nil
  362. }
  363. return "", err
  364. }
  365. arch, err := l.TarStream()
  366. if err != nil {
  367. return "", err
  368. }
  369. defer arch.Close()
  370. // don't care if this fails; best effort
  371. size, _ := l.DiffSize()
  372. // Send the layer
  373. logrus.Debugf("rendered layer for %s of [%d] size", v1ID, size)
  374. reader := progress.NewProgressReader(ioutils.NewCancelReadCloser(ctx, arch), p.config.ProgressOutput, size, truncID, "Pushing")
  375. defer reader.Close()
  376. checksum, checksumPayload, err := p.session.PushImageLayerRegistry(v1ID, reader, ep, jsonRaw)
  377. if err != nil {
  378. return "", err
  379. }
  380. imgData.Checksum = checksum
  381. imgData.ChecksumPayload = checksumPayload
  382. // Send the checksum
  383. if err := p.session.PushImageChecksumRegistry(imgData, ep); err != nil {
  384. return "", err
  385. }
  386. if err := p.v1IDService.Set(v1ID, p.repoInfo.Index.Name, l.DiffID()); err != nil {
  387. logrus.Warnf("Could not set v1 ID mapping: %v", err)
  388. }
  389. progress.Update(p.config.ProgressOutput, truncID, "Image successfully pushed")
  390. return imgData.Checksum, nil
  391. }