blob: f476de65dbe96f3f668b9b41c85562e8be485192 [file] [edit]
// Copyright 2026 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package project
import (
"cmp"
"context"
"encoding/json"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"go.fuchsia.dev/jiri"
"go.fuchsia.dev/jiri/cipd"
)
// PackageCacheFormatVersionFileName is the filename in the package cache root
// that records the schema version of the central package cache.
const PackageCacheFormatVersionFileName = ".jiri_cache_format_version"
// CurrentPackageCacheFormatVersion is the current format version of the package cache.
// Caches with a missing or older format version are wiped and re-initialized cleanly.
const CurrentPackageCacheFormatVersion = 2
// PackageCache manages the central package cache directory (`.jiri_root/packages`).
//
// In Jiri, the central package cache serves as the single source of truth for
// downloaded CIPD package payloads across all active workspaces and worktrees.
// It stores immutable package instances in content-addressed directories under
// `instances/<instance_id>`, manages the global non-blocking synchronization lock
// (`.cache.lock`), and coordinates CIPD ensure synchronization and pruning.
type PackageCache struct {
root string
}
// NewPackageCache constructs a new PackageCache manager for the specified cache root.
func NewPackageCache(root string) *PackageCache {
return &PackageCache{root: root}
}
// Root returns the root directory of the package cache.
func (c *PackageCache) Root() string {
return c.root
}
// InstanceDir returns the absolute directory path where a package instance is installed in cache.
func (c *PackageCache) InstanceDir(inst PackageCacheInstance) string {
return filepath.Join(c.root, filepath.FromSlash(inst.Subdir()))
}
// InstanceExists checks if the instance directory exists in the cache.
func (c *PackageCache) InstanceExists(inst PackageCacheInstance) bool {
fi, err := os.Stat(c.InstanceDir(inst))
return err == nil && fi.IsDir()
}
// Lock acquires an exclusive, non-blocking lock on `.cache.lock` within the cache root.
// This guarantees fail-fast concurrency control across concurrent Jiri processes
// or active worktrees running package synchronization.
// Returns an unlock function to release the lock, or an error if acquisition fails.
func (c *PackageCache) Lock() (unlock func(), err error) {
return AcquireCacheLock(c.root)
}
// LockWithContext acquires an exclusive lock on `.cache.lock` within the cache root,
// waiting until the lock becomes available or ctx is canceled.
func (c *PackageCache) LockWithContext(ctx context.Context) (unlock func(), err error) {
return AcquireCacheLockWithContext(ctx, c.root)
}
// reset wipes all cached instances and metadata in the package cache root
// and writes CurrentPackageCacheFormatVersion.
// The caller must already hold cache.Lock() before calling reset.
func (c *PackageCache) reset() error {
if err := os.MkdirAll(c.root, 0755); err != nil {
return err
}
entries, err := os.ReadDir(c.root)
if err != nil {
return err
}
for _, entry := range entries {
// Preserve .cache.lock because this process currently holds the exclusive
// flock on its open file descriptor; unlinking the path would allow a
// concurrent process to O_CREATE a new .cache.lock inode and acquire a
// second flock while reset and sync are still in progress.
if entry.Name() == ".cache.lock" {
continue
}
target := filepath.Join(c.root, entry.Name())
if entry.IsDir() {
makeDirectoriesWritable(target)
}
if err := os.RemoveAll(target); err != nil {
return err
}
}
return c.writeFormatVersion()
}
// hasCachedData reports whether the cache directory contains any entries
// other than .cache.lock and PackageCacheFormatVersionFileName.
func (c *PackageCache) hasCachedData() bool {
entries, err := os.ReadDir(c.root)
if err != nil {
return false
}
for _, entry := range entries {
switch entry.Name() {
case ".cache.lock", PackageCacheFormatVersionFileName:
continue
default:
return true
}
}
return false
}
// Sync runs CIPD cache synchronization using the provided CIPDEnsureFile.
// It writes the ensure specification to `instance_master.ensure` and invokes CIPD ensure,
// which validates, repairs, downloads, and natively prunes unreferenced instances
// under `instances/<instance_id>`. The caller must hold cache.Lock() before calling Sync.
func (c *PackageCache) Sync(ctx context.Context, ensureFile *CIPDEnsureFile, timeout uint) error {
checkout := jiri.CheckoutFromContext(ctx)
if err := os.MkdirAll(c.root, 0755); err != nil {
return err
}
// In non-paranoid mode, CIPD assumes packages are intact if their metadata
// slot in .cipd/pkgs exists and does not check the filesystem. If an instance
// directory is missing or corrupted, clean up any corrupted file and remove the
// corresponding .cipd/pkgs metadata slot so CIPD notices and redeploys it.
for _, inst := range ensureFile.Instances() {
instDir := c.InstanceDir(inst)
fi, err := os.Lstat(instDir)
if err != nil || !fi.IsDir() {
if err == nil {
_ = os.RemoveAll(instDir)
}
c.removeCIPDPkgForInstance(inst.InstanceID)
}
}
masterEnsurePath := filepath.Join(c.root, "instance_master.ensure")
if err := ensureFile.Write(masterEnsurePath, checkout.CipdParanoidMode); err != nil {
return err
}
defer os.Remove(masterEnsurePath)
jiri.TimerPush(ctx, "cipd package cache sync")
defer jiri.TimerPop(ctx)
return cipd.Ensure(ctx, masterEnsurePath, c.root, timeout)
}
// InstalledInstances returns all package instances currently recorded in
// .cipd/pkgs/*/description.json whose instance directories exist in the cache.
func (c *PackageCache) InstalledInstances() []PackageCacheInstance {
pkgsDir := filepath.Join(c.root, ".cipd", "pkgs")
entries, err := os.ReadDir(pkgsDir)
if err != nil {
return nil
}
var installed []PackageCacheInstance
for _, entry := range entries {
if !entry.IsDir() {
continue
}
descPath := filepath.Join(pkgsDir, entry.Name(), "description.json")
descBytes, err := os.ReadFile(descPath)
if err != nil {
continue
}
var desc struct {
Subdir string `json:"subdir"`
PackageName string `json:"package_name"`
}
if err := json.Unmarshal(descBytes, &desc); err != nil {
continue
}
const prefix = "instances/"
if !strings.HasPrefix(desc.Subdir, prefix) || desc.PackageName == "" {
continue
}
instID := strings.TrimPrefix(desc.Subdir, prefix)
if instID == "" || strings.Contains(instID, "/") || instID == "." || instID == ".." {
continue
}
inst := PackageCacheInstance{
Name: desc.PackageName,
Version: instID,
InstanceID: instID,
}
if c.InstanceExists(inst) {
installed = append(installed, inst)
}
}
slices.SortFunc(installed, func(a, b PackageCacheInstance) int {
return cmp.Or(cmp.Compare(a.Name, b.Name), cmp.Compare(a.InstanceID, b.InstanceID))
})
return installed
}
// BuildSubsetEnsureFile constructs a CIPDEnsureFile combining all currently
// installed cache instances from InstalledInstances() with the given missing
// instances so that CIPD ensure does not prune existing cached packages.
func (c *PackageCache) BuildSubsetEnsureFile(missing []PackageCacheInstance) *CIPDEnsureFile {
ensureFile := NewCIPDEnsureFile()
for _, inst := range c.InstalledInstances() {
ensureFile.AddInstance(inst)
}
for _, inst := range missing {
ensureFile.AddInstance(inst)
}
return ensureFile
}
// SyncSubset downloads the given missing instances into the package cache
// without pruning already-cached instances in .cipd/pkgs.
// The caller must hold the cache lock before calling SyncSubset.
func (c *PackageCache) SyncSubset(ctx context.Context, missing []PackageCacheInstance, timeout uint) error {
return c.syncMissingInstances(ctx, missing, timeout, nil)
}
func (c *PackageCache) syncMissingInstances(ctx context.Context, missing []PackageCacheInstance, timeout uint, fetcher InstanceFetcher) error {
if len(missing) == 0 {
return nil
}
wasEmpty := c.isEmptyExceptLock()
if fetcher != nil {
for _, inst := range missing {
if err := fetcher(ctx, inst, c.InstanceDir(inst), timeout); err != nil {
return err
}
}
} else {
ensureFile := c.BuildSubsetEnsureFile(missing)
if err := c.Sync(ctx, ensureFile, timeout); err != nil {
return err
}
}
if wasEmpty {
if err := c.writeFormatVersion(); err != nil {
return err
}
}
return nil
}
func (c *PackageCache) isEmptyExceptLock() bool {
entries, err := os.ReadDir(c.root)
if err != nil {
return os.IsNotExist(err)
}
for _, entry := range entries {
if entry.Name() != ".cache.lock" {
return false
}
}
return true
}
func (c *PackageCache) isFormatVersionCurrent() bool {
versionPath := filepath.Join(c.root, PackageCacheFormatVersionFileName)
data, err := os.ReadFile(versionPath)
if err != nil {
return false
}
v, err := strconv.Atoi(strings.TrimSpace(string(data)))
return err == nil && v >= CurrentPackageCacheFormatVersion
}
func (c *PackageCache) writeFormatVersion() error {
versionPath := filepath.Join(c.root, PackageCacheFormatVersionFileName)
return os.WriteFile(versionPath, []byte(strconv.Itoa(CurrentPackageCacheFormatVersion)+"\n"), 0644)
}
// removeCIPDPkgForInstance removes the .cipd/pkgs metadata directory associated
// with instID. When an instance directory is missing on disk, cleaning up the
// corresponding CIPD package slot forces CIPD to re-deploy it during ensure.
func (c *PackageCache) removeCIPDPkgForInstance(instID string) {
pkgsDir := filepath.Join(c.root, ".cipd", "pkgs")
entries, err := os.ReadDir(pkgsDir)
if err != nil {
return
}
for _, entry := range entries {
if !entry.IsDir() {
continue
}
pDir := filepath.Join(pkgsDir, entry.Name())
descBytes, err := os.ReadFile(filepath.Join(pDir, "description.json"))
if err == nil && strings.Contains(string(descBytes), instID) {
_ = os.RemoveAll(pDir)
continue
}
if _, err := os.Stat(filepath.Join(pDir, instID)); err == nil {
_ = os.RemoveAll(pDir)
continue
}
}
}