push_v1.go 13 KB

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