forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
digestcache.go
93 lines (81 loc) · 2.18 KB
/
digestcache.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
package server
import (
"sync"
"github.com/hashicorp/golang-lru"
"github.com/docker/distribution/digest"
)
// digestToRepositoryCache maps image digests to recently seen remote repositories that
// may contain that digest. Each digest is bucketed and remembering new repositories will
// push old repositories out.
type digestToRepositoryCache struct {
*lru.Cache
}
// newDigestToRepositoryCache creates a new LRU cache of image digests to possible remote
// repository strings with the given size. It returns an error if the cache
// cannot be created.
func newDigestToRepositoryCache(size int) (digestToRepositoryCache, error) {
c, err := lru.New(size)
if err != nil {
return digestToRepositoryCache{}, err
}
return digestToRepositoryCache{Cache: c}, nil
}
const bucketSize = 10
// RememberDigest associates a digest with a repository.
func (c digestToRepositoryCache) RememberDigest(dgst digest.Digest, repo string) {
key := dgst.String()
value, ok := c.Get(key)
if !ok {
value = &repositoryBucket{}
if ok, _ := c.ContainsOrAdd(key, value); !ok {
return
}
}
repos := value.(*repositoryBucket)
repos.Add(repo)
}
// RepositoriesForDigest returns a list of repositories that may contain this digest.
func (c digestToRepositoryCache) RepositoriesForDigest(dgst digest.Digest) []string {
value, ok := c.Get(dgst.String())
if !ok {
return nil
}
repos := value.(*repositoryBucket)
return repos.Copy()
}
type repositoryBucket struct {
mu sync.Mutex
list []string
}
// Has returns true if the bucket contains this repository.
func (i *repositoryBucket) Has(repo string) bool {
i.mu.Lock()
defer i.mu.Unlock()
for _, s := range i.list {
if s == repo {
return true
}
}
return false
}
// Add one or more repositories to this bucket.
func (i *repositoryBucket) Add(repos ...string) {
i.mu.Lock()
defer i.mu.Unlock()
arr := i.list
for _, repo := range repos {
if len(arr) >= bucketSize {
arr = arr[1:]
}
arr = append(arr, repo)
}
i.list = arr
}
// Copy returns a copy of the contents of this bucket in a threadsafe fasion.
func (i *repositoryBucket) Copy() []string {
i.mu.Lock()
defer i.mu.Unlock()
out := make([]string, len(i.list))
copy(out, i.list)
return out
}