diff --git a/cmd/chisel/cmd_cut.go b/cmd/chisel/cmd_cut.go index 35c81a79a..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{ @@ -78,6 +82,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 +92,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 +131,10 @@ func (cmd *cmdCut) Execute(args []string) error { Archives: archives, TargetDir: cmd.RootDir, }) - return err + if err != nil { + return 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/internal/cache/cache.go b/internal/cache/cache.go index 3b5621ecc..1afeab2dd 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 { @@ -166,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 @@ -187,8 +200,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,21 +213,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 { - finfo, err := entry.Info() - 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 { - 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 7267a2e85..c186fac51 100644 --- a/internal/cache/cache_test.go +++ b/internal/cache/cache_test.go @@ -2,6 +2,7 @@ package cache_test import ( "io" + "io/fs" "os" "path/filepath" "strings" @@ -303,3 +304,120 @@ func (s *S) TestCacheExpireNoDigestKindDirs(c *C) { err := cc.Expire(time.Hour) c.Assert(err, IsNil) } + +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 _, name := range append(own, other...) { + path := filepath.Join(dir, name) + err := os.WriteFile(path, nil, 0644) + c.Assert(err, IsNil) + 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)) + } +} + +func (s *S) TestCacheExpireKeepsGoing(c *C) { + if os.Getuid() == 0 { + c.Skip("root can remove files from a read-only directory") + } + 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, 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 diff --git a/tests/cache-expiry/task.yaml b/tests/cache-expiry/task.yaml new file mode 100644 index 000000000..e942ac54b --- /dev/null +++ b/tests/cache-expiry/task.yaml @@ -0,0 +1,45 @@ +summary: Cut expires cache entries unused for a week, unless told otherwise + +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 ${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. 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 + used=$f + fi + done + test -n "$used" + stale=${cache_dir}/sha256/$(echo stale | sha256sum | cut -d' ' -f1) + echo stale > $stale + foreign=${cache_dir}/sha256/notes + echo notes > $foreign + touch -d "8 days ago" $used $stale $foreign + + # 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, 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