ensure that new index does not break on missing lock file

Signed-off-by: Avi Deitcher <avi@deitcher.net>
This commit is contained in:
Avi Deitcher 2025-06-27 10:07:42 +03:00
parent 254aefc953
commit 54adc7ddd5

View File

@ -2,6 +2,7 @@ package cache
import ( import (
"fmt" "fmt"
"os"
"path/filepath" "path/filepath"
"github.com/google/go-containerregistry/pkg/v1/empty" "github.com/google/go-containerregistry/pkg/v1/empty"
@ -10,19 +11,29 @@ import (
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
var (
newIndexLockFile = filepath.Join(os.TempDir(), "linuxkit-new-cache-index.lock")
)
// Get get or initialize the cache // Get get or initialize the cache
func Get(cache string) (layout.Path, error) { func Get(cache string) (layout.Path, error) {
// initialize the cache path if needed // initialize the cache path if needed
p, err := layout.FromPath(cache) p, err := layout.FromPath(cache)
if err != nil { if err != nil {
lock, err := util.Lock(filepath.Join(cache, indexFile)) if err := os.WriteFile(newIndexLockFile, []byte{}, 0644); err != nil {
return "", fmt.Errorf("unable to create lock file %s for writing descriptor for new cache %s: %v", newIndexLockFile, cache, err)
}
lock, err := util.Lock(newIndexLockFile)
if err != nil { if err != nil {
return "", fmt.Errorf("unable to lock cache index for writing descriptor for new cache: %v", err) return "", fmt.Errorf("unable to retrieve lock for writing descriptor for new cache %s: %v", newIndexLockFile, err)
} }
defer func() { defer func() {
if err := lock.Unlock(); err != nil { if err := lock.Unlock(); err != nil {
log.Errorf("unable to close lock for cache index after writing descriptor for new cache: %v", err) log.Errorf("unable to close lock for cache index after writing descriptor for new cache: %v", err)
} }
if err := os.RemoveAll(newIndexLockFile); err != nil {
log.Errorf("unable to remove lock file %s after writing descriptor for new cache: %v", newIndexLockFile, err)
}
}() }()
p, err = layout.Write(cache, empty.Index) p, err = layout.Write(cache, empty.Index)
if err != nil { if err != nil {