Debian Codegraph @

content/oci/oci.go

raw
1 /*
2 Copyright The ORAS Authors.
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 */
15
16 // Package oci provides access to an OCI content store.
17 // Reference: https://github.com/opencontainers/image-spec/blob/v1.1.1/image-layout.md
18 package oci
19
20 import (
21 "context"
22 "encoding/json"
23 "errors"
24 "fmt"
25 "io"
26 "maps"
27 "os"
28 "path"
29 "path/filepath"
30 "sync"
31
32 "github.com/opencontainers/go-digest"
33 specs "github.com/opencontainers/image-spec/specs-go"
34 ocispec "github.com/opencontainers/image-spec/specs-go/v1"
35 "oras.land/oras-go/v2/content"
36 "oras.land/oras-go/v2/errdef"
37 "oras.land/oras-go/v2/internal/container/set"
38 "oras.land/oras-go/v2/internal/descriptor"
39 "oras.land/oras-go/v2/internal/graph"
40 "oras.land/oras-go/v2/internal/manifestutil"
41 "oras.land/oras-go/v2/internal/resolver"
42 "oras.land/oras-go/v2/registry"
43 )
44
45 // Store implements `oras.Target`, and represents a content store
46 // based on file system with the OCI-Image layout.
47 // Reference: https://github.com/opencontainers/image-spec/blob/v1.1.1/image-layout.md
48 type Store struct {
49 // AutoSaveIndex controls if the OCI store will automatically save the index
50 // file when needed.
51 // - If AutoSaveIndex is set to true, the OCI store will automatically save
52 // the changes to `index.json` when
53 // 1. pushing a manifest
54 // 2. calling Tag() or Delete()
55 // - If AutoSaveIndex is set to false, it's the caller's responsibility
56 // to manually call SaveIndex() when needed.
57 // - Default value: true.
58 AutoSaveIndex bool
59
60 // AutoGC controls if the OCI store will automatically clean dangling
61 // (unreferenced) blobs created by the Delete() operation. This includes the
62 // referrers and the unreferenced successor blobs of the deleted content.
63 // Tagged manifests will not be deleted.
64 // - Default value: true.
65 AutoGC bool
66
67 root string
68 indexPath string
69 index *ocispec.Index
70 storage *Storage
71 tagResolver *resolver.Memory
72 graph *graph.Memory
73
74 // sync ensures that most operations can be done concurrently, while Delete
75 // has the exclusive access to Store if a delete operation is underway.
76 // Operations such as Fetch, Push use sync.RLock(), while Delete uses
77 // sync.Lock().
78 sync sync.RWMutex
79 // indexLock ensures that only one go-routine is writing to the index.
80 indexLock sync.Mutex
81 }
82
83 // New creates a new OCI store with context.Background().
84 func New(root string) (*Store, error) {
85 return NewWithContext(context.Background(), root)
86 }
87
88 // NewWithContext creates a new OCI store.
89 func NewWithContext(ctx context.Context, root string) (*Store, error) {
90 rootAbs, err := filepath.Abs(root)
91 if err != nil {
92 return nil, fmt.Errorf("failed to resolve absolute path for %s: %w", root, err)
93 }
94 storage, err := NewStorage(rootAbs)
95 if err != nil {
96 return nil, fmt.Errorf("failed to create storage: %w", err)
97 }
98
99 store := &Store{
100 AutoSaveIndex: true,
101 AutoGC: true,
102 root: rootAbs,
103 indexPath: filepath.Join(rootAbs, ocispec.ImageIndexFile),
104 storage: storage,
105 tagResolver: resolver.NewMemory(),
106 graph: graph.NewMemory(),
107 }
108
109 if err := ensureDir(filepath.Join(rootAbs, ocispec.ImageBlobsDir)); err != nil {
110 return nil, err
111 }
112 if err := store.ensureOCILayoutFile(); err != nil {
113 return nil, fmt.Errorf("invalid OCI Image Layout: %w", err)
114 }
115 if err := store.loadIndexFile(ctx); err != nil {
116 return nil, fmt.Errorf("invalid OCI Image Index: %w", err)
117 }
118
119 return store, nil
120 }
121
122 // Fetch fetches the content identified by the descriptor. It returns an io.ReadCloser.
123 // It's recommended to close the io.ReadCloser before a Delete operation, otherwise
124 // Delete may fail (for example on NTFS file systems).
125 func (s *Store) Fetch(ctx context.Context, target ocispec.Descriptor) (io.ReadCloser, error) {
126 s.sync.RLock()
127 defer s.sync.RUnlock()
128
129 return s.storage.Fetch(ctx, target)
130 }
131
132 // Push pushes the content, matching the expected descriptor.
133 func (s *Store) Push(ctx context.Context, expected ocispec.Descriptor, reader io.Reader) error {
134 s.sync.RLock()
135 defer s.sync.RUnlock()
136
137 if err := s.storage.Push(ctx, expected, reader); err != nil {
138 return err
139 }
140 if err := s.graph.Index(ctx, s.storage, expected); err != nil {
141 return err
142 }
143 if descriptor.IsManifest(expected) {
144 // tag by digest
145 return s.tag(ctx, expected, expected.Digest.String())
146 }
147 return nil
148 }
149
150 // Exists returns true if the described content exists.
151 func (s *Store) Exists(ctx context.Context, target ocispec.Descriptor) (bool, error) {
152 s.sync.RLock()
153 defer s.sync.RUnlock()
154
155 return s.storage.Exists(ctx, target)
156 }
157
158 // Delete deletes the content matching the descriptor from the store. Delete may
159 // fail on certain systems (i.e. NTFS), if there is a process (i.e. an unclosed
160 // Reader) using target.
161 // - If s.AutoGC is set to true, Delete will recursively
162 // remove the dangling blobs caused by the current delete.
163 // - If s.AutoDeleteReferrers is set to true, Delete will recursively remove
164 // the referrers of the manifests being deleted.
165 func (s *Store) Delete(ctx context.Context, target ocispec.Descriptor) error {
166 s.sync.Lock()
167 defer s.sync.Unlock()
168
169 deleteQueue := []ocispec.Descriptor{target}
170 for len(deleteQueue) > 0 {
171 head := deleteQueue[0]
172 deleteQueue = deleteQueue[1:]
173
174 // get referrers if applicable
175 if s.AutoGC && descriptor.IsManifest(head) {
176 referrers, err := registry.Referrers(ctx, &unsafeStore{s}, head, "")
177 if err != nil {
178 return err
179 }
180 deleteQueue = append(deleteQueue, referrers...)
181 }
182
183 // delete the head of queue
184 danglings, err := s.delete(ctx, head)
185 if err != nil {
186 return err
187 }
188 if s.AutoGC {
189 for _, d := range danglings {
190 // do not delete existing tagged manifests
191 if !s.isTagged(d) {
192 deleteQueue = append(deleteQueue, d)
193 }
194 }
195 }
196 }
197
198 return nil
199 }
200
201 // delete deletes one node and returns the dangling nodes caused by the delete.
202 func (s *Store) delete(ctx context.Context, target ocispec.Descriptor) ([]ocispec.Descriptor, error) {
203 resolvers := s.tagResolver.Map()
204 untagged := false
205 for reference, desc := range resolvers {
206 if content.Equal(desc, target) {
207 s.tagResolver.Untag(reference)
208 untagged = true
209 }
210 }
211 danglings := s.graph.Remove(target)
212 if untagged && s.AutoSaveIndex {
213 err := s.saveIndex()
214 if err != nil {
215 return nil, err
216 }
217 }
218 if err := s.storage.Delete(ctx, target); err != nil {
219 return nil, err
220 }
221 return danglings, nil
222 }
223
224 // Tag associates a reference string (e.g. "latest") with the descriptor.
225 // The reference string is recorded in the "org.opencontainers.image.ref.name"
226 // annotation of the descriptor. When saved, the updated descriptor is persisted
227 // in the `index.json` file.
228 //
229 // - If the same reference string is tagged multiple times on different
230 // descriptors, the descriptor from the last call will be stored.
231 // - If the same descriptor is tagged multiple times with different reference
232 // strings, multiple copies of the descriptor with different reference tags
233 // will be stored in the `index.json` file.
234 //
235 // Reference: https://github.com/opencontainers/image-spec/blob/v1.1.1/image-layout.md#indexjson-file
236 func (s *Store) Tag(ctx context.Context, desc ocispec.Descriptor, reference string) error {
237 s.sync.RLock()
238 defer s.sync.RUnlock()
239
240 if err := validateReference(reference); err != nil {
241 return err
242 }
243
244 exists, err := s.storage.Exists(ctx, desc)
245 if err != nil {
246 return err
247 }
248 if !exists {
249 return fmt.Errorf("%s: %s: %w", desc.Digest, desc.MediaType, errdef.ErrNotFound)
250 }
251
252 return s.tag(ctx, desc, reference)
253 }
254
255 // tag tags a descriptor with a reference string.
256 func (s *Store) tag(ctx context.Context, desc ocispec.Descriptor, reference string) error {
257 dgst := desc.Digest.String()
258 if reference != dgst {
259 // also tag desc by its digest
260 if err := s.tagResolver.Tag(ctx, desc, dgst); err != nil {
261 return err
262 }
263 }
264 if err := s.tagResolver.Tag(ctx, desc, reference); err != nil {
265 return err
266 }
267 if s.AutoSaveIndex {
268 return s.saveIndex()
269 }
270 return nil
271 }
272
273 // Resolve resolves a reference to a descriptor.
274 // - If the reference to be resolved is a tag, the returned descriptor will be
275 // a full descriptor declared by github.com/opencontainers/image-spec/specs-go/v1.
276 // - If the reference is a digest, the returned descriptor will be a
277 // plain descriptor (containing only the digest, media type and size).
278 func (s *Store) Resolve(ctx context.Context, reference string) (ocispec.Descriptor, error) {
279 s.sync.RLock()
280 defer s.sync.RUnlock()
281
282 if reference == "" {
283 return ocispec.Descriptor{}, errdef.ErrMissingReference
284 }
285
286 // attempt resolving manifest
287 desc, err := s.tagResolver.Resolve(ctx, reference)
288 if err != nil {
289 if errors.Is(err, errdef.ErrNotFound) {
290 // attempt resolving blob
291 return resolveBlob(os.DirFS(s.root), reference)
292 }
293 return ocispec.Descriptor{}, err
294 }
295
296 if reference == desc.Digest.String() {
297 return descriptor.Plain(desc), nil
298 }
299
300 return desc, nil
301 }
302
303 // Untag disassociates a reference string from its descriptor.
304 // When saved, the descriptor entry cotanining the reference in the
305 // "org.opencontainers.image.ref.name" annotation is removed from the
306 // `index.json` file.
307 // The actual content identified by the descriptor is NOT deleted.
308 //
309 // Reference: https://github.com/opencontainers/image-spec/blob/v1.1.1/image-layout.md#indexjson-file
310 func (s *Store) Untag(ctx context.Context, reference string) error {
311 if reference == "" {
312 return errdef.ErrMissingReference
313 }
314
315 s.sync.RLock()
316 defer s.sync.RUnlock()
317
318 desc, err := s.tagResolver.Resolve(ctx, reference)
319 if err != nil {
320 return fmt.Errorf("resolving reference %q: %w", reference, err)
321 }
322 if reference == desc.Digest.String() {
323 return fmt.Errorf("reference %q is a digest and not a tag: %w", reference, errdef.ErrInvalidReference)
324 }
325
326 s.tagResolver.Untag(reference)
327 if s.AutoSaveIndex {
328 return s.saveIndex()
329 }
330 return nil
331 }
332
333 // Predecessors returns the nodes directly pointing to the current node.
334 // Predecessors returns nil without error if the node does not exists in the
335 // store.
336 func (s *Store) Predecessors(ctx context.Context, node ocispec.Descriptor) ([]ocispec.Descriptor, error) {
337 s.sync.RLock()
338 defer s.sync.RUnlock()
339
340 return s.graph.Predecessors(ctx, node)
341 }
342
343 // Tags lists the tags presented in the `index.json` file of the OCI layout,
344 // returned in ascending order.
345 // If `last` is NOT empty, the entries in the response start after the tag
346 // specified by `last`. Otherwise, the response starts from the top of the tags
347 // list.
348 //
349 // See also `Tags()` in the package `registry`.
350 func (s *Store) Tags(ctx context.Context, last string, fn func(tags []string) error) error {
351 s.sync.RLock()
352 defer s.sync.RUnlock()
353
354 return listTags(s.tagResolver, last, fn)
355 }
356
357 // ensureOCILayoutFile ensures the `oci-layout` file.
358 func (s *Store) ensureOCILayoutFile() error {
359 layoutFilePath := filepath.Join(s.root, ocispec.ImageLayoutFile)
360 layoutFile, err := os.Open(layoutFilePath)
361 if err != nil {
362 if !os.IsNotExist(err) {
363 return fmt.Errorf("failed to open OCI layout file: %w", err)
364 }
365
366 layout := ocispec.ImageLayout{
367 Version: ocispec.ImageLayoutVersion,
368 }
369 layoutJSON, err := json.Marshal(layout)
370 if err != nil {
371 return fmt.Errorf("failed to marshal OCI layout file: %w", err)
372 }
373 return os.WriteFile(layoutFilePath, layoutJSON, 0666)
374 }
375 defer layoutFile.Close()
376
377 var layout ocispec.ImageLayout
378 err = json.NewDecoder(layoutFile).Decode(&layout)
379 if err != nil {
380 return fmt.Errorf("failed to decode OCI layout file: %w", err)
381 }
382 return validateOCILayout(&layout)
383 }
384
385 // loadIndexFile reads index.json from the file system.
386 // Create index.json if it does not exist.
387 func (s *Store) loadIndexFile(ctx context.Context) error {
388 indexFile, err := os.Open(s.indexPath)
389 if err != nil {
390 if !os.IsNotExist(err) {
391 return fmt.Errorf("failed to open index file: %w", err)
392 }
393
394 // write index.json if it does not exist
395 s.index = &ocispec.Index{
396 Versioned: specs.Versioned{
397 SchemaVersion: 2, // historical value
398 },
399 MediaType: ocispec.MediaTypeImageIndex,
400 Manifests: []ocispec.Descriptor{},
401 }
402 return s.writeIndexFile()
403 }
404 defer indexFile.Close()
405
406 var index ocispec.Index
407 if err := json.NewDecoder(indexFile).Decode(&index); err != nil {
408 return fmt.Errorf("failed to decode index file: %w", err)
409 }
410 s.index = &index
411 return loadIndex(ctx, s.index, s.storage, s.tagResolver, s.graph)
412 }
413
414 // SaveIndex writes the `index.json` file to the file system.
415 // - If AutoSaveIndex is set to true (default value),
416 // the OCI store will automatically save the changes to `index.json`
417 // on Tag() and Delete() calls, and when pushing a manifest.
418 // - If AutoSaveIndex is set to false, it's the caller's responsibility
419 // to manually call this method when needed.
420 func (s *Store) SaveIndex() error {
421 s.sync.RLock()
422 defer s.sync.RUnlock()
423
424 return s.saveIndex()
425 }
426
427 func (s *Store) saveIndex() error {
428 s.indexLock.Lock()
429 defer s.indexLock.Unlock()
430
431 var manifests []ocispec.Descriptor
432 tagged := set.New[digest.Digest]()
433 refMap := s.tagResolver.Map()
434
435 // 1. Add descriptors that are associated with tags
436 // Note: One descriptor can be associated with multiple tags.
437 for ref, desc := range refMap {
438 if ref != desc.Digest.String() {
439 annotations := make(map[string]string, len(desc.Annotations)+1)
440 maps.Copy(annotations, desc.Annotations)
441 annotations[ocispec.AnnotationRefName] = ref
442 desc.Annotations = annotations
443 manifests = append(manifests, desc)
444 // mark the digest as tagged for deduplication in step 2
445 tagged.Add(desc.Digest)
446 }
447 }
448 // 2. Add descriptors that are not associated with any tag
449 for ref, desc := range refMap {
450 if ref == desc.Digest.String() && !tagged.Contains(desc.Digest) {
451 // skip tagged ones since they have been added in step 1
452 manifests = append(manifests, deleteAnnotationRefName(desc))
453 }
454 }
455
456 s.index.Manifests = manifests
457 return s.writeIndexFile()
458 }
459
460 // writeIndexFile writes the `index.json` file.
461 func (s *Store) writeIndexFile() error {
462 indexJSON, err := json.Marshal(s.index)
463 if err != nil {
464 return fmt.Errorf("failed to marshal index file: %w", err)
465 }
466 return os.WriteFile(s.indexPath, indexJSON, 0666)
467 }
468
469 // GC removes garbage from Store. Unsaved index will be lost. To prevent unexpected
470 // loss, call SaveIndex() before GC or set AutoSaveIndex to true.
471 // The garbage to be cleaned are:
472 // - unreferenced (dangling) blobs in Store which have no predecessors
473 // - garbage blobs in the storage whose metadata is not stored in Store
474 func (s *Store) GC(ctx context.Context) error {
475 s.sync.Lock()
476 defer s.sync.Unlock()
477
478 // get reachable nodes by reloading the index
479 err := s.gcIndex(ctx)
480 if err != nil {
481 return fmt.Errorf("unable to reload index: %w", err)
482 }
483 reachableNodes := s.graph.DigestSet()
484
485 // clean up garbage blobs in the storage
486 rootpath := filepath.Join(s.root, ocispec.ImageBlobsDir)
487 algDirs, err := os.ReadDir(rootpath)
488 if err != nil {
489 return err
490 }
491 for _, algDir := range algDirs {
492 if !algDir.IsDir() {
493 continue
494 }
495 alg := algDir.Name()
496 // skip unsupported directories
497 if !isKnownAlgorithm(alg) {
498 continue
499 }
500 algPath := path.Join(rootpath, alg)
501 digestEntries, err := os.ReadDir(algPath)
502 if err != nil {
503 return err
504 }
505 for _, digestEntry := range digestEntries {
506 if err := isContextDone(ctx); err != nil {
507 return err
508 }
509 dgst := digestEntry.Name()
510 blobDigest := digest.NewDigestFromEncoded(digest.Algorithm(alg), dgst)
511 if err := blobDigest.Validate(); err != nil {
512 // skip irrelevant content
513 continue
514 }
515 if !reachableNodes.Contains(blobDigest) {
516 // remove the blob from storage if it does not exist in Store
517 err = os.Remove(path.Join(algPath, dgst))
518 if err != nil {
519 return err
520 }
521 }
522 }
523 }
524 return nil
525 }
526
527 // gcIndex reloads the index and updates metadata. Information of untagged blobs
528 // are cleaned and only tagged blobs remain.
529 func (s *Store) gcIndex(ctx context.Context) error {
530 tagResolver := resolver.NewMemory()
531 graph := graph.NewMemory()
532 tagged := set.New[digest.Digest]()
533
534 // index tagged manifests
535 refMap := s.tagResolver.Map()
536 for ref, desc := range refMap {
537 if ref == desc.Digest.String() {
538 continue
539 }
540 if err := tagResolver.Tag(ctx, deleteAnnotationRefName(desc), desc.Digest.String()); err != nil {
541 return err
542 }
543 if err := tagResolver.Tag(ctx, desc, ref); err != nil {
544 return err
545 }
546 plain := descriptor.Plain(desc)
547 if err := graph.IndexAll(ctx, s.storage, plain); err != nil {
548 return err
549 }
550 tagged.Add(desc.Digest)
551 }
552
553 // index referrer manifests
554 for ref, desc := range refMap {
555 if ref != desc.Digest.String() || tagged.Contains(desc.Digest) {
556 continue
557 }
558 // check if the referrers manifest can traverse to the existing graph
559 subject := &desc
560 for {
561 subject, err := manifestutil.Subject(ctx, s.storage, *subject)
562 if err != nil {
563 return err
564 }
565 if subject == nil {
566 break
567 }
568 if graph.Exists(*subject) {
569 if err := tagResolver.Tag(ctx, deleteAnnotationRefName(desc), desc.Digest.String()); err != nil {
570 return err
571 }
572 plain := descriptor.Plain(desc)
573 if err := graph.IndexAll(ctx, s.storage, plain); err != nil {
574 return err
575 }
576 break
577 }
578 }
579 }
580 s.tagResolver = tagResolver
581 s.graph = graph
582 return nil
583 }
584
585 // isTagged checks if the blob given by the descriptor is tagged.
586 func (s *Store) isTagged(desc ocispec.Descriptor) bool {
587 tagSet := s.tagResolver.TagSet(desc)
588 if tagSet.Contains(string(desc.Digest)) {
589 return len(tagSet) > 1
590 }
591 return len(tagSet) > 0
592 }
593
594 // unsafeStore is used to bypass lock restrictions in Delete.
595 type unsafeStore struct {
596 *Store
597 }
598
599 func (s *unsafeStore) Fetch(ctx context.Context, target ocispec.Descriptor) (io.ReadCloser, error) {
600 return s.storage.Fetch(ctx, target)
601 }
602
603 func (s *unsafeStore) Predecessors(ctx context.Context, node ocispec.Descriptor) ([]ocispec.Descriptor, error) {
604 return s.graph.Predecessors(ctx, node)
605 }
606
607 // isContextDone returns an error if the context is done.
608 // Reference: https://pkg.go.dev/context#Context
609 func isContextDone(ctx context.Context) error {
610 select {
611 case <-ctx.Done():
612 return ctx.Err()
613 default:
614 return nil
615 }
616 }
617
618 // validateReference validates ref.
619 func validateReference(ref string) error {
620 if ref == "" {
621 return errdef.ErrMissingReference
622 }
623
624 // TODO: may enforce more strict validation if needed.
625 return nil
626 }
627
628 // isKnownAlgorithm checks is a string is a supported hash algorithm
629 func isKnownAlgorithm(alg string) bool {
630 switch digest.Algorithm(alg) {
631 case digest.SHA256, digest.SHA512, digest.SHA384:
632 return true
633 default:
634 return false
635 }
636 }