Debian Codegraph @

store/refs.go

raw
1 /*
2 Copyright The containerd Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package store
18
19 import (
20 "context"
21 "encoding/json"
22 "fmt"
23 "os"
24 "path/filepath"
25 "sync"
26 "time"
27
28 "github.com/containerd/containerd/log"
29 "github.com/containerd/containerd/platforms"
30 "github.com/containerd/containerd/reference"
31 "github.com/containerd/containerd/remotes/docker"
32 "github.com/containerd/stargz-snapshotter/fs/source"
33 "github.com/containerd/stargz-snapshotter/util/cacheutil"
34 "github.com/containerd/stargz-snapshotter/util/containerdutil"
35 digest "github.com/opencontainers/go-digest"
36 ocispec "github.com/opencontainers/image-spec/specs-go/v1"
37 )
38
39 const (
40 refCacheEntry = 30
41 defaultManifestCacheTime = 120 * time.Second
42 )
43
44 func newRefPool(ctx context.Context, root string, hosts source.RegistryHosts) (*refPool, error) {
45 var poolroot = filepath.Join(root, "pool")
46 if err := os.MkdirAll(poolroot, 0700); err != nil {
47 return nil, err
48 }
49 p := &refPool{
50 path: poolroot,
51 hosts: hosts,
52 refcounter: make(map[string]*releaser),
53 }
54 p.cache = cacheutil.NewLRUCache(refCacheEntry)
55 p.cache.OnEvicted = func(key string, value interface{}) {
56 refspec := value.(reference.Spec)
57 if err := os.RemoveAll(p.metadataDir(refspec)); err != nil {
58 log.G(ctx).WithField("key", key).WithError(err).Warnf("failed to clean up ref")
59 return
60 }
61 log.G(ctx).WithField("key", key).Debugf("cleaned up ref")
62 }
63 return p, nil
64 }
65
66 type refPool struct {
67 path string
68 hosts source.RegistryHosts
69
70 refcounter map[string]*releaser
71 cache *cacheutil.LRUCache
72 mu sync.Mutex
73 }
74
75 type releaser struct {
76 count int
77 release func()
78 }
79
80 func (p *refPool) loadRef(ctx context.Context, refspec reference.Spec) (manifest ocispec.Manifest, config ocispec.Image, err error) {
81 manifest, config, err = p.readManifestAndConfig(refspec)
82 if err == nil {
83 log.G(ctx).Debugf("reusing manifest and config of %q", refspec.String())
84 return
85 }
86 log.G(ctx).WithError(err).Debugf("fetching manifest and config of %q", refspec.String())
87 manifest, config, err = p.fetchManifestAndConfig(ctx, refspec)
88 if err != nil {
89 return ocispec.Manifest{}, ocispec.Image{}, err
90 }
91 if err := p.writeManifestAndConfig(refspec, manifest, config); err != nil {
92 return ocispec.Manifest{}, ocispec.Image{}, err
93 }
94 // Cache it so that next immediate call can acquire ref information from that dir.
95 p.mu.Lock()
96 _, done, _ := p.cache.Add(refspec.String(), refspec)
97 p.mu.Unlock()
98 go func() {
99 // Release it after a reasonable amount of time.
100 // If use() funcs are called for this reference, eviction of this won't be done until
101 // all corresponding release() funcs are called.
102 time.Sleep(defaultManifestCacheTime)
103 done()
104 }()
105 return manifest, config, nil
106 }
107
108 func (p *refPool) use(refspec reference.Spec) int {
109 p.mu.Lock()
110 defer p.mu.Unlock()
111
112 r, ok := p.refcounter[refspec.String()]
113 if !ok {
114 _, done, _ := p.cache.Add(refspec.String(), refspec)
115 p.refcounter[refspec.String()] = &releaser{
116 count: 1,
117 release: done,
118 }
119 return 1
120 }
121 r.count++
122 return r.count
123 }
124
125 func (p *refPool) release(refspec reference.Spec) (int, error) {
126 p.mu.Lock()
127 defer p.mu.Unlock()
128
129 r, ok := p.refcounter[refspec.String()]
130 if !ok {
131 return 0, fmt.Errorf("ref %q not tracked", refspec.String())
132 }
133 r.count--
134 if r.count <= 0 {
135 delete(p.refcounter, refspec.String())
136 r.release()
137 return 0, nil
138 }
139 return r.count, nil
140 }
141
142 func (p *refPool) readManifestAndConfig(refspec reference.Spec) (manifest ocispec.Manifest, config ocispec.Image, _ error) {
143 mPath, cPath := p.manifestFile(refspec), p.configFile(refspec)
144 mf, err := os.Open(mPath)
145 if err != nil {
146 return ocispec.Manifest{}, ocispec.Image{}, err
147 }
148 defer mf.Close()
149 if err := json.NewDecoder(mf).Decode(&manifest); err != nil {
150 return ocispec.Manifest{}, ocispec.Image{}, err
151 }
152 cf, err := os.Open(cPath)
153 if err != nil {
154 return ocispec.Manifest{}, ocispec.Image{}, err
155 }
156 defer cf.Close()
157 if err := json.NewDecoder(cf).Decode(&config); err != nil {
158 return ocispec.Manifest{}, ocispec.Image{}, err
159 }
160 return manifest, config, nil
161 }
162
163 func (p *refPool) writeManifestAndConfig(refspec reference.Spec, manifest ocispec.Manifest, config ocispec.Image) error {
164 mPath, cPath := p.manifestFile(refspec), p.configFile(refspec)
165 if err := os.MkdirAll(filepath.Dir(mPath), 0700); err != nil {
166 return err
167 }
168 if err := os.MkdirAll(filepath.Dir(cPath), 0700); err != nil {
169 return err
170 }
171 mf, err := os.Create(mPath)
172 if err != nil {
173 return err
174 }
175 defer mf.Close()
176 if err := json.NewEncoder(mf).Encode(&manifest); err != nil {
177 return err
178 }
179 cf, err := os.Create(cPath)
180 if err != nil {
181 return err
182 }
183 defer cf.Close()
184 return json.NewEncoder(cf).Encode(&config)
185 }
186
187 func (p *refPool) fetchManifestAndConfig(ctx context.Context, refspec reference.Spec) (ocispec.Manifest, ocispec.Image, error) {
188 // temporary resolver. should only be used for resolving `refpec`.
189 resolver := docker.NewResolver(docker.ResolverOptions{
190 Hosts: func(host string) ([]docker.RegistryHost, error) {
191 if host != refspec.Hostname() {
192 return nil, fmt.Errorf("unexpected host %q for image ref %q", host, refspec.String())
193 }
194 return p.hosts(refspec)
195 },
196 })
197 _, img, err := resolver.Resolve(ctx, refspec.String())
198 if err != nil {
199 return ocispec.Manifest{}, ocispec.Image{}, err
200 }
201 fetcher, err := resolver.Fetcher(ctx, refspec.String())
202 if err != nil {
203 return ocispec.Manifest{}, ocispec.Image{}, err
204 }
205 plt := platforms.DefaultSpec() // TODO: should we make this configurable?
206 manifest, err := containerdutil.FetchManifestPlatform(ctx, fetcher, img, plt)
207 if err != nil {
208 return ocispec.Manifest{}, ocispec.Image{}, err
209 }
210 r, err := fetcher.Fetch(ctx, manifest.Config)
211 if err != nil {
212 return ocispec.Manifest{}, ocispec.Image{}, err
213 }
214 defer r.Close()
215 var config ocispec.Image
216 if err := json.NewDecoder(r).Decode(&config); err != nil {
217 return ocispec.Manifest{}, ocispec.Image{}, err
218 }
219
220 return manifest, config, nil
221 }
222
223 func (p *refPool) root() string {
224 return p.path
225 }
226
227 func (p *refPool) metadataDir(refspec reference.Spec) string {
228 return filepath.Join(p.path, "metadata--"+colon2dash(digest.FromString(refspec.String()).String()))
229 }
230
231 func (p *refPool) manifestFile(refspec reference.Spec) string {
232 return filepath.Join(p.metadataDir(refspec), "manifest")
233 }
234
235 func (p *refPool) configFile(refspec reference.Spec) string {
236 return filepath.Join(p.metadataDir(refspec), "config")
237 }