/
cids.go
82 lines (64 loc) 路 1.42 KB
/
cids.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
package registry
import (
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
)
// cidStore contains known cid entries.
type cidStore struct {
// maps repo:tag -> cid
cids map[string]string
location string
sync.RWMutex
}
func key(repo, ref string) string {
return repo + ":" + ref
}
func (r *cidStore) Add(repo, reference string, cid string) {
r.Lock()
k := key(repo, reference)
r.cids[k] = cid
// only store name:tag reference
if repo != cid && !strings.HasPrefix(reference, "sha256:") {
r.writeCID(k, cid)
}
r.Unlock()
}
func (r *cidStore) Get(repo, reference string) (string, bool) {
r.RLock()
k := key(repo, reference)
val, ok := r.cids[k]
if !ok {
if v, err := r.readCID(k); err == nil {
val = v
ok = true
}
}
r.RUnlock()
return val, ok
}
func (r *cidStore) readCID(key string) (string, error) {
pc := strings.SplitN(key, ":", 2)
p := filepath.Join(r.location, strings.Join(pc, "/"))
content, err := ioutil.ReadFile(p)
if err != nil {
return "", err
}
return string(content), nil
}
func (r *cidStore) writeCID(key string, val string) error {
pc := strings.SplitN(key, ":", 2)
p := filepath.Join(r.location, strings.Join(pc, "/"))
if err := os.MkdirAll(filepath.Dir(p), os.ModePerm); err != nil {
return err
}
return ioutil.WriteFile(p, []byte(val), 0644)
}
func newCIDStore(location string) *cidStore {
return &cidStore{
cids: map[string]string{},
location: location,
}
}