-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathremoteblobgetter.go
384 lines (335 loc) · 12.3 KB
/
remoteblobgetter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
package server
import (
"net/http"
"sort"
"github.com/docker/distribution"
"github.com/docker/distribution/context"
"github.com/docker/distribution/digest"
"github.com/docker/distribution/registry/api/errcode"
disterrors "github.com/docker/distribution/registry/api/v2"
"github.com/openshift/image-registry/pkg/dockerregistry/server/cache"
"github.com/openshift/image-registry/pkg/dockerregistry/server/client"
imageapi "github.com/openshift/origin/pkg/image/apis/image"
imageapiv1 "github.com/openshift/origin/pkg/image/apis/image/v1"
"github.com/openshift/origin/pkg/image/importer"
)
// BlobGetterService combines the operations to access and read blobs.
type BlobGetterService interface {
distribution.BlobStatter
distribution.BlobProvider
distribution.BlobServer
}
type ImageStreamGetter func() (*imageapiv1.ImageStream, error)
// remoteBlobGetterService implements BlobGetterService and allows to serve blobs from remote
// repositories.
type remoteBlobGetterService struct {
namespace string
name string
getImageStream ImageStreamGetter
isSecretsNamespacer client.ImageStreamSecretsNamespacer
cache cache.RepositoryDigest
digestToStore map[string]distribution.BlobStore
}
var _ BlobGetterService = &remoteBlobGetterService{}
// NewBlobGetterService returns a getter for remote blobs. Its cache will be shared among different middleware
// wrappers, which is a must at least for stat calls made on manifest's dependencies during its verification.
func NewBlobGetterService(
namespace, name string,
imageStreamGetter ImageStreamGetter,
isSecretsNamespacer client.ImageStreamSecretsNamespacer,
cache cache.RepositoryDigest,
) BlobGetterService {
return &remoteBlobGetterService{
namespace: namespace,
name: name,
getImageStream: imageStreamGetter,
isSecretsNamespacer: isSecretsNamespacer,
cache: cache,
digestToStore: make(map[string]distribution.BlobStore),
}
}
// imagePullthroughSpec contains a reference of remote image to pull associated with an insecure flag for the
// corresponding registry.
type imagePullthroughSpec struct {
dockerImageReference *imageapi.DockerImageReference
insecure bool
}
// Stat provides metadata about a blob identified by the digest. If the
// blob is unknown to the describer, ErrBlobUnknown will be returned.
func (rbgs *remoteBlobGetterService) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
context.GetLogger(ctx).Debugf("(*remoteBlobGetterService).Stat: starting with dgst=%s", dgst.String())
// look up the potential remote repositories that this blob could be part of (at this time,
// we don't know which image in the image stream surfaced the content).
is, err := rbgs.getImageStream()
if err != nil {
if t, ok := err.(errcode.Error); ok && t.ErrorCode() == disterrors.ErrorCodeNameUnknown {
return distribution.Descriptor{}, distribution.ErrBlobUnknown
}
return distribution.Descriptor{}, err
}
cached, _ := rbgs.cache.Repositories(dgst)
var localRegistry string
if local, err := imageapi.ParseDockerImageReference(is.Status.DockerImageRepository); err == nil {
// TODO: normalize further?
localRegistry = local.Registry
}
retriever := getImportContext(ctx, rbgs.isSecretsNamespacer, rbgs.namespace, rbgs.name)
// look at the first level of tagged repositories first
repositoryCandidates, search := identifyCandidateRepositories(is, localRegistry, true)
if desc, err := rbgs.findCandidateRepository(ctx, repositoryCandidates, search, cached, dgst, retriever); err == nil {
return desc, nil
}
// look at all other repositories tagged by the server
repositoryCandidates, secondary := identifyCandidateRepositories(is, localRegistry, false)
for k := range search {
delete(secondary, k)
}
if desc, err := rbgs.findCandidateRepository(ctx, repositoryCandidates, secondary, cached, dgst, retriever); err == nil {
return desc, nil
}
return distribution.Descriptor{}, distribution.ErrBlobUnknown
}
func (rbgs *remoteBlobGetterService) Open(ctx context.Context, dgst digest.Digest) (distribution.ReadSeekCloser, error) {
context.GetLogger(ctx).Debugf("(*remoteBlobGetterService).Open: starting with dgst=%s", dgst.String())
store, ok := rbgs.digestToStore[dgst.String()]
if ok {
return store.Open(ctx, dgst)
}
desc, err := rbgs.Stat(ctx, dgst)
if err != nil {
context.GetLogger(ctx).Errorf("Open: failed to stat blob %q in remote repositories: %v", dgst.String(), err)
return nil, err
}
store, ok = rbgs.digestToStore[desc.Digest.String()]
if !ok {
return nil, distribution.ErrBlobUnknown
}
return store.Open(ctx, desc.Digest)
}
func (rbgs *remoteBlobGetterService) ServeBlob(ctx context.Context, w http.ResponseWriter, req *http.Request, dgst digest.Digest) error {
context.GetLogger(ctx).Debugf("(*remoteBlobGetterService).ServeBlob: starting with dgst=%s", dgst.String())
store, ok := rbgs.digestToStore[dgst.String()]
if ok {
return store.ServeBlob(ctx, w, req, dgst)
}
desc, err := rbgs.Stat(ctx, dgst)
if err != nil {
context.GetLogger(ctx).Errorf("ServeBlob: failed to stat blob %q in remote repositories: %v", dgst.String(), err)
return err
}
store, ok = rbgs.digestToStore[desc.Digest.String()]
if !ok {
return distribution.ErrBlobUnknown
}
return store.ServeBlob(ctx, w, req, desc.Digest)
}
// proxyStat attempts to locate the digest in the provided remote repository or returns an error. If the digest is found,
// rbgs.digestToStore saves the store.
func (rbgs *remoteBlobGetterService) proxyStat(
ctx context.Context,
retriever importer.RepositoryRetriever,
spec *imagePullthroughSpec,
dgst digest.Digest,
) (distribution.Descriptor, error) {
ref := spec.dockerImageReference
insecureNote := ""
if spec.insecure {
insecureNote = " with a fall-back to insecure transport"
}
context.GetLogger(ctx).Infof("Trying to stat %q from %q%s", dgst, ref.AsRepository().Exact(), insecureNote)
repo, err := retriever.Repository(ctx, ref.RegistryURL(), ref.RepositoryName(), spec.insecure)
if err != nil {
context.GetLogger(ctx).Errorf("Error getting remote repository for image %q: %v", ref.AsRepository().Exact(), err)
return distribution.Descriptor{}, err
}
pullthroughBlobStore := repo.Blobs(ctx)
desc, err := pullthroughBlobStore.Stat(ctx, dgst)
if err != nil {
if err != distribution.ErrBlobUnknown {
context.GetLogger(ctx).Errorf("Error statting blob %s in remote repository %q: %v", dgst, ref.AsRepository().Exact(), err)
}
return distribution.Descriptor{}, err
}
rbgs.digestToStore[dgst.String()] = pullthroughBlobStore
return desc, nil
}
// Get attempts to fetch the requested blob by digest using a remote proxy store if necessary.
func (rbgs *remoteBlobGetterService) Get(ctx context.Context, dgst digest.Digest) ([]byte, error) {
context.GetLogger(ctx).Debugf("(*remoteBlobGetterService).Get: starting with dgst=%s", dgst.String())
store, ok := rbgs.digestToStore[dgst.String()]
if ok {
return store.Get(ctx, dgst)
}
desc, err := rbgs.Stat(ctx, dgst)
if err != nil {
context.GetLogger(ctx).Errorf("Get: failed to stat blob %q in remote repositories: %v", dgst.String(), err)
return nil, err
}
store, ok = rbgs.digestToStore[desc.Digest.String()]
if !ok {
return nil, distribution.ErrBlobUnknown
}
return store.Get(ctx, desc.Digest)
}
// findCandidateRepository looks in search for a particular blob, referring to previously cached items
func (rbgs *remoteBlobGetterService) findCandidateRepository(
ctx context.Context,
repositoryCandidates []string,
search map[string]imagePullthroughSpec,
cachedRepos []string,
dgst digest.Digest,
retriever importer.RepositoryRetriever,
) (distribution.Descriptor, error) {
// no possible remote locations to search, exit early
if len(search) == 0 {
return distribution.Descriptor{}, distribution.ErrBlobUnknown
}
// see if any of the previously located repositories containing this digest are in this
// image stream
for _, repo := range cachedRepos {
spec, ok := search[repo]
if !ok {
continue
}
desc, err := rbgs.proxyStat(ctx, retriever, &spec, dgst)
if err != nil {
delete(search, repo)
continue
}
context.GetLogger(ctx).Infof("Found digest location from cache %q in %q", dgst, repo)
return desc, nil
}
// search the remaining registries for this digest
for _, repo := range repositoryCandidates {
spec, ok := search[repo]
if !ok {
continue
}
desc, err := rbgs.proxyStat(ctx, retriever, &spec, dgst)
if err != nil {
continue
}
_ = rbgs.cache.AddDigest(dgst, repo)
context.GetLogger(ctx).Infof("Found digest location by search %q in %q", dgst, repo)
return desc, nil
}
return distribution.Descriptor{}, distribution.ErrBlobUnknown
}
type byInsecureFlag struct {
repositories []string
specs []*imagePullthroughSpec
}
func (by *byInsecureFlag) Len() int {
if len(by.specs) < len(by.repositories) {
return len(by.specs)
}
return len(by.repositories)
}
func (by *byInsecureFlag) Swap(i, j int) {
by.repositories[i], by.repositories[j] = by.repositories[j], by.repositories[i]
by.specs[i], by.specs[j] = by.specs[j], by.specs[i]
}
func (by *byInsecureFlag) Less(i, j int) bool {
if by.specs[i].insecure == by.specs[j].insecure {
switch {
case by.repositories[i] < by.repositories[j]:
return true
case by.repositories[i] > by.repositories[j]:
return false
default:
return by.specs[i].dockerImageReference.Exact() < by.specs[j].dockerImageReference.Exact()
}
}
return !by.specs[i].insecure
}
// identifyCandidateRepositories returns a list of remote repository names sorted from the best candidate to
// the worst and a map of remote repositories referenced by this image stream. The best candidate is a secure
// one. The worst allows for insecure transport.
func identifyCandidateRepositories(
is *imageapiv1.ImageStream,
localRegistry string,
primary bool,
) ([]string, map[string]imagePullthroughSpec) {
insecureByDefault := false
if insecure, ok := is.Annotations[imageapi.InsecureRepositoryAnnotation]; ok {
insecureByDefault = insecure == "true"
}
// maps registry to insecure flag
insecureRegistries := make(map[string]bool)
// identify the canonical location of referenced registries to search
search := make(map[string]*imageapi.DockerImageReference)
for _, tagEvent := range is.Status.Tags {
tag := tagEvent.Tag
var candidates []imageapiv1.TagEvent
if primary {
if len(tagEvent.Items) == 0 {
continue
}
candidates = tagEvent.Items[:1]
} else {
if len(tagEvent.Items) <= 1 {
continue
}
candidates = tagEvent.Items[1:]
}
for _, event := range candidates {
ref, err := imageapi.ParseDockerImageReference(event.DockerImageReference)
if err != nil {
continue
}
// skip anything that matches the innate registry
// TODO: there may be a better way to make this determination
if len(localRegistry) != 0 && localRegistry == ref.Registry {
continue
}
ref = ref.DockerClientDefaults()
insecure := insecureByDefault
for _, t := range is.Spec.Tags {
if t.Name == tag {
insecure = insecureByDefault || t.ImportPolicy.Insecure
break
}
}
if is := insecureRegistries[ref.Registry]; !is && insecure {
insecureRegistries[ref.Registry] = insecure
}
search[ref.AsRepository().Exact()] = &ref
}
}
repositories := make([]string, 0, len(search))
results := make(map[string]imagePullthroughSpec)
specs := []*imagePullthroughSpec{}
for repo, ref := range search {
repositories = append(repositories, repo)
// accompany the reference with corresponding registry's insecure flag
spec := imagePullthroughSpec{
dockerImageReference: ref,
insecure: insecureRegistries[ref.Registry],
}
results[repo] = spec
specs = append(specs, &spec)
}
sort.Sort(&byInsecureFlag{repositories: repositories, specs: specs})
return repositories, results
}
// pullInsecureByDefault returns true if the given repository or repository's tag allows for insecure
// transport.
func pullInsecureByDefault(isGetter ImageStreamGetter, tag string) bool {
insecureByDefault := false
is, err := isGetter()
if err != nil {
return insecureByDefault
}
if insecure, ok := is.Annotations[imageapi.InsecureRepositoryAnnotation]; ok {
insecureByDefault = insecure == "true"
}
if insecureByDefault || len(tag) == 0 {
return insecureByDefault
}
for _, t := range is.Spec.Tags {
if t.Name == tag {
return t.ImportPolicy.Insecure
}
}
return false
}