ensure that new index does not break on missing lock file (#4134)

Signed-off-by: Avi Deitcher <avi@deitcher.net>
This commit is contained in:
Avi Deitcher 2025-06-27 11:01:43 +03:00 committed by GitHub
parent 254aefc953
commit 50120bce2d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -2,6 +2,7 @@ package cache
import (
"fmt"
"os"
"path/filepath"
"github.com/google/go-containerregistry/pkg/v1/empty"
@ -10,19 +11,29 @@ import (
log "github.com/sirupsen/logrus"
)
var (
newIndexLockFile = filepath.Join(os.TempDir(), "linuxkit-new-cache-index.lock")
)
// Get get or initialize the cache
func Get(cache string) (layout.Path, error) {
// initialize the cache path if needed
p, err := layout.FromPath(cache)
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 {
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() {
if err := lock.Unlock(); err != nil {
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)
if err != nil {