From 92537e556aad8096a2761f501e6fac357bab14fa Mon Sep 17 00:00:00 2001 From: Nir Soffer Date: Wed, 13 Nov 2024 22:18:16 +0200 Subject: [PATCH 1/5] Add failing redownload test We tested that modified last modified time on the server cause a redownload, but we did not test that after a redownload we update the cache, so the next attempt will used the cached download. Add a failing test verifying the issue, and improve test comments and configuration to make it more clear. Part-of: #2902 Signed-off-by: Nir Soffer --- pkg/downloader/downloader_test.go | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/pkg/downloader/downloader_test.go b/pkg/downloader/downloader_test.go index 2e4483194cb..8ee94fd747b 100644 --- a/pkg/downloader/downloader_test.go +++ b/pkg/downloader/downloader_test.go @@ -203,18 +203,26 @@ func TestRedownloadRemote(t *testing.T) { assert.NilError(t, os.Chtimes(remoteFile, time.Now(), time.Now().Add(-time.Hour))) opt := []Opt{cacheOpt} - r, err := Download(context.Background(), filepath.Join(downloadDir, "digest-less1.txt"), ts.URL+"/digest-less.txt", opt...) + // Download on the first call + r, err := Download(context.Background(), filepath.Join(downloadDir, "1"), ts.URL+"/digest-less.txt", opt...) assert.NilError(t, err) assert.Equal(t, StatusDownloaded, r.Status) - r, err = Download(context.Background(), filepath.Join(downloadDir, "digest-less2.txt"), ts.URL+"/digest-less.txt", opt...) + + // Next download will use the cached download + r, err = Download(context.Background(), filepath.Join(downloadDir, "2"), ts.URL+"/digest-less.txt", opt...) assert.NilError(t, err) assert.Equal(t, StatusUsedCache, r.Status) - // modifying remote file will cause redownload + // Modifying remote file will cause redownload assert.NilError(t, os.Chtimes(remoteFile, time.Now(), time.Now())) - r, err = Download(context.Background(), filepath.Join(downloadDir, "digest-less3.txt"), ts.URL+"/digest-less.txt", opt...) + r, err = Download(context.Background(), filepath.Join(downloadDir, "3"), ts.URL+"/digest-less.txt", opt...) assert.NilError(t, err) assert.Equal(t, StatusDownloaded, r.Status) + + // Next download will use the cached download + r, err = Download(context.Background(), filepath.Join(downloadDir, "4"), ts.URL+"/digest-less.txt", opt...) + assert.NilError(t, err) + assert.Equal(t, StatusUsedCache, r.Status) }) t.Run("has-digest", func(t *testing.T) { From 8b90a0a0c52d86fdaed836e9961702e771ddaeda Mon Sep 17 00:00:00 2001 From: Nir Soffer Date: Thu, 14 Nov 2024 04:30:04 +0200 Subject: [PATCH 2/5] Split Download() to smaller functions Extract getCache() to handle getting and file from the cache, and fetch() for fetching a file from the remote to the cache. This will allow locking around the code checking and updating the cache, and much easier to maintain and understand. Signed-off-by: Nir Soffer --- pkg/downloader/downloader.go | 86 +++++++++++++++++++++++------------- 1 file changed, 56 insertions(+), 30 deletions(-) diff --git a/pkg/downloader/downloader.go b/pkg/downloader/downloader.go index ade98bd3b90..5f1f729b90d 100644 --- a/pkg/downloader/downloader.go +++ b/pkg/downloader/downloader.go @@ -229,6 +229,20 @@ func Download(ctx context.Context, local, remote string, opts ...Opt) (*Result, return res, nil } + res, err := getCached(ctx, localPath, remote, o) + if err != nil { + return nil, err + } + if res != nil { + return res, nil + } + return fetch(ctx, localPath, remote, o) +} + +// getCached tries to copy the file from the cache to local path. Return result, +// nil if the file was copied, nil, nil if the file is not in the cache or the +// cache needs update, or nil, error on fatal error. +func getCached(ctx context.Context, localPath, remote string, o options) (*Result, error) { shad := cacheDirectoryPath(o.cacheDir, remote) shadData := filepath.Join(shad, "data") shadTime := filepath.Join(shad, "time") @@ -237,41 +251,53 @@ func Download(ctx context.Context, local, remote string, opts ...Opt) (*Result, if err != nil { return nil, err } - if _, err := os.Stat(shadData); err == nil { - logrus.Debugf("file %q is cached as %q", localPath, shadData) - useCache := true - if _, err := os.Stat(shadDigest); err == nil { - logrus.Debugf("Comparing digest %q with the cached digest file %q, not computing the actual digest of %q", - o.expectedDigest, shadDigest, shadData) - if err := validateCachedDigest(shadDigest, o.expectedDigest); err != nil { - return nil, err - } - if err := copyLocal(ctx, localPath, shadData, ext, o.decompress, "", ""); err != nil { + if _, err := os.Stat(shadData); err != nil { + return nil, nil + } + ext := path.Ext(remote) + logrus.Debugf("file %q is cached as %q", localPath, shadData) + if _, err := os.Stat(shadDigest); err == nil { + logrus.Debugf("Comparing digest %q with the cached digest file %q, not computing the actual digest of %q", + o.expectedDigest, shadDigest, shadData) + if err := validateCachedDigest(shadDigest, o.expectedDigest); err != nil { + return nil, err + } + if err := copyLocal(ctx, localPath, shadData, ext, o.decompress, "", ""); err != nil { + return nil, err + } + } else { + if match, lmCached, lmRemote, err := matchLastModified(ctx, shadTime, remote); err != nil { + logrus.WithError(err).Info("Failed to retrieve last-modified for cached digest-less image; using cached image.") + } else if match { + if err := copyLocal(ctx, localPath, shadData, ext, o.decompress, o.description, o.expectedDigest); err != nil { return nil, err } } else { - if match, lmCached, lmRemote, err := matchLastModified(ctx, shadTime, remote); err != nil { - logrus.WithError(err).Info("Failed to retrieve last-modified for cached digest-less image; using cached image.") - } else if match { - if err := copyLocal(ctx, localPath, shadData, ext, o.decompress, o.description, o.expectedDigest); err != nil { - return nil, err - } - } else { - logrus.Infof("Re-downloading digest-less image: last-modified mismatch (cached: %q, remote: %q)", lmCached, lmRemote) - useCache = false - } - } - if useCache { - res := &Result{ - Status: StatusUsedCache, - CachePath: shadData, - LastModified: readTime(shadTime), - ContentType: readFile(shadType), - ValidatedDigest: o.expectedDigest != "", - } - return res, nil + logrus.Infof("Re-downloading digest-less image: last-modified mismatch (cached: %q, remote: %q)", lmCached, lmRemote) + return nil, nil } } + res := &Result{ + Status: StatusUsedCache, + CachePath: shadData, + LastModified: readTime(shadTime), + ContentType: readFile(shadType), + ValidatedDigest: o.expectedDigest != "", + } + return res, nil +} + +// fetch downloads remote to the cache and copy the cached file to local path. +func fetch(ctx context.Context, localPath, remote string, o options) (*Result, error) { + shad := cacheDirectoryPath(o.cacheDir, remote) + shadData := filepath.Join(shad, "data") + shadTime := filepath.Join(shad, "time") + shadType := filepath.Join(shad, "type") + shadDigest, err := cacheDigestPath(shad, o.expectedDigest) + if err != nil { + return nil, err + } + ext := path.Ext(remote) if err := os.MkdirAll(shad, 0o700); err != nil { return nil, err } From 76d5c8638899e378cef09e28d47bb9bcf6a8d96a Mon Sep 17 00:00:00 2001 From: Nir Soffer Date: Thu, 14 Nov 2024 04:49:00 +0200 Subject: [PATCH 3/5] Lock cache directory during download To solve the races during concurrent downloads and avoid unneeded work and bandwidth, we allow one concurrent download of the same image. When a limactl process try to access the cache, it takes a lock on the file cache directory. If multiple processes try to get the lock in the same time, only one will take the lock, and the other will block. The process that took the lock tries to get the file from the cache. This is the fast path and the common case. This can fail if the file is not in the cache, the digest does not match, or the cached last modified time does not match the last modified returned from the server. If the process cannot get the file from the cache, it downloads the file from the remote server, and update the cached data and metadata files. Finally the process release the lock on the cache directory. Other limactl processes waiting on the lock wake up and take the lock. In the common case they will find the image in the cache and will release the lock quickly. Since we have exactly one concurrent download, updating the metadata files is trivial and we don't need the writeFirst() helper. Fixes: #2902 Fixes: #2732 Signed-off-by: Nir Soffer --- pkg/downloader/downloader.go | 60 +++++++++++++----------------------- 1 file changed, 22 insertions(+), 38 deletions(-) diff --git a/pkg/downloader/downloader.go b/pkg/downloader/downloader.go index 5f1f729b90d..1d278af0666 100644 --- a/pkg/downloader/downloader.go +++ b/pkg/downloader/downloader.go @@ -229,14 +229,25 @@ func Download(ctx context.Context, local, remote string, opts ...Opt) (*Result, return res, nil } - res, err := getCached(ctx, localPath, remote, o) - if err != nil { + shad := cacheDirectoryPath(o.cacheDir, remote) + if err := os.MkdirAll(shad, 0o700); err != nil { return nil, err } - if res != nil { - return res, nil - } - return fetch(ctx, localPath, remote, o) + + var res *Result + err := lockutil.WithDirLock(shad, func() error { + var err error + res, err = getCached(ctx, localPath, remote, o) + if err != nil { + return err + } + if res != nil { + return nil + } + res, err = fetch(ctx, localPath, remote, o) + return err + }) + return res, err } // getCached tries to copy the file from the cache to local path. Return result, @@ -298,18 +309,15 @@ func fetch(ctx context.Context, localPath, remote string, o options) (*Result, e return nil, err } ext := path.Ext(remote) - if err := os.MkdirAll(shad, 0o700); err != nil { - return nil, err - } shadURL := filepath.Join(shad, "url") - if err := writeFirst(shadURL, []byte(remote), 0o644); err != nil { + if err := os.WriteFile(shadURL, []byte(remote), 0o644); err != nil { return nil, err } if err := downloadHTTP(ctx, shadData, shadTime, shadType, remote, o.description, o.expectedDigest); err != nil { return nil, err } if shadDigest != "" && o.expectedDigest != "" { - if err := writeFirst(shadDigest, []byte(o.expectedDigest.String()), 0o644); err != nil { + if err := os.WriteFile(shadDigest, []byte(o.expectedDigest.String()), 0o644); err != nil { return nil, err } } @@ -638,13 +646,13 @@ func downloadHTTP(ctx context.Context, localPath, lastModified, contentType, url } if lastModified != "" { lm := resp.Header.Get("Last-Modified") - if err := writeFirst(lastModified, []byte(lm), 0o644); err != nil { + if err := os.WriteFile(lastModified, []byte(lm), 0o644); err != nil { return err } } if contentType != "" { ct := resp.Header.Get("Content-Type") - if err := writeFirst(contentType, []byte(ct), 0o644); err != nil { + if err := os.WriteFile(contentType, []byte(ct), 0o644); err != nil { return err } } @@ -705,19 +713,7 @@ func downloadHTTP(ctx context.Context, localPath, lastModified, contentType, url return err } - // If localPath was created by a parallel download keep it. Replacing it - // while another process is copying it to the destination may fail the - // clonefile syscall. We use a lock to ensure that only one process updates - // data, and when we return data file exists. - - return lockutil.WithDirLock(filepath.Dir(localPath), func() error { - if _, err := os.Stat(localPath); err == nil { - return nil - } else if !errors.Is(err, os.ErrNotExist) { - return err - } - return os.Rename(localPathTmp, localPath) - }) + return os.Rename(localPathTmp, localPath) } var tempfileCount atomic.Uint64 @@ -732,18 +728,6 @@ func perProcessTempfile(path string) string { return fmt.Sprintf("%s.tmp.%d.%d", path, os.Getpid(), tempfileCount.Add(1)) } -// writeFirst writes data to path unless path already exists. -func writeFirst(path string, data []byte, perm os.FileMode) error { - return lockutil.WithDirLock(filepath.Dir(path), func() error { - if _, err := os.Stat(path); err == nil { - return nil - } else if !errors.Is(err, os.ErrNotExist) { - return err - } - return os.WriteFile(path, data, perm) - }) -} - // CacheEntries returns a map of cache entries. // The key is the SHA256 of the URL. // The value is the path to the cache entry. From c1b4d72e4d10118e444775b46cb225a511158c02 Mon Sep 17 00:00:00 2001 From: Nir Soffer Date: Thu, 14 Nov 2024 05:42:37 +0200 Subject: [PATCH 4/5] Make parallel downloads test more strict We can assert now that only one thread downloaded the file, and all other threads used the cache. Signed-off-by: Nir Soffer --- pkg/downloader/downloader_test.go | 52 +++++++++++++++++-------------- 1 file changed, 28 insertions(+), 24 deletions(-) diff --git a/pkg/downloader/downloader_test.go b/pkg/downloader/downloader_test.go index 8ee94fd747b..045805bc00d 100644 --- a/pkg/downloader/downloader_test.go +++ b/pkg/downloader/downloader_test.go @@ -8,7 +8,6 @@ import ( "os/exec" "path/filepath" "runtime" - "slices" "strings" "testing" "time" @@ -31,11 +30,6 @@ type downloadResult struct { // races quicker. 20 parallel downloads take about 120 milliseconds on M1 Pro. const parallelDownloads = 20 -// When downloading in parallel usually all downloads completed with -// StatusDownload, but some may be delayed and find the data file when they -// start. Can be reproduced locally using 100 parallel downloads. -var parallelStatus = []Status{StatusDownloaded, StatusUsedCache} - func TestDownloadRemote(t *testing.T) { ts := httptest.NewServer(http.FileServer(http.Dir("testdata"))) t.Cleanup(ts.Close) @@ -103,15 +97,10 @@ func TestDownloadRemote(t *testing.T) { results <- downloadResult{r, err} }() } - // We must process all results before cleanup. - for i := 0; i < parallelDownloads; i++ { - result := <-results - if result.err != nil { - t.Errorf("Download failed: %s", result.err) - } else if !slices.Contains(parallelStatus, result.r.Status) { - t.Errorf("Expected download status %s, got %s", parallelStatus, result.r.Status) - } - } + // Only one thread should download, the rest should use the cache. + downloaded, cached := countResults(t, results) + assert.Equal(t, downloaded, 1) + assert.Equal(t, cached, parallelDownloads-1) }) }) t.Run("caching-only mode", func(t *testing.T) { @@ -146,15 +135,10 @@ func TestDownloadRemote(t *testing.T) { results <- downloadResult{r, err} }() } - // We must process all results before cleanup. - for i := 0; i < parallelDownloads; i++ { - result := <-results - if result.err != nil { - t.Errorf("Download failed: %s", result.err) - } else if !slices.Contains(parallelStatus, result.r.Status) { - t.Errorf("Expected download status %s, got %s", parallelStatus, result.r.Status) - } - } + // Only one thread should download, the rest should use the cache. + downloaded, cached := countResults(t, results) + assert.Equal(t, downloaded, 1) + assert.Equal(t, cached, parallelDownloads-1) }) }) t.Run("cached", func(t *testing.T) { @@ -188,6 +172,26 @@ func TestDownloadRemote(t *testing.T) { }) } +func countResults(t *testing.T, results chan downloadResult) (downloaded, cached int) { + t.Helper() + for i := 0; i < parallelDownloads; i++ { + result := <-results + if result.err != nil { + t.Errorf("Download failed: %s", result.err) + } else { + switch result.r.Status { + case StatusDownloaded: + downloaded++ + case StatusUsedCache: + cached++ + default: + t.Errorf("Unexpected download status %q", result.r.Status) + } + } + } + return downloaded, cached +} + func TestRedownloadRemote(t *testing.T) { remoteDir := t.TempDir() ts := httptest.NewServer(http.FileServer(http.Dir(remoteDir))) From 5071535b06b67172e2bf68c03c2698d19db1f9b4 Mon Sep 17 00:00:00 2001 From: Nir Soffer Date: Thu, 14 Nov 2024 22:22:24 +0200 Subject: [PATCH 5/5] Fix race in dowloader.Cached() Checking if an image is cached races with parallel downloads. Take the lock when validating the digest or the data file to ensure that we validate the cached when it is in consistent state. If an image is being downloaded, the check will block until the download completes. Signed-off-by: Nir Soffer --- pkg/downloader/downloader.go | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/pkg/downloader/downloader.go b/pkg/downloader/downloader.go index 1d278af0666..8a3160854c7 100644 --- a/pkg/downloader/downloader.go +++ b/pkg/downloader/downloader.go @@ -361,18 +361,33 @@ func Cached(remote string, opts ...Opt) (*Result, error) { if err != nil { return nil, err } + + // Checking if data file exists is safe without locking. if _, err := os.Stat(shadData); err != nil { return nil, err } - if _, err := os.Stat(shadDigest); err != nil { - if err := validateCachedDigest(shadDigest, o.expectedDigest); err != nil { - return nil, err - } - } else { - if err := validateLocalFileDigest(shadData, o.expectedDigest); err != nil { - return nil, err + + // But validating the digest or the data file must take the lock to avoid races + // with parallel downloads. + if err := os.MkdirAll(shad, 0o700); err != nil { + return nil, err + } + err = lockutil.WithDirLock(shad, func() error { + if _, err := os.Stat(shadDigest); err != nil { + if err := validateCachedDigest(shadDigest, o.expectedDigest); err != nil { + return err + } + } else { + if err := validateLocalFileDigest(shadData, o.expectedDigest); err != nil { + return err + } } + return nil + }) + if err != nil { + return nil, err } + res := &Result{ Status: StatusUsedCache, CachePath: shadData,