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