push_v2.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. package distribution
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "runtime"
  7. "sort"
  8. "strings"
  9. "sync"
  10. "golang.org/x/net/context"
  11. "github.com/Sirupsen/logrus"
  12. "github.com/docker/distribution"
  13. "github.com/docker/distribution/manifest/schema1"
  14. "github.com/docker/distribution/manifest/schema2"
  15. "github.com/docker/distribution/reference"
  16. "github.com/docker/distribution/registry/client"
  17. apitypes "github.com/docker/docker/api/types"
  18. "github.com/docker/docker/distribution/metadata"
  19. "github.com/docker/docker/distribution/xfer"
  20. "github.com/docker/docker/layer"
  21. "github.com/docker/docker/pkg/ioutils"
  22. "github.com/docker/docker/pkg/progress"
  23. "github.com/docker/docker/pkg/stringid"
  24. "github.com/docker/docker/registry"
  25. "github.com/opencontainers/go-digest"
  26. )
  27. const (
  28. smallLayerMaximumSize = 100 * (1 << 10) // 100KB
  29. middleLayerMaximumSize = 10 * (1 << 20) // 10MB
  30. )
  31. type v2Pusher struct {
  32. v2MetadataService metadata.V2MetadataService
  33. ref reference.Named
  34. endpoint registry.APIEndpoint
  35. repoInfo *registry.RepositoryInfo
  36. config *ImagePushConfig
  37. repo distribution.Repository
  38. // pushState is state built by the Upload functions.
  39. pushState pushState
  40. }
  41. type pushState struct {
  42. sync.Mutex
  43. // remoteLayers is the set of layers known to exist on the remote side.
  44. // This avoids redundant queries when pushing multiple tags that
  45. // involve the same layers. It is also used to fill in digest and size
  46. // information when building the manifest.
  47. remoteLayers map[layer.DiffID]distribution.Descriptor
  48. // confirmedV2 is set to true if we confirm we're talking to a v2
  49. // registry. This is used to limit fallbacks to the v1 protocol.
  50. confirmedV2 bool
  51. }
  52. func (p *v2Pusher) Push(ctx context.Context) (err error) {
  53. p.pushState.remoteLayers = make(map[layer.DiffID]distribution.Descriptor)
  54. p.repo, p.pushState.confirmedV2, err = NewV2Repository(ctx, p.repoInfo, p.endpoint, p.config.MetaHeaders, p.config.AuthConfig, "push", "pull")
  55. if err != nil {
  56. logrus.Debugf("Error getting v2 registry: %v", err)
  57. return err
  58. }
  59. if err = p.pushV2Repository(ctx); err != nil {
  60. if continueOnError(err) {
  61. return fallbackError{
  62. err: err,
  63. confirmedV2: p.pushState.confirmedV2,
  64. transportOK: true,
  65. }
  66. }
  67. }
  68. return err
  69. }
  70. func (p *v2Pusher) pushV2Repository(ctx context.Context) (err error) {
  71. if namedTagged, isNamedTagged := p.ref.(reference.NamedTagged); isNamedTagged {
  72. imageID, err := p.config.ReferenceStore.Get(p.ref)
  73. if err != nil {
  74. return fmt.Errorf("tag does not exist: %s", reference.FamiliarString(p.ref))
  75. }
  76. return p.pushV2Tag(ctx, namedTagged, imageID)
  77. }
  78. if !reference.IsNameOnly(p.ref) {
  79. return errors.New("cannot push a digest reference")
  80. }
  81. // Pull all tags
  82. pushed := 0
  83. for _, association := range p.config.ReferenceStore.ReferencesByName(p.ref) {
  84. if namedTagged, isNamedTagged := association.Ref.(reference.NamedTagged); isNamedTagged {
  85. pushed++
  86. if err := p.pushV2Tag(ctx, namedTagged, association.ID); err != nil {
  87. return err
  88. }
  89. }
  90. }
  91. if pushed == 0 {
  92. return fmt.Errorf("no tags to push for %s", reference.FamiliarName(p.repoInfo.Name))
  93. }
  94. return nil
  95. }
  96. func (p *v2Pusher) pushV2Tag(ctx context.Context, ref reference.NamedTagged, id digest.Digest) error {
  97. logrus.Debugf("Pushing repository: %s", reference.FamiliarString(ref))
  98. imgConfig, err := p.config.ImageStore.Get(id)
  99. if err != nil {
  100. return fmt.Errorf("could not find image from tag %s: %v", reference.FamiliarString(ref), err)
  101. }
  102. rootfs, err := p.config.ImageStore.RootFSFromConfig(imgConfig)
  103. if err != nil {
  104. return fmt.Errorf("unable to get rootfs for image %s: %s", reference.FamiliarString(ref), err)
  105. }
  106. l, err := p.config.LayerStore.Get(rootfs.ChainID())
  107. if err != nil {
  108. return fmt.Errorf("failed to get top layer from image: %v", err)
  109. }
  110. defer l.Release()
  111. hmacKey, err := metadata.ComputeV2MetadataHMACKey(p.config.AuthConfig)
  112. if err != nil {
  113. return fmt.Errorf("failed to compute hmac key of auth config: %v", err)
  114. }
  115. var descriptors []xfer.UploadDescriptor
  116. descriptorTemplate := v2PushDescriptor{
  117. v2MetadataService: p.v2MetadataService,
  118. hmacKey: hmacKey,
  119. repoInfo: p.repoInfo.Name,
  120. ref: p.ref,
  121. endpoint: p.endpoint,
  122. repo: p.repo,
  123. pushState: &p.pushState,
  124. }
  125. // Loop bounds condition is to avoid pushing the base layer on Windows.
  126. for i := 0; i < len(rootfs.DiffIDs); i++ {
  127. descriptor := descriptorTemplate
  128. descriptor.layer = l
  129. descriptor.checkedDigests = make(map[digest.Digest]struct{})
  130. descriptors = append(descriptors, &descriptor)
  131. l = l.Parent()
  132. }
  133. if err := p.config.UploadManager.Upload(ctx, descriptors, p.config.ProgressOutput); err != nil {
  134. return err
  135. }
  136. // Try schema2 first
  137. builder := schema2.NewManifestBuilder(p.repo.Blobs(ctx), p.config.ConfigMediaType, imgConfig)
  138. manifest, err := manifestFromBuilder(ctx, builder, descriptors)
  139. if err != nil {
  140. return err
  141. }
  142. manSvc, err := p.repo.Manifests(ctx)
  143. if err != nil {
  144. return err
  145. }
  146. putOptions := []distribution.ManifestServiceOption{distribution.WithTag(ref.Tag())}
  147. if _, err = manSvc.Put(ctx, manifest, putOptions...); err != nil {
  148. if runtime.GOOS == "windows" || p.config.TrustKey == nil || p.config.RequireSchema2 {
  149. logrus.Warnf("failed to upload schema2 manifest: %v", err)
  150. return err
  151. }
  152. logrus.Warnf("failed to upload schema2 manifest: %v - falling back to schema1", err)
  153. manifestRef, err := reference.WithTag(p.repo.Named(), ref.Tag())
  154. if err != nil {
  155. return err
  156. }
  157. builder = schema1.NewConfigManifestBuilder(p.repo.Blobs(ctx), p.config.TrustKey, manifestRef, imgConfig)
  158. manifest, err = manifestFromBuilder(ctx, builder, descriptors)
  159. if err != nil {
  160. return err
  161. }
  162. if _, err = manSvc.Put(ctx, manifest, putOptions...); err != nil {
  163. return err
  164. }
  165. }
  166. var canonicalManifest []byte
  167. switch v := manifest.(type) {
  168. case *schema1.SignedManifest:
  169. canonicalManifest = v.Canonical
  170. case *schema2.DeserializedManifest:
  171. _, canonicalManifest, err = v.Payload()
  172. if err != nil {
  173. return err
  174. }
  175. }
  176. manifestDigest := digest.FromBytes(canonicalManifest)
  177. progress.Messagef(p.config.ProgressOutput, "", "%s: digest: %s size: %d", ref.Tag(), manifestDigest, len(canonicalManifest))
  178. if err := addDigestReference(p.config.ReferenceStore, ref, manifestDigest, id); err != nil {
  179. return err
  180. }
  181. // Signal digest to the trust client so it can sign the
  182. // push, if appropriate.
  183. progress.Aux(p.config.ProgressOutput, apitypes.PushResult{Tag: ref.Tag(), Digest: manifestDigest.String(), Size: len(canonicalManifest)})
  184. return nil
  185. }
  186. func manifestFromBuilder(ctx context.Context, builder distribution.ManifestBuilder, descriptors []xfer.UploadDescriptor) (distribution.Manifest, error) {
  187. // descriptors is in reverse order; iterate backwards to get references
  188. // appended in the right order.
  189. for i := len(descriptors) - 1; i >= 0; i-- {
  190. if err := builder.AppendReference(descriptors[i].(*v2PushDescriptor)); err != nil {
  191. return nil, err
  192. }
  193. }
  194. return builder.Build(ctx)
  195. }
  196. type v2PushDescriptor struct {
  197. layer PushLayer
  198. v2MetadataService metadata.V2MetadataService
  199. hmacKey []byte
  200. repoInfo reference.Named
  201. ref reference.Named
  202. endpoint registry.APIEndpoint
  203. repo distribution.Repository
  204. pushState *pushState
  205. remoteDescriptor distribution.Descriptor
  206. // a set of digests whose presence has been checked in a target repository
  207. checkedDigests map[digest.Digest]struct{}
  208. }
  209. func (pd *v2PushDescriptor) Key() string {
  210. return "v2push:" + pd.ref.Name() + " " + pd.layer.DiffID().String()
  211. }
  212. func (pd *v2PushDescriptor) ID() string {
  213. return stringid.TruncateID(pd.layer.DiffID().String())
  214. }
  215. func (pd *v2PushDescriptor) DiffID() layer.DiffID {
  216. return pd.layer.DiffID()
  217. }
  218. func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress.Output) (distribution.Descriptor, error) {
  219. // Skip foreign layers unless this registry allows nondistributable artifacts.
  220. if !pd.endpoint.AllowNondistributableArtifacts {
  221. if fs, ok := pd.layer.(distribution.Describable); ok {
  222. if d := fs.Descriptor(); len(d.URLs) > 0 {
  223. progress.Update(progressOutput, pd.ID(), "Skipped foreign layer")
  224. return d, nil
  225. }
  226. }
  227. }
  228. diffID := pd.DiffID()
  229. pd.pushState.Lock()
  230. if descriptor, ok := pd.pushState.remoteLayers[diffID]; ok {
  231. // it is already known that the push is not needed and
  232. // therefore doing a stat is unnecessary
  233. pd.pushState.Unlock()
  234. progress.Update(progressOutput, pd.ID(), "Layer already exists")
  235. return descriptor, nil
  236. }
  237. pd.pushState.Unlock()
  238. maxMountAttempts, maxExistenceChecks, checkOtherRepositories := getMaxMountAndExistenceCheckAttempts(pd.layer)
  239. // Do we have any metadata associated with this layer's DiffID?
  240. v2Metadata, err := pd.v2MetadataService.GetMetadata(diffID)
  241. if err == nil {
  242. // check for blob existence in the target repository
  243. descriptor, exists, err := pd.layerAlreadyExists(ctx, progressOutput, diffID, true, 1, v2Metadata)
  244. if exists || err != nil {
  245. return descriptor, err
  246. }
  247. }
  248. // if digest was empty or not saved, or if blob does not exist on the remote repository,
  249. // then push the blob.
  250. bs := pd.repo.Blobs(ctx)
  251. var layerUpload distribution.BlobWriter
  252. // Attempt to find another repository in the same registry to mount the layer from to avoid an unnecessary upload
  253. candidates := getRepositoryMountCandidates(pd.repoInfo, pd.hmacKey, maxMountAttempts, v2Metadata)
  254. for _, mountCandidate := range candidates {
  255. logrus.Debugf("attempting to mount layer %s (%s) from %s", diffID, mountCandidate.Digest, mountCandidate.SourceRepository)
  256. createOpts := []distribution.BlobCreateOption{}
  257. if len(mountCandidate.SourceRepository) > 0 {
  258. namedRef, err := reference.ParseNormalizedNamed(mountCandidate.SourceRepository)
  259. if err != nil {
  260. logrus.Errorf("failed to parse source repository reference %v: %v", reference.FamiliarString(namedRef), err)
  261. pd.v2MetadataService.Remove(mountCandidate)
  262. continue
  263. }
  264. // Candidates are always under same domain, create remote reference
  265. // with only path to set mount from with
  266. remoteRef, err := reference.WithName(reference.Path(namedRef))
  267. if err != nil {
  268. logrus.Errorf("failed to make remote reference out of %q: %v", reference.Path(namedRef), err)
  269. continue
  270. }
  271. canonicalRef, err := reference.WithDigest(reference.TrimNamed(remoteRef), mountCandidate.Digest)
  272. if err != nil {
  273. logrus.Errorf("failed to make canonical reference: %v", err)
  274. continue
  275. }
  276. createOpts = append(createOpts, client.WithMountFrom(canonicalRef))
  277. }
  278. // send the layer
  279. lu, err := bs.Create(ctx, createOpts...)
  280. switch err := err.(type) {
  281. case nil:
  282. // noop
  283. case distribution.ErrBlobMounted:
  284. progress.Updatef(progressOutput, pd.ID(), "Mounted from %s", err.From.Name())
  285. err.Descriptor.MediaType = schema2.MediaTypeLayer
  286. pd.pushState.Lock()
  287. pd.pushState.confirmedV2 = true
  288. pd.pushState.remoteLayers[diffID] = err.Descriptor
  289. pd.pushState.Unlock()
  290. // Cache mapping from this layer's DiffID to the blobsum
  291. if err := pd.v2MetadataService.TagAndAdd(diffID, pd.hmacKey, metadata.V2Metadata{
  292. Digest: err.Descriptor.Digest,
  293. SourceRepository: pd.repoInfo.Name(),
  294. }); err != nil {
  295. return distribution.Descriptor{}, xfer.DoNotRetry{Err: err}
  296. }
  297. return err.Descriptor, nil
  298. default:
  299. logrus.Infof("failed to mount layer %s (%s) from %s: %v", diffID, mountCandidate.Digest, mountCandidate.SourceRepository, err)
  300. }
  301. if len(mountCandidate.SourceRepository) > 0 &&
  302. (metadata.CheckV2MetadataHMAC(&mountCandidate, pd.hmacKey) ||
  303. len(mountCandidate.HMAC) == 0) {
  304. cause := "blob mount failure"
  305. if err != nil {
  306. cause = fmt.Sprintf("an error: %v", err.Error())
  307. }
  308. logrus.Debugf("removing association between layer %s and %s due to %s", mountCandidate.Digest, mountCandidate.SourceRepository, cause)
  309. pd.v2MetadataService.Remove(mountCandidate)
  310. }
  311. if lu != nil {
  312. // cancel previous upload
  313. cancelLayerUpload(ctx, mountCandidate.Digest, layerUpload)
  314. layerUpload = lu
  315. }
  316. }
  317. if maxExistenceChecks-len(pd.checkedDigests) > 0 {
  318. // do additional layer existence checks with other known digests if any
  319. descriptor, exists, err := pd.layerAlreadyExists(ctx, progressOutput, diffID, checkOtherRepositories, maxExistenceChecks-len(pd.checkedDigests), v2Metadata)
  320. if exists || err != nil {
  321. return descriptor, err
  322. }
  323. }
  324. logrus.Debugf("Pushing layer: %s", diffID)
  325. if layerUpload == nil {
  326. layerUpload, err = bs.Create(ctx)
  327. if err != nil {
  328. return distribution.Descriptor{}, retryOnError(err)
  329. }
  330. }
  331. defer layerUpload.Close()
  332. // upload the blob
  333. desc, err := pd.uploadUsingSession(ctx, progressOutput, diffID, layerUpload)
  334. if err != nil {
  335. return desc, err
  336. }
  337. return desc, nil
  338. }
  339. func (pd *v2PushDescriptor) SetRemoteDescriptor(descriptor distribution.Descriptor) {
  340. pd.remoteDescriptor = descriptor
  341. }
  342. func (pd *v2PushDescriptor) Descriptor() distribution.Descriptor {
  343. return pd.remoteDescriptor
  344. }
  345. func (pd *v2PushDescriptor) uploadUsingSession(
  346. ctx context.Context,
  347. progressOutput progress.Output,
  348. diffID layer.DiffID,
  349. layerUpload distribution.BlobWriter,
  350. ) (distribution.Descriptor, error) {
  351. var reader io.ReadCloser
  352. contentReader, err := pd.layer.Open()
  353. if err != nil {
  354. return distribution.Descriptor{}, retryOnError(err)
  355. }
  356. size, _ := pd.layer.Size()
  357. reader = progress.NewProgressReader(ioutils.NewCancelReadCloser(ctx, contentReader), progressOutput, size, pd.ID(), "Pushing")
  358. switch m := pd.layer.MediaType(); m {
  359. case schema2.MediaTypeUncompressedLayer:
  360. compressedReader, compressionDone := compress(reader)
  361. defer func(closer io.Closer) {
  362. closer.Close()
  363. <-compressionDone
  364. }(reader)
  365. reader = compressedReader
  366. case schema2.MediaTypeLayer:
  367. default:
  368. reader.Close()
  369. return distribution.Descriptor{}, fmt.Errorf("unsupported layer media type %s", m)
  370. }
  371. digester := digest.Canonical.Digester()
  372. tee := io.TeeReader(reader, digester.Hash())
  373. nn, err := layerUpload.ReadFrom(tee)
  374. reader.Close()
  375. if err != nil {
  376. return distribution.Descriptor{}, retryOnError(err)
  377. }
  378. pushDigest := digester.Digest()
  379. if _, err := layerUpload.Commit(ctx, distribution.Descriptor{Digest: pushDigest}); err != nil {
  380. return distribution.Descriptor{}, retryOnError(err)
  381. }
  382. logrus.Debugf("uploaded layer %s (%s), %d bytes", diffID, pushDigest, nn)
  383. progress.Update(progressOutput, pd.ID(), "Pushed")
  384. // Cache mapping from this layer's DiffID to the blobsum
  385. if err := pd.v2MetadataService.TagAndAdd(diffID, pd.hmacKey, metadata.V2Metadata{
  386. Digest: pushDigest,
  387. SourceRepository: pd.repoInfo.Name(),
  388. }); err != nil {
  389. return distribution.Descriptor{}, xfer.DoNotRetry{Err: err}
  390. }
  391. desc := distribution.Descriptor{
  392. Digest: pushDigest,
  393. MediaType: schema2.MediaTypeLayer,
  394. Size: nn,
  395. }
  396. pd.pushState.Lock()
  397. // If Commit succeeded, that's an indication that the remote registry speaks the v2 protocol.
  398. pd.pushState.confirmedV2 = true
  399. pd.pushState.remoteLayers[diffID] = desc
  400. pd.pushState.Unlock()
  401. return desc, nil
  402. }
  403. // layerAlreadyExists checks if the registry already knows about any of the metadata passed in the "metadata"
  404. // slice. If it finds one that the registry knows about, it returns the known digest and "true". If
  405. // "checkOtherRepositories" is true, stat will be performed also with digests mapped to any other repository
  406. // (not just the target one).
  407. func (pd *v2PushDescriptor) layerAlreadyExists(
  408. ctx context.Context,
  409. progressOutput progress.Output,
  410. diffID layer.DiffID,
  411. checkOtherRepositories bool,
  412. maxExistenceCheckAttempts int,
  413. v2Metadata []metadata.V2Metadata,
  414. ) (desc distribution.Descriptor, exists bool, err error) {
  415. // filter the metadata
  416. candidates := []metadata.V2Metadata{}
  417. for _, meta := range v2Metadata {
  418. if len(meta.SourceRepository) > 0 && !checkOtherRepositories && meta.SourceRepository != pd.repoInfo.Name() {
  419. continue
  420. }
  421. candidates = append(candidates, meta)
  422. }
  423. // sort the candidates by similarity
  424. sortV2MetadataByLikenessAndAge(pd.repoInfo, pd.hmacKey, candidates)
  425. digestToMetadata := make(map[digest.Digest]*metadata.V2Metadata)
  426. // an array of unique blob digests ordered from the best mount candidates to worst
  427. layerDigests := []digest.Digest{}
  428. for i := 0; i < len(candidates); i++ {
  429. if len(layerDigests) >= maxExistenceCheckAttempts {
  430. break
  431. }
  432. meta := &candidates[i]
  433. if _, exists := digestToMetadata[meta.Digest]; exists {
  434. // keep reference just to the first mapping (the best mount candidate)
  435. continue
  436. }
  437. if _, exists := pd.checkedDigests[meta.Digest]; exists {
  438. // existence of this digest has already been tested
  439. continue
  440. }
  441. digestToMetadata[meta.Digest] = meta
  442. layerDigests = append(layerDigests, meta.Digest)
  443. }
  444. attempts:
  445. for _, dgst := range layerDigests {
  446. meta := digestToMetadata[dgst]
  447. logrus.Debugf("Checking for presence of layer %s (%s) in %s", diffID, dgst, pd.repoInfo.Name())
  448. desc, err = pd.repo.Blobs(ctx).Stat(ctx, dgst)
  449. pd.checkedDigests[meta.Digest] = struct{}{}
  450. switch err {
  451. case nil:
  452. if m, ok := digestToMetadata[desc.Digest]; !ok || m.SourceRepository != pd.repoInfo.Name() || !metadata.CheckV2MetadataHMAC(m, pd.hmacKey) {
  453. // cache mapping from this layer's DiffID to the blobsum
  454. if err := pd.v2MetadataService.TagAndAdd(diffID, pd.hmacKey, metadata.V2Metadata{
  455. Digest: desc.Digest,
  456. SourceRepository: pd.repoInfo.Name(),
  457. }); err != nil {
  458. return distribution.Descriptor{}, false, xfer.DoNotRetry{Err: err}
  459. }
  460. }
  461. desc.MediaType = schema2.MediaTypeLayer
  462. exists = true
  463. break attempts
  464. case distribution.ErrBlobUnknown:
  465. if meta.SourceRepository == pd.repoInfo.Name() {
  466. // remove the mapping to the target repository
  467. pd.v2MetadataService.Remove(*meta)
  468. }
  469. default:
  470. logrus.WithError(err).Debugf("Failed to check for presence of layer %s (%s) in %s", diffID, dgst, pd.repoInfo.Name())
  471. }
  472. }
  473. if exists {
  474. progress.Update(progressOutput, pd.ID(), "Layer already exists")
  475. pd.pushState.Lock()
  476. pd.pushState.remoteLayers[diffID] = desc
  477. pd.pushState.Unlock()
  478. }
  479. return desc, exists, nil
  480. }
  481. // getMaxMountAndExistenceCheckAttempts returns a maximum number of cross repository mount attempts from
  482. // source repositories of target registry, maximum number of layer existence checks performed on the target
  483. // repository and whether the check shall be done also with digests mapped to different repositories. The
  484. // decision is based on layer size. The smaller the layer, the fewer attempts shall be made because the cost
  485. // of upload does not outweigh a latency.
  486. func getMaxMountAndExistenceCheckAttempts(layer PushLayer) (maxMountAttempts, maxExistenceCheckAttempts int, checkOtherRepositories bool) {
  487. size, err := layer.Size()
  488. switch {
  489. // big blob
  490. case size > middleLayerMaximumSize:
  491. // 1st attempt to mount the blob few times
  492. // 2nd few existence checks with digests associated to any repository
  493. // then fallback to upload
  494. return 4, 3, true
  495. // middle sized blobs; if we could not get the size, assume we deal with middle sized blob
  496. case size > smallLayerMaximumSize, err != nil:
  497. // 1st attempt to mount blobs of average size few times
  498. // 2nd try at most 1 existence check if there's an existing mapping to the target repository
  499. // then fallback to upload
  500. return 3, 1, false
  501. // small blobs, do a minimum number of checks
  502. default:
  503. return 1, 1, false
  504. }
  505. }
  506. // getRepositoryMountCandidates returns an array of v2 metadata items belonging to the given registry. The
  507. // array is sorted from youngest to oldest. If requireRegistryMatch is true, the resulting array will contain
  508. // only metadata entries having registry part of SourceRepository matching the part of repoInfo.
  509. func getRepositoryMountCandidates(
  510. repoInfo reference.Named,
  511. hmacKey []byte,
  512. max int,
  513. v2Metadata []metadata.V2Metadata,
  514. ) []metadata.V2Metadata {
  515. candidates := []metadata.V2Metadata{}
  516. for _, meta := range v2Metadata {
  517. sourceRepo, err := reference.ParseNamed(meta.SourceRepository)
  518. if err != nil || reference.Domain(repoInfo) != reference.Domain(sourceRepo) {
  519. continue
  520. }
  521. // target repository is not a viable candidate
  522. if meta.SourceRepository == repoInfo.Name() {
  523. continue
  524. }
  525. candidates = append(candidates, meta)
  526. }
  527. sortV2MetadataByLikenessAndAge(repoInfo, hmacKey, candidates)
  528. if max >= 0 && len(candidates) > max {
  529. // select the youngest metadata
  530. candidates = candidates[:max]
  531. }
  532. return candidates
  533. }
  534. // byLikeness is a sorting container for v2 metadata candidates for cross repository mount. The
  535. // candidate "a" is preferred over "b":
  536. //
  537. // 1. if it was hashed using the same AuthConfig as the one used to authenticate to target repository and the
  538. // "b" was not
  539. // 2. if a number of its repository path components exactly matching path components of target repository is higher
  540. type byLikeness struct {
  541. arr []metadata.V2Metadata
  542. hmacKey []byte
  543. pathComponents []string
  544. }
  545. func (bla byLikeness) Less(i, j int) bool {
  546. aMacMatch := metadata.CheckV2MetadataHMAC(&bla.arr[i], bla.hmacKey)
  547. bMacMatch := metadata.CheckV2MetadataHMAC(&bla.arr[j], bla.hmacKey)
  548. if aMacMatch != bMacMatch {
  549. return aMacMatch
  550. }
  551. aMatch := numOfMatchingPathComponents(bla.arr[i].SourceRepository, bla.pathComponents)
  552. bMatch := numOfMatchingPathComponents(bla.arr[j].SourceRepository, bla.pathComponents)
  553. return aMatch > bMatch
  554. }
  555. func (bla byLikeness) Swap(i, j int) {
  556. bla.arr[i], bla.arr[j] = bla.arr[j], bla.arr[i]
  557. }
  558. func (bla byLikeness) Len() int { return len(bla.arr) }
  559. func sortV2MetadataByLikenessAndAge(repoInfo reference.Named, hmacKey []byte, marr []metadata.V2Metadata) {
  560. // reverse the metadata array to shift the newest entries to the beginning
  561. for i := 0; i < len(marr)/2; i++ {
  562. marr[i], marr[len(marr)-i-1] = marr[len(marr)-i-1], marr[i]
  563. }
  564. // keep equal entries ordered from the youngest to the oldest
  565. sort.Stable(byLikeness{
  566. arr: marr,
  567. hmacKey: hmacKey,
  568. pathComponents: getPathComponents(repoInfo.Name()),
  569. })
  570. }
  571. // numOfMatchingPathComponents returns a number of path components in "pth" that exactly match "matchComponents".
  572. func numOfMatchingPathComponents(pth string, matchComponents []string) int {
  573. pthComponents := getPathComponents(pth)
  574. i := 0
  575. for ; i < len(pthComponents) && i < len(matchComponents); i++ {
  576. if matchComponents[i] != pthComponents[i] {
  577. return i
  578. }
  579. }
  580. return i
  581. }
  582. func getPathComponents(path string) []string {
  583. return strings.Split(path, "/")
  584. }
  585. func cancelLayerUpload(ctx context.Context, dgst digest.Digest, layerUpload distribution.BlobWriter) {
  586. if layerUpload != nil {
  587. logrus.Debugf("cancelling upload of blob %s", dgst)
  588. err := layerUpload.Cancel(ctx)
  589. if err != nil {
  590. logrus.Warnf("failed to cancel upload: %v", err)
  591. }
  592. }
  593. }