//go:build linux package chunk_cache import ( "os" "path/filepath" "syscall" "testing" "golang.org/x/sys/unix" ) func TestNewCacheFilesReserveOnlyWhatIsAboveMinFreeSpace(t *testing.T) { dir := t.TempDir() probe, err := os.Create(filepath.Join(dir, "probe")) if err != nil { t.Fatal(err) } err = unix.Fallocate(int(probe.Fd()), unix.FALLOC_FL_KEEP_SIZE, 0, 1<<20) probe.Close() os.Remove(probe.Name()) if err != nil { t.Skipf("fallocate not supported in %s: %v", dir, err) } allocated := func(v *ChunkCacheVolume) int64 { var st syscall.Stat_t if err := syscall.Stat(v.fileName+".dat", &st); err != nil { t.Fatal(err) } return st.Blocks * 512 } // 1 MiB above a 10 MiB floor: each new file reserves at most that much, // though it may still fill up to its size limit later, while the disk // stays above the floor. useFakeDisk(t, 100<<20, 11<<20) layer := NewOnDiskCacheLayer(dir, "c2_2", 8<<20, 2, newDiskSpaceGuard(dir, minFreeSpace(t, "10MiB"))) defer layer.shutdown() if len(layer.diskCaches) != 2 { t.Fatalf("layer has %d files, want 2", len(layer.diskCaches)) } for _, v := range layer.diskCaches { if v.sizeLimit != 4<<20 { t.Errorf("%s holds up to %d bytes, want 4 MiB", v.fileName, v.sizeLimit) } if got := allocated(v); got < 1<<20 || got > 1<<20+64<<10 { t.Errorf("%s reserved %d bytes, want the 1 MiB above the floor", v.fileName, got) } if v.reserved != allocated(v) { t.Errorf("%s counts %d bytes as held, the disk gave it %d", v.fileName, v.reserved, allocated(v)) } } // Without a floor each file reserves its whole size. unguarded := NewOnDiskCacheLayer(t.TempDir(), "c2_2", 8<<20, 2, nil) defer unguarded.shutdown() for _, v := range unguarded.diskCaches { if got := allocated(v); got < 4<<20 { t.Errorf("%s reserved %d bytes without a floor, want 4 MiB", v.fileName, got) } } } func TestOwnFilesCountTheBlocksTheyHold(t *testing.T) { dir := t.TempDir() f, err := os.Create(filepath.Join(dir, "c2_2_0.dat")) if err != nil { t.Fatal(err) } err = unix.Fallocate(int(f.Fd()), unix.FALLOC_FL_KEEP_SIZE, 0, 1<<20) f.Close() if err != nil { t.Skipf("fallocate not supported in %s: %v", dir, err) } // An empty cache file that preallocated 1 MiB, as one left behind by an // unclean exit soon after it opened, holds that 1 MiB of the disk. if got := cacheFilesSize(dir); got < 1<<20 { t.Errorf("cache files hold %d bytes, want the 1 MiB preallocated", got) } }