Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions cmd/chisel/cmd_cut.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand Down Expand Up @@ -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{
Expand All @@ -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,
Expand Down Expand Up @@ -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
}
4 changes: 3 additions & 1 deletion cmd/chisel/cmd_debug_check_release_archives.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand All @@ -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,
Expand All @@ -89,6 +90,7 @@ func (cmd *cmdDebugCheckReleaseArchives) Execute(args []string) error {
if err != nil {
return err
}
expireCache(cacheDir)

var issues []any
type pathConflict struct {
Expand Down
14 changes: 14 additions & 0 deletions cmd/chisel/cmd_debug_check_release_archives_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"path/filepath"
"slices"
"strings"
"time"

. "gopkg.in/check.v1"
"gopkg.in/yaml.v3"
Expand Down Expand Up @@ -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})
Expand All @@ -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"
Expand Down
4 changes: 4 additions & 0 deletions cmd/chisel/export_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
43 changes: 43 additions & 0 deletions cmd/chisel/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@ import (
"fmt"
"os"
"regexp"
"strconv"
"strings"
"time"

"github.com/canonical/chisel/internal/cache"
"github.com/canonical/chisel/internal/setup"
)

Expand Down Expand Up @@ -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)
}
}
86 changes: 86 additions & 0 deletions cmd/chisel/helpers_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
15 changes: 15 additions & 0 deletions cmd/chisel/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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
}
Expand Down
59 changes: 48 additions & 11 deletions internal/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ import (
"fmt"
"hash"
"io"
"io/fs"
"os"
"path/filepath"
"regexp"
"time"

"golang.org/x/crypto/sha3"
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand All @@ -187,30 +200,54 @@ 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)
if os.IsNotExist(err) {
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
}
Loading