From 6a7c3df703ebf6f9fa90f575e150449c7cfe1c41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmed=20Semih=20=C3=96zmekik?= Date: Wed, 4 Nov 2026 15:10:50 +0300 Subject: [PATCH 1/5] fix: expire cache entries unused for a week after a cut The cache grows forever since nothing ever calls Cache.Expire. Call it after a successful cut with a one week timeout. Opening an entry refreshes its mtime, so this only removes entries no cut has read in that time, and a failure to expire is logged rather than failing the cut. Expire now also skips entries that disappear while it runs, so two expiries over the same cache don't fail on each other's removals. Fixes #261 --- cmd/chisel/cmd_cut.go | 18 ++++++++++++++++-- internal/cache/cache.go | 7 ++++++- internal/cache/cache_test.go | 31 +++++++++++++++++++++++++++++++ tests/cache-expiry/task.yaml | 36 ++++++++++++++++++++++++++++++++++++ 4 files changed, 89 insertions(+), 3 deletions(-) create mode 100644 tests/cache-expiry/task.yaml diff --git a/cmd/chisel/cmd_cut.go b/cmd/chisel/cmd_cut.go index 35c81a79a..37c06c5be 100644 --- a/cmd/chisel/cmd_cut.go +++ b/cmd/chisel/cmd_cut.go @@ -29,6 +29,9 @@ var cutDescs = map[string]string{ "ignore": "Conditions to ignore (e.g. unmaintained, unstable)", } +// cacheExpiry is how long a cache entry can go unused before a cut removes it. +const cacheExpiry = 7 * 24 * time.Hour + type cmdCut struct { Release string `long:"release" value-name:""` RootDir string `long:"root" value-name:"" required:"yes"` @@ -78,6 +81,7 @@ func (cmd *cmdCut) Execute(args []string) error { return err } + cacheDir := cache.DefaultDir("chisel") archives := make(map[string]archive.Archive) for archiveName, archiveInfo := range release.Archives { openArchive, err := archive.Open(&archive.Options{ @@ -87,7 +91,7 @@ func (cmd *cmdCut) Execute(args []string) error { Suites: archiveInfo.Suites, Components: archiveInfo.Components, Pro: archiveInfo.Pro, - CacheDir: cache.DefaultDir("chisel"), + CacheDir: cacheDir, PubKeys: archiveInfo.PubKeys, Maintained: archiveInfo.Maintained, OldRelease: archiveInfo.OldRelease, @@ -126,5 +130,15 @@ func (cmd *cmdCut) Execute(args []string) error { Archives: archives, TargetDir: cmd.RootDir, }) - return err + if err != nil { + return err + } + + // Reading an entry refreshes its timestamp, so this only drops what no + // cut has used for a while. Failing to clean up is not a failed cut. + cc := &cache.Cache{Dir: cacheDir} + if err := cc.Expire(cacheExpiry); err != nil { + logf("Warning: cannot expire cache entries: %v", err) + } + return nil } diff --git a/internal/cache/cache.go b/internal/cache/cache.go index 3b5621ecc..3a440e1a9 100644 --- a/internal/cache/cache.go +++ b/internal/cache/cache.go @@ -199,7 +199,12 @@ func (c *Cache) Expire(timeout time.Duration) error { return fmt.Errorf("cannot list cache directory: %v", err) } for _, entry := range entries { + // Entries may vanish while listing, e.g. renamed from .tmp by + // a writer or removed by a concurrent expiry. finfo, err := entry.Info() + if os.IsNotExist(err) { + continue + } if err != nil { return err } @@ -207,7 +212,7 @@ func (c *Cache) Expire(timeout time.Duration) error { continue } err = os.Remove(filepath.Join(digestKindDir, finfo.Name())) - if err != nil { + if err != nil && !os.IsNotExist(err) { return fmt.Errorf("cannot expire cache entry: %v", err) } } diff --git a/internal/cache/cache_test.go b/internal/cache/cache_test.go index 7267a2e85..c57fb9747 100644 --- a/internal/cache/cache_test.go +++ b/internal/cache/cache_test.go @@ -1,6 +1,7 @@ package cache_test import ( + "fmt" "io" "os" "path/filepath" @@ -303,3 +304,33 @@ func (s *S) TestCacheExpireNoDigestKindDirs(c *C) { err := cc.Expire(time.Hour) c.Assert(err, IsNil) } + +func (s *S) TestCacheExpireConcurrent(c *C) { + cc := cache.Cache{Dir: c.MkDir()} + dir := filepath.Join(cc.Dir, "sha256") + err := os.MkdirAll(dir, 0755) + c.Assert(err, IsNil) + + expiredTime := time.Now().Add(-2 * time.Hour) + for i := 0; i < 2000; i++ { + name := filepath.Join(dir, fmt.Sprintf("%064x", i)) + err := os.WriteFile(name, nil, 0644) + c.Assert(err, IsNil) + err = os.Chtimes(name, expiredTime, expiredTime) + c.Assert(err, IsNil) + } + + // Expiries running at the same time remove entries the others have + // listed too, and must not fail because of it. + errs := make(chan error, 4) + for i := 0; i < 4; i++ { + go func() { errs <- cc.Expire(time.Hour) }() + } + for i := 0; i < 4; i++ { + c.Assert(<-errs, IsNil) + } + + entries, err := os.ReadDir(dir) + c.Assert(err, IsNil) + c.Assert(entries, HasLen, 0) +} diff --git a/tests/cache-expiry/task.yaml b/tests/cache-expiry/task.yaml new file mode 100644 index 000000000..fcb2db404 --- /dev/null +++ b/tests/cache-expiry/task.yaml @@ -0,0 +1,36 @@ +summary: Cache entries that no cut has used for a week are expired + +execute: | + cache_dir=${XDG_CACHE_HOME:-$HOME/.cache}/chisel + rootfs_folder=rootfs_${RELEASE} + + EXTRA_OPTIONS="" + if [ "$RELEASE" = "23.10" -o "$RELEASE" = "20.04" ]; then + EXTRA_OPTIONS="--ignore=unmaintained " + fi + + mkdir -p ${rootfs_folder}_1 ${rootfs_folder}_2 + chisel cut --release ${OS}-${RELEASE} --root ${rootfs_folder}_1 \ + $EXTRA_OPTIONS base-passwd_data + + # Find the cached base-passwd deb and backdate it, and add a stale entry + # that no cut uses. + used="" + for f in ${cache_dir}/sha256/*; do + if [ "$(dpkg-deb -f "$f" Package 2>/dev/null)" = "base-passwd" ]; then + used=$f + fi + done + test -n "$used" + stale=${cache_dir}/sha256/$(echo stale | sha256sum | cut -d' ' -f1) + echo stale > $stale + touch -d "8 days ago" $used $stale + + chisel cut --release ${OS}-${RELEASE} --root ${rootfs_folder}_2 \ + $EXTRA_OPTIONS base-passwd_data + + # The stale entry is gone. The deb was used again, so it is kept, with a + # fresh timestamp. + test ! -e $stale + test -e $used + test $(( $(date +%s) - $(stat -c %Y $used) )) -lt 3600 From 73ef2ff9b5f69c312cd688f5e0b97294dc679342 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmed=20Semih=20=C3=96zmekik?= Date: Wed, 4 Nov 2026 15:17:08 +0300 Subject: [PATCH 2/5] test: look for the deb in every digest directory --- tests/cache-expiry/task.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/cache-expiry/task.yaml b/tests/cache-expiry/task.yaml index fcb2db404..efafb72fe 100644 --- a/tests/cache-expiry/task.yaml +++ b/tests/cache-expiry/task.yaml @@ -13,10 +13,10 @@ execute: | chisel cut --release ${OS}-${RELEASE} --root ${rootfs_folder}_1 \ $EXTRA_OPTIONS base-passwd_data - # Find the cached base-passwd deb and backdate it, and add a stale entry - # that no cut uses. + # Find the cached base-passwd deb (under the strongest digest the archive + # offers) and backdate it, and add a stale entry that no cut uses. used="" - for f in ${cache_dir}/sha256/*; do + for f in ${cache_dir}/sha*/*; do if [ "$(dpkg-deb -f "$f" Package 2>/dev/null)" = "base-passwd" ]; then used=$f fi From d3206649c697f69cd6bda409748019789371a942 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmed=20Semih=20=C3=96zmekik?= Date: Wed, 4 Nov 2026 21:46:32 +0300 Subject: [PATCH 3/5] fix: only expire files chisel wrote, and keep going past failures Expire removed anything old under the digest directories, and the first entry it could not remove stopped the whole run. It now only looks at regular files named like a digest of that kind, or like the temporary files of an unfinished write, and returns the first failure after trying every entry. The concurrent expiry test depended on scheduling. It is replaced by a test that removes an entry between listing and removal on purpose. --- internal/cache/cache.go | 58 ++++++++++++----- internal/cache/cache_test.go | 115 +++++++++++++++++++++++++++++----- internal/cache/export_test.go | 3 + 3 files changed, 148 insertions(+), 28 deletions(-) create mode 100644 internal/cache/export_test.go diff --git a/internal/cache/cache.go b/internal/cache/cache.go index 3a440e1a9..50f9956b0 100644 --- a/internal/cache/cache.go +++ b/internal/cache/cache.go @@ -7,8 +7,10 @@ import ( "fmt" "hash" "io" + "io/fs" "os" "path/filepath" + "regexp" "time" "golang.org/x/crypto/sha3" @@ -102,6 +104,15 @@ const ( var digestKinds = []DigestKind{SHA256, SHA384, SHA512} +// entryNames matches the names Chisel writes in the directory of each digest +// kind: an entry named after its digest, or a temporary file left behind by a +// write that did not finish. +var entryNames = map[DigestKind]*regexp.Regexp{ + SHA256: regexp.MustCompile(`^([0-9a-f]{64}(\.tmp)?|tmp\.[0-9]+)$`), + SHA384: regexp.MustCompile(`^([0-9a-f]{96}(\.tmp)?|tmp\.[0-9]+)$`), + SHA512: regexp.MustCompile(`^([0-9a-f]{128}(\.tmp)?|tmp\.[0-9]+)$`), +} + var ErrMiss = fmt.Errorf("not cached") func (c *Cache) filePath(digestKind DigestKind, digest string) string { @@ -187,8 +198,12 @@ func (c *Cache) Read(digestKind DigestKind, digest string) ([]byte, error) { return data, nil } +// Expire removes the entries that were last used longer than timeout ago. +// Only files Chisel wrote are considered. A failure on one entry does not +// stop the others from being expired, and the first failure is returned. func (c *Cache) Expire(timeout time.Duration) error { expired := time.Now().Add(-timeout) + var firstErr error for _, digestKind := range digestKinds { digestKindDir := filepath.Join(c.Dir, string(digestKind)) entries, err := os.ReadDir(digestKindDir) @@ -196,26 +211,41 @@ func (c *Cache) Expire(timeout time.Duration) error { continue } if err != nil { - return fmt.Errorf("cannot list cache directory: %v", err) + if firstErr == nil { + firstErr = fmt.Errorf("cannot list cache directory: %v", err) + } + continue } for _, entry := range entries { - // Entries may vanish while listing, e.g. renamed from .tmp by - // a writer or removed by a concurrent expiry. - finfo, err := entry.Info() - if os.IsNotExist(err) { - continue - } - if err != nil { - return err - } - if finfo.ModTime().After(expired) { + if !entry.Type().IsRegular() || !entryNames[digestKind].MatchString(entry.Name()) { continue } - err = os.Remove(filepath.Join(digestKindDir, finfo.Name())) - if err != nil && !os.IsNotExist(err) { - return fmt.Errorf("cannot expire cache entry: %v", err) + err := expireEntry(filepath.Join(digestKindDir, entry.Name()), entry, expired) + if err != nil && firstErr == nil { + firstErr = err } } } + return firstErr +} + +// expireEntry removes the entry at path if it was last used before expired. +// Entries may vanish meanwhile, renamed from .tmp by a writer or removed by a +// concurrent expiry, and that is not an error. +func expireEntry(path string, entry fs.DirEntry, expired time.Time) error { + finfo, err := entry.Info() + if os.IsNotExist(err) { + return nil + } + if err != nil { + return fmt.Errorf("cannot expire cache entry: %v", err) + } + if finfo.ModTime().After(expired) { + return nil + } + err = os.Remove(path) + if err != nil && !os.IsNotExist(err) { + return fmt.Errorf("cannot expire cache entry: %v", err) + } return nil } diff --git a/internal/cache/cache_test.go b/internal/cache/cache_test.go index c57fb9747..c186fac51 100644 --- a/internal/cache/cache_test.go +++ b/internal/cache/cache_test.go @@ -1,8 +1,8 @@ package cache_test import ( - "fmt" "io" + "io/fs" "os" "path/filepath" "strings" @@ -305,32 +305,119 @@ func (s *S) TestCacheExpireNoDigestKindDirs(c *C) { c.Assert(err, IsNil) } -func (s *S) TestCacheExpireConcurrent(c *C) { +func (s *S) TestCacheExpireOnlyOwnEntries(c *C) { cc := cache.Cache{Dir: c.MkDir()} dir := filepath.Join(cc.Dir, "sha256") err := os.MkdirAll(dir, 0755) c.Assert(err, IsNil) + // Names Chisel writes: entries and leftovers of unfinished writes. + own := []string{ + data1Digest, + data2Digest + ".tmp", + "tmp.123456", + } + // Anything else, including digests of another kind or length, upper + // case digests, and a directory named after a digest. + other := []string{ + "README", + data3Digest + ".partial", + strings.ToUpper(data2Digest), + data3Digest[:63], + data3Digest + data3Digest, + "tmp.abc", + } expiredTime := time.Now().Add(-2 * time.Hour) - for i := 0; i < 2000; i++ { - name := filepath.Join(dir, fmt.Sprintf("%064x", i)) - err := os.WriteFile(name, nil, 0644) + for _, name := range append(own, other...) { + path := filepath.Join(dir, name) + err := os.WriteFile(path, nil, 0644) c.Assert(err, IsNil) - err = os.Chtimes(name, expiredTime, expiredTime) + err = os.Chtimes(path, expiredTime, expiredTime) c.Assert(err, IsNil) } + digestDir := filepath.Join(dir, data3Digest) + err = os.Mkdir(digestDir, 0755) + c.Assert(err, IsNil) + err = os.WriteFile(filepath.Join(digestDir, "file"), nil, 0644) + c.Assert(err, IsNil) + err = os.Chtimes(digestDir, expiredTime, expiredTime) + c.Assert(err, IsNil) + + err = cc.Expire(time.Hour) + c.Assert(err, IsNil) + + for _, name := range own { + _, err := os.Stat(filepath.Join(dir, name)) + c.Assert(os.IsNotExist(err), Equals, true, Commentf("%s", name)) + } + for _, name := range append(other, data3Digest) { + _, err := os.Stat(filepath.Join(dir, name)) + c.Assert(err, IsNil, Commentf("%s", name)) + } +} - // Expiries running at the same time remove entries the others have - // listed too, and must not fail because of it. - errs := make(chan error, 4) - for i := 0; i < 4; i++ { - go func() { errs <- cc.Expire(time.Hour) }() +func (s *S) TestCacheExpireKeepsGoing(c *C) { + if os.Getuid() == 0 { + c.Skip("root can remove files from a read-only directory") } - for i := 0; i < 4; i++ { - c.Assert(<-errs, IsNil) + cc := cache.Cache{Dir: c.MkDir()} + err := cc.Write(cache.SHA256, data1Digest, []byte("data1")) + c.Assert(err, IsNil) + w := cc.Create(cache.SHA512, "") + _, err = w.Write([]byte("sha512data1")) + c.Assert(err, IsNil) + err = w.Close() + c.Assert(err, IsNil) + + sha256Entry := filepath.Join(cc.Dir, "sha256", data1Digest) + sha512Entry := filepath.Join(cc.Dir, "sha512", w.Digest()) + expiredTime := time.Now().Add(-2 * time.Hour) + for _, path := range []string{sha256Entry, sha512Entry} { + err := os.Chtimes(path, expiredTime, expiredTime) + c.Assert(err, IsNil) } + // The sha256 entry cannot be removed, which must not keep the sha512 + // entry from being expired. + sha256Dir := filepath.Join(cc.Dir, "sha256") + err = os.Chmod(sha256Dir, 0555) + c.Assert(err, IsNil) + defer func() { + err := os.Chmod(sha256Dir, 0755) + c.Assert(err, IsNil) + }() + + err = cc.Expire(time.Hour) + c.Assert(err, ErrorMatches, "cannot expire cache entry: remove .*/sha256/"+data1Digest+": permission denied") + + _, err = os.Stat(sha256Entry) + c.Assert(err, IsNil) + _, err = os.Stat(sha512Entry) + c.Assert(os.IsNotExist(err), Equals, true) +} + +func (s *S) TestCacheExpireVanishedEntry(c *C) { + cc := cache.Cache{Dir: c.MkDir()} + err := cc.Write(cache.SHA256, data1Digest, []byte("data1")) + c.Assert(err, IsNil) + dir := filepath.Join(cc.Dir, "sha256") + path := filepath.Join(dir, data1Digest) + expiredTime := time.Now().Add(-2 * time.Hour) + err = os.Chtimes(path, expiredTime, expiredTime) + c.Assert(err, IsNil) + + // Listed and then removed by someone else before it was looked at. entries, err := os.ReadDir(dir) c.Assert(err, IsNil) - c.Assert(entries, HasLen, 0) + c.Assert(entries, HasLen, 1) + finfo, err := os.Stat(path) + c.Assert(err, IsNil) + err = os.Remove(path) + c.Assert(err, IsNil) + err = cache.ExpireEntry(path, entries[0], time.Now().Add(-time.Hour)) + c.Assert(err, IsNil) + + // Looked at and then removed by someone else before it was removed. + err = cache.ExpireEntry(path, fs.FileInfoToDirEntry(finfo), time.Now().Add(-time.Hour)) + c.Assert(err, IsNil) } diff --git a/internal/cache/export_test.go b/internal/cache/export_test.go new file mode 100644 index 000000000..3864292ac --- /dev/null +++ b/internal/cache/export_test.go @@ -0,0 +1,3 @@ +package cache + +var ExpireEntry = expireEntry From 4888187e0aa0d7e32867e327e56da19a6e215e75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmed=20Semih=20=C3=96zmekik?= Date: Wed, 4 Nov 2026 21:46:33 +0300 Subject: [PATCH 4/5] fix: tolerate a cache entry expired right after it is opened Open refreshes the timestamp of an entry after opening it. If another process expires the entry in between, Chtimes fails and so did the fetch, although the open file is still readable. Ignore that case, and close the file on the other failures. --- internal/cache/cache.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/internal/cache/cache.go b/internal/cache/cache.go index 50f9956b0..1afeab2dd 100644 --- a/internal/cache/cache.go +++ b/internal/cache/cache.go @@ -177,9 +177,11 @@ func (c *Cache) Open(digestKind DigestKind, digest string) (io.ReadSeekCloser, e } else if err != nil { return nil, fmt.Errorf("cannot open cache file: %v", err) } - // Use mtime as last reuse time. + // Use mtime as last reuse time. If the entry was expired since it was + // opened, the open file is still readable and there is nothing to update. now := time.Now() - if err := os.Chtimes(filePath, now, now); err != nil { + if err := os.Chtimes(filePath, now, now); err != nil && !os.IsNotExist(err) { + file.Close() return nil, fmt.Errorf("cannot update cached file timestamp: %v", err) } return file, nil From 3676017da5c75412b468cce6cf17ab2d87ff8fb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmed=20Semih=20=C3=96zmekik?= Date: Wed, 4 Nov 2026 21:46:33 +0300 Subject: [PATCH 5/5] feat: set the cache expiry with CHISEL_CACHE_EXPIRY CHISEL_CACHE_EXPIRY sets how many days a cache entry can go unused, 7 by default, and 0 disables expiry. Any other value logs a warning and leaves the cache alone, since deleting is the one thing that can't be undone. debug check-release-archives fetches every package of a release, so it now expires the cache too. find and info only refresh the release directory, which is replaced in place and does not grow. The command tests point XDG_CACHE_HOME at a temporary directory, so they never expire the cache of whoever runs them. --- cmd/chisel/cmd_cut.go | 14 ++- .../cmd_debug_check_release_archives.go | 4 +- .../cmd_debug_check_release_archives_test.go | 14 +++ cmd/chisel/export_test.go | 4 + cmd/chisel/helpers.go | 43 ++++++++++ cmd/chisel/helpers_test.go | 86 +++++++++++++++++++ cmd/chisel/main_test.go | 15 ++++ tests/cache-expiry/task.yaml | 23 +++-- 8 files changed, 186 insertions(+), 17 deletions(-) create mode 100644 cmd/chisel/helpers_test.go diff --git a/cmd/chisel/cmd_cut.go b/cmd/chisel/cmd_cut.go index 37c06c5be..edc00e6fe 100644 --- a/cmd/chisel/cmd_cut.go +++ b/cmd/chisel/cmd_cut.go @@ -20,6 +20,10 @@ to create a new filesystem tree in the root location. By default it fetches the slices for the same Ubuntu version as the current host, unless the --release flag is used. + +Packages and archive indexes are cached, and cache entries that have not +been used for 7 days are removed after the cut. Set CHISEL_CACHE_EXPIRY +to a number of days to change that, or to 0 to keep all entries. ` var cutDescs = map[string]string{ @@ -29,9 +33,6 @@ var cutDescs = map[string]string{ "ignore": "Conditions to ignore (e.g. unmaintained, unstable)", } -// cacheExpiry is how long a cache entry can go unused before a cut removes it. -const cacheExpiry = 7 * 24 * time.Hour - type cmdCut struct { Release string `long:"release" value-name:""` RootDir string `long:"root" value-name:"" required:"yes"` @@ -134,11 +135,6 @@ func (cmd *cmdCut) Execute(args []string) error { return err } - // Reading an entry refreshes its timestamp, so this only drops what no - // cut has used for a while. Failing to clean up is not a failed cut. - cc := &cache.Cache{Dir: cacheDir} - if err := cc.Expire(cacheExpiry); err != nil { - logf("Warning: cannot expire cache entries: %v", err) - } + expireCache(cacheDir) return nil } diff --git a/cmd/chisel/cmd_debug_check_release_archives.go b/cmd/chisel/cmd_debug_check_release_archives.go index c9c6270e4..da3978363 100644 --- a/cmd/chisel/cmd_debug_check_release_archives.go +++ b/cmd/chisel/cmd_debug_check_release_archives.go @@ -62,6 +62,7 @@ func (cmd *cmdDebugCheckReleaseArchives) Execute(args []string) error { return err } + cacheDir := cache.DefaultDir("chisel") archives := make(map[string]archive.Archive) for archiveName, archiveInfo := range release.Archives { openArchive, err := archiveOpen(&archive.Options{ @@ -71,7 +72,7 @@ func (cmd *cmdDebugCheckReleaseArchives) Execute(args []string) error { Suites: archiveInfo.Suites, Components: archiveInfo.Components, Pro: archiveInfo.Pro, - CacheDir: cache.DefaultDir("chisel"), + CacheDir: cacheDir, PubKeys: archiveInfo.PubKeys, Maintained: archiveInfo.Maintained, OldRelease: archiveInfo.OldRelease, @@ -89,6 +90,7 @@ func (cmd *cmdDebugCheckReleaseArchives) Execute(args []string) error { if err != nil { return err } + expireCache(cacheDir) var issues []any type pathConflict struct { diff --git a/cmd/chisel/cmd_debug_check_release_archives_test.go b/cmd/chisel/cmd_debug_check_release_archives_test.go index 0ca5afb0b..2253d080a 100644 --- a/cmd/chisel/cmd_debug_check_release_archives_test.go +++ b/cmd/chisel/cmd_debug_check_release_archives_test.go @@ -5,6 +5,7 @@ import ( "path/filepath" "slices" "strings" + "time" . "gopkg.in/check.v1" "gopkg.in/yaml.v3" @@ -520,6 +521,16 @@ func (s *ChiselSuite) TestRun(c *C) { }) defer restore() + // A cache entry no command has used for a while. + stale := filepath.Join(os.Getenv("XDG_CACHE_HOME"), "chisel", "sha256", strings.Repeat("0", 64)) + err = os.MkdirAll(filepath.Dir(stale), 0755) + c.Assert(err, IsNil) + err = os.WriteFile(stale, nil, 0644) + c.Assert(err, IsNil) + lastUsed := time.Now().Add(-8 * 24 * time.Hour) + err = os.Chtimes(stale, lastUsed, lastUsed) + c.Assert(err, IsNil) + cliArgs := []string{"debug", "check-release-archives", "--release", releaseDir} if test.arch != "" { cliArgs = slices.Concat(cliArgs, []string{"--arch", test.arch}) @@ -531,6 +542,9 @@ func (s *ChiselSuite) TestRun(c *C) { } else { c.Assert(err, IsNil) } + // Once the packages are fetched, the cache is expired. + _, err = os.Stat(stale) + c.Assert(os.IsNotExist(err), Equals, true) if test.stdout != "" { test.stdout = string(testutil.Reindent(test.stdout)) test.stdout = strings.TrimSpace(test.stdout) + "\n" diff --git a/cmd/chisel/export_test.go b/cmd/chisel/export_test.go index 648225274..ae5b45f43 100644 --- a/cmd/chisel/export_test.go +++ b/cmd/chisel/export_test.go @@ -22,6 +22,10 @@ func FakeIsStdinTTY(t bool) (restore func()) { var FindSlices = findSlices +var CacheExpiry = cacheExpiry + +var ExpireCache = expireCache + func FakeArchiveOpen(f func(_ *archive.Options) (archive.Archive, error)) (restore func()) { oldArchiveOpen := archiveOpen archiveOpen = f diff --git a/cmd/chisel/helpers.go b/cmd/chisel/helpers.go index 7506888e6..86753e1e5 100644 --- a/cmd/chisel/helpers.go +++ b/cmd/chisel/helpers.go @@ -4,8 +4,11 @@ import ( "fmt" "os" "regexp" + "strconv" "strings" + "time" + "github.com/canonical/chisel/internal/cache" "github.com/canonical/chisel/internal/setup" ) @@ -69,3 +72,43 @@ func obtainRelease(releaseStr string) (release *setup.Release, err error) { } return release, nil } + +// defaultCacheExpiry is how long a cache entry can go unused before it is +// removed, unless CHISEL_CACHE_EXPIRY says otherwise. +const defaultCacheExpiry = 7 * 24 * time.Hour + +// cacheExpiry returns how long a cache entry can go unused before it is +// removed. CHISEL_CACHE_EXPIRY sets it as a number of days, and 0 disables +// expiry. +func cacheExpiry() (time.Duration, error) { + value := os.Getenv("CHISEL_CACHE_EXPIRY") + if value == "" { + return defaultCacheExpiry, nil + } + // Limit it to 16 bits, about 179 years, so the duration cannot overflow. + days, err := strconv.ParseUint(value, 10, 16) + if err != nil { + return 0, fmt.Errorf("invalid CHISEL_CACHE_EXPIRY %q, expected a number of days", value) + } + return time.Duration(days) * 24 * time.Hour, nil +} + +// expireCache removes the entries of the cache in dir that have not been +// used for the time given by cacheExpiry. It is meant to run once a command +// is done with the cache. +func expireCache(dir string) { + expiry, err := cacheExpiry() + if err != nil { + logf("Warning: %v; the cache is not expired", err) + return + } + if expiry == 0 { + return + } + // Reading an entry refreshes its timestamp, so this only drops what no + // command has used for a while. + cc := &cache.Cache{Dir: dir} + if err := cc.Expire(expiry); err != nil { + logf("Warning: cannot expire cache entries: %v", err) + } +} diff --git a/cmd/chisel/helpers_test.go b/cmd/chisel/helpers_test.go new file mode 100644 index 000000000..1d699078b --- /dev/null +++ b/cmd/chisel/helpers_test.go @@ -0,0 +1,86 @@ +package main_test + +import ( + "bytes" + "log" + "os" + "path/filepath" + "time" + + . "gopkg.in/check.v1" + + chisel "github.com/canonical/chisel/cmd/chisel" +) + +var cacheExpiryTests = []struct { + value string + expiry time.Duration + err string +}{ + {value: "", expiry: 7 * 24 * time.Hour}, + {value: "0", expiry: 0}, + {value: "1", expiry: 24 * time.Hour}, + {value: "30", expiry: 30 * 24 * time.Hour}, + {value: "65535", expiry: 65535 * 24 * time.Hour}, + {value: "65536", err: `invalid CHISEL_CACHE_EXPIRY "65536", expected a number of days`}, + {value: "-1", err: `invalid CHISEL_CACHE_EXPIRY "-1", expected a number of days`}, + {value: "7d", err: `invalid CHISEL_CACHE_EXPIRY "7d", expected a number of days`}, + {value: "1.5", err: `invalid CHISEL_CACHE_EXPIRY "1.5", expected a number of days`}, + {value: " 7", err: `invalid CHISEL_CACHE_EXPIRY " 7", expected a number of days`}, +} + +func (s *ChiselSuite) TestCacheExpiry(c *C) { + for _, test := range cacheExpiryTests { + c.Logf("CHISEL_CACHE_EXPIRY=%q", test.value) + restore := fakeEnv("CHISEL_CACHE_EXPIRY", test.value) + expiry, err := chisel.CacheExpiry() + restore() + if test.err != "" { + c.Assert(err, ErrorMatches, test.err) + continue + } + c.Assert(err, IsNil) + c.Assert(expiry, Equals, test.expiry) + } +} + +var expireCacheTests = []struct { + value string + expired bool + log string +}{ + {value: "", expired: true}, + {value: "7", expired: true}, + {value: "30", expired: false}, + {value: "0", expired: false}, + {value: "never", expired: false, log: "Warning: invalid CHISEL_CACHE_EXPIRY \"never\", expected a number of days; the cache is not expired\n"}, +} + +func (s *ChiselSuite) TestExpireCache(c *C) { + var logs bytes.Buffer + chisel.SetLogger(log.New(&logs, "", 0)) + defer chisel.SetLogger(nil) + + for _, test := range expireCacheTests { + c.Logf("CHISEL_CACHE_EXPIRY=%q", test.value) + logs.Reset() + + dir := c.MkDir() + entry := filepath.Join(dir, "sha256", "5b41362bc82b7f3d56edc5a306db22105707d01ff4819e26faef9724a2d406c9") + err := os.MkdirAll(filepath.Dir(entry), 0755) + c.Assert(err, IsNil) + err = os.WriteFile(entry, []byte("data1"), 0644) + c.Assert(err, IsNil) + lastUsed := time.Now().Add(-8 * 24 * time.Hour) + err = os.Chtimes(entry, lastUsed, lastUsed) + c.Assert(err, IsNil) + + restore := fakeEnv("CHISEL_CACHE_EXPIRY", test.value) + chisel.ExpireCache(dir) + restore() + + _, err = os.Stat(entry) + c.Assert(os.IsNotExist(err), Equals, test.expired) + c.Assert(logs.String(), Equals, test.log) + } +} diff --git a/cmd/chisel/main_test.go b/cmd/chisel/main_test.go index a7023c919..b6214f2e6 100644 --- a/cmd/chisel/main_test.go +++ b/cmd/chisel/main_test.go @@ -44,6 +44,9 @@ func (s *BaseChiselSuite) SetUpTest(c *C) { s.AddCleanup(chisel.FakeIsStdoutTTY(false)) s.AddCleanup(chisel.FakeIsStdinTTY(false)) + + // Commands expire the cache, so keep them away from the real one. + s.AddCleanup(fakeEnv("XDG_CACHE_HOME", c.MkDir())) } func (s *BaseChiselSuite) TearDownTest(c *C) { @@ -75,6 +78,18 @@ func fakeVersion(v string) (restore func()) { return func() { cmd.Version = old } } +func fakeEnv(name, value string) (restore func()) { + old, ok := os.LookupEnv(name) + os.Setenv(name, value) + return func() { + if ok { + os.Setenv(name, old) + } else { + os.Unsetenv(name) + } + } +} + type ChiselSuite struct { BaseChiselSuite } diff --git a/tests/cache-expiry/task.yaml b/tests/cache-expiry/task.yaml index efafb72fe..e942ac54b 100644 --- a/tests/cache-expiry/task.yaml +++ b/tests/cache-expiry/task.yaml @@ -1,4 +1,4 @@ -summary: Cache entries that no cut has used for a week are expired +summary: Cut expires cache entries unused for a week, unless told otherwise execute: | cache_dir=${XDG_CACHE_HOME:-$HOME/.cache}/chisel @@ -9,12 +9,13 @@ execute: | EXTRA_OPTIONS="--ignore=unmaintained " fi - mkdir -p ${rootfs_folder}_1 ${rootfs_folder}_2 + mkdir -p ${rootfs_folder}_1 ${rootfs_folder}_2 ${rootfs_folder}_3 chisel cut --release ${OS}-${RELEASE} --root ${rootfs_folder}_1 \ $EXTRA_OPTIONS base-passwd_data # Find the cached base-passwd deb (under the strongest digest the archive - # offers) and backdate it, and add a stale entry that no cut uses. + # offers) and backdate it. Add a stale entry that no cut uses, and a file + # Chisel did not write. used="" for f in ${cache_dir}/sha*/*; do if [ "$(dpkg-deb -f "$f" Package 2>/dev/null)" = "base-passwd" ]; then @@ -24,13 +25,21 @@ execute: | test -n "$used" stale=${cache_dir}/sha256/$(echo stale | sha256sum | cut -d' ' -f1) echo stale > $stale - touch -d "8 days ago" $used $stale + foreign=${cache_dir}/sha256/notes + echo notes > $foreign + touch -d "8 days ago" $used $stale $foreign - chisel cut --release ${OS}-${RELEASE} --root ${rootfs_folder}_2 \ + # Nothing is expired when expiry is disabled. + CHISEL_CACHE_EXPIRY=0 chisel cut --release ${OS}-${RELEASE} \ + --root ${rootfs_folder}_2 $EXTRA_OPTIONS base-passwd_data + test -e $stale + + chisel cut --release ${OS}-${RELEASE} --root ${rootfs_folder}_3 \ $EXTRA_OPTIONS base-passwd_data - # The stale entry is gone. The deb was used again, so it is kept, with a - # fresh timestamp. + # The stale entry is gone, and the file Chisel did not write is kept. The + # deb was used again, so it is kept, with a fresh timestamp. test ! -e $stale + test -e $foreign test -e $used test $(( $(date +%s) - $(stat -c %Y $used) )) -lt 3600