...

Source file src/edge-infra.dev/pkg/f8n/warehouse/oci/cache/providers/disk/disk.go

Documentation: edge-infra.dev/pkg/f8n/warehouse/oci/cache/providers/disk

     1  package disk
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path"
     7  	"path/filepath"
     8  	"sync"
     9  
    10  	"github.com/google/go-containerregistry/pkg/name"
    11  
    12  	"edge-infra.dev/pkg/f8n/warehouse/oci"
    13  	"edge-infra.dev/pkg/f8n/warehouse/oci/layout"
    14  )
    15  
    16  // Cache is a thread-safe wrapper around an OCI Image Layout with functionality
    17  // for purging.
    18  type Cache struct {
    19  	sync.RWMutex
    20  	path *layout.Path
    21  }
    22  
    23  // New returns a new instance of the disk Cache.
    24  func New(layoutPath *layout.Path) *Cache {
    25  	return &Cache{path: layoutPath}
    26  }
    27  
    28  // FromPath returns a new instance of the disk Cache from an existing path.
    29  func FromPath(path string) (*Cache, error) {
    30  	layoutPath, err := layout.New(path)
    31  	if err != nil {
    32  		return nil, err
    33  	}
    34  	return &Cache{path: layoutPath}, nil
    35  }
    36  
    37  // Get fetches an oci artifact from an oci layout path.
    38  func (d *Cache) Get(ref name.Reference) (oci.Artifact, error) {
    39  	d.RLock()
    40  	defer d.RUnlock()
    41  	a, err := d.path.Get(ref)
    42  	if err != nil {
    43  		return nil, err
    44  	}
    45  	return a, nil
    46  }
    47  
    48  // Exists check if an oci artifact exists in the oci layout path.
    49  func (d *Cache) Exists(ref name.Reference) bool {
    50  	// TODO(aw18576): not needed because we will lock in Get?
    51  	// d.RLock()
    52  	// defer d.RUnlock()
    53  	_, err := d.path.Get(ref)
    54  	return err == nil
    55  }
    56  
    57  // Add appends an oci artifact to a layout path.
    58  func (d *Cache) Add(ref name.Reference, a oci.Artifact) error {
    59  	d.Lock()
    60  	defer d.Unlock()
    61  	return d.path.Append(ref, a)
    62  }
    63  
    64  // Purge deletes an oci layout path from disk.
    65  func (d *Cache) Purge() error {
    66  	layoutPath := string(d.path.Path)
    67  	contents, err := filepath.Glob(path.Join(layoutPath, "/*"))
    68  	if err != nil {
    69  		return err
    70  	}
    71  	for _, item := range contents {
    72  		err = os.RemoveAll(item)
    73  		if err != nil {
    74  			return err
    75  		}
    76  	}
    77  	np, err := layout.New(layoutPath)
    78  	if err != nil {
    79  		return fmt.Errorf("failed to re-instantiate empty layout: %w", err)
    80  	}
    81  	d.path = np
    82  	return nil
    83  }
    84  

View as plain text