package chunk_cache import ( "bytes" "errors" "fmt" "os" "path/filepath" "sync" "testing" "time" "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb" "github.com/seaweedfs/seaweedfs/weed/util" ) // fakeDisk stands in for the disk holding a cache directory. type fakeDisk struct { mu sync.Mutex all uint64 free uint64 err error } func (d *fakeDisk) status(dir string) (*volume_server_pb.DiskStatus, error) { d.mu.Lock() defer d.mu.Unlock() if d.err != nil { return nil, d.err } return &volume_server_pb.DiskStatus{ Dir: dir, All: d.all, Free: d.free, Used: d.all - d.free, PercentFree: float32(float64(d.free) / float64(d.all) * 100), PercentUsed: float32(float64(d.all-d.free) / float64(d.all) * 100), }, nil } func (d *fakeDisk) setFree(free uint64) { d.mu.Lock() defer d.mu.Unlock() d.free = free } func useFakeDisk(t *testing.T, all, free uint64) *fakeDisk { t.Helper() disk := &fakeDisk{all: all, free: free} saved := diskStatusOf diskStatusOf = disk.status t.Cleanup(func() { diskStatusOf = saved }) return disk } func minFreeSpace(t *testing.T, s string) *util.MinFreeSpace { t.Helper() m, err := util.ParseMinFreeSpace(s) if err != nil { t.Fatalf("ParseMinFreeSpace(%q): %v", s, err) } return m } // diskCacheSize is how many bytes of chunks the disk layers take in all. func diskCacheSize(c *TieredChunkCache) (size int64) { for _, layer := range c.diskCaches { for _, v := range layer.diskCaches { size += v.sizeLimit } } return size } func TestDiskCacheShrinksToFitAboveMinFreeSpace(t *testing.T) { // 20 MiB free on a 100 MiB disk that must keep 10% free: 10 MiB above // the floor, of which the index files get a sixteenth, and the cache the // whole 1 MiB units of the rest. useFakeDisk(t, 100<<20, 20<<20) cache := NewTieredChunkCache(2, t.TempDir(), 64, 1<<20, minFreeSpace(t, "10")) defer cache.Shutdown() if got, want := diskCacheSize(cache), int64(9<<20); got != want { t.Errorf("disk cache takes %d bytes, want %d of the 10 MiB above the floor", got, want) } if got, want := cache.GetMaxFilePartSizeInCache(), uint64(9<<20)/4; got != want { t.Errorf("max file part in cache %d, want a quarter of the shrunk cache %d", got, want) } unguarded := NewTieredChunkCache(2, t.TempDir(), 64, 1<<20, nil) defer unguarded.Shutdown() if got, want := diskCacheSize(unguarded), int64(64<<20); got != want { t.Errorf("without a floor the disk cache takes %d bytes, want the configured %d", got, want) } } func TestDiskCacheCountsItsOwnFilesAsRoom(t *testing.T) { dir := t.TempDir() // Files a cache left behind on an unclean exit are reused, so their space // is the cache's to keep; nothing else in dir is. for name, size := range map[string]int64{ "c2_2_0.dat": 4 << 20, "c2_2_0.idx": 1 << 20, "c0_2_1.dat": 1 << 20, "unrelated.dat": 8 << 20, "c2_2_0.tmp": 8 << 20, } { f, err := os.Create(filepath.Join(dir, name)) if err != nil { t.Fatal(err) } if err := f.Truncate(size); err != nil { t.Fatal(err) } f.Close() } if err := os.MkdirAll(filepath.Join(dir, "c1_3_0.ldb"), 0755); err != nil { t.Fatal(err) } // 2 MiB above a 10 MiB floor. useFakeDisk(t, 100<<20, 12<<20) guard := newDiskSpaceGuard(dir, minFreeSpace(t, "10MiB")) if got, want := guard.capacity(64<<20), int64(8<<20-8<<20/16); got != want { t.Errorf("capacity %d, want %d: 2 MiB free above the floor plus 6 MiB of the cache's own files, less a sixteenth for the index files", got, want) } if got, want := guard.capacity(4<<20), int64(4<<20); got != want { t.Errorf("capacity %d, want the configured %d when it fits", got, want) } } func TestDiskCacheWithNoRoomKeepsNothingOnDisk(t *testing.T) { // 5 MiB free, under a floor of 10% of 100 MiB. useFakeDisk(t, 100<<20, 5<<20) dir := t.TempDir() cache := NewTieredChunkCache(2, dir, 64, 1024, minFreeSpace(t, "10")) defer cache.Shutdown() if entries, _ := os.ReadDir(dir); len(entries) != 0 { t.Fatalf("cache created %d files on a disk under its floor", len(entries)) } if got := cache.GetMaxFilePartSizeInCache(); got != 0 { t.Errorf("max file part in cache %d, want 0 for a cache with no disk room", got) } chunk := bytes.Repeat([]byte{7}, 4096) cache.SetChunk("1,1aabbccdd", chunk) if cache.IsInCache("1,1aabbccdd", true) { t.Errorf("a chunk too big for memory was cached with no disk room") } } // holdNoBlocks makes every cache file look created where nothing could be // preallocated, so each write past what it has written takes new disk space. func holdNoBlocks(c *TieredChunkCache) { for _, layer := range c.diskCaches { for _, v := range layer.diskCaches { v.reserved = v.fileSize } } } // holdAllBlocks makes every cache file look preallocated in full. func holdAllBlocks(c *TieredChunkCache) { for _, layer := range c.diskCaches { for _, v := range layer.diskCaches { v.reserved = v.sizeLimit } } } func cachedChunk(c *TieredChunkCache, fileId string, data []byte) bool { buf := make([]byte, len(data)) n, _ := c.ReadChunkAt(buf, fileId, 0) return n == len(data) && bytes.Equal(buf, data) } // testChunk is a chunk too big for the memory tier of a cache with 1 KiB units. func testChunk(i int) (string, []byte) { return fmt.Sprintf("1,%xaabbccdd", i), bytes.Repeat([]byte{byte(i)}, 4096) } func TestDiskCacheTakesNoNewSpaceUnderMinFreeSpace(t *testing.T) { disk := useFakeDisk(t, 100<<20, 50<<20) cache := NewTieredChunkCache(2, t.TempDir(), 1024, 1024, minFreeSpace(t, "10")) defer cache.Shutdown() holdNoBlocks(cache) fid, data := testChunk(1) cache.SetChunk(fid, data) if !cachedChunk(cache, fid, data) { t.Fatalf("chunk 1 not cached with the disk above its floor") } // The disk drops under its floor: writes that need new space are // turned away from the next one on. disk.setFree(5 << 20) fid, data = testChunk(2) cache.SetChunk(fid, data) if cachedChunk(cache, fid, data) { t.Errorf("chunk 2 took new space on a disk under its floor") } disk.setFree(50 << 20) fid, data = testChunk(3) cache.SetChunk(fid, data) if !cachedChunk(cache, fid, data) { t.Errorf("chunk 3 not cached once the disk is back above its floor") } if fid, data = testChunk(1); !cachedChunk(cache, fid, data) { t.Errorf("chunk 1, cached before the disk ran low, is gone") } } func TestDiskCacheSeesOtherWritersAtOnce(t *testing.T) { disk := useFakeDisk(t, 100<<20, 50<<20) cache := NewTieredChunkCache(2, t.TempDir(), 1024, 1024, minFreeSpace(t, "10MiB")) defer cache.Shutdown() holdNoBlocks(cache) // Room above the floor for three chunks. record := uint64(cacheHeaderSize + 4096) disk.setFree(10<<20 + 3*record + 100) fid, data := testChunk(1) cache.SetChunk(fid, data) if !cachedChunk(cache, fid, data) { t.Fatalf("chunk 1 not cached with room above the floor") } // Another mount on the same disk takes the rest; the very next write // that needs new space sees it. disk.setFree(10 << 20) fid, data = testChunk(2) cache.SetChunk(fid, data) if cachedChunk(cache, fid, data) { t.Errorf("chunk 2 took the space another writer had taken") } } func TestDiskCacheFillsTheSpaceItHoldsUnderMinFreeSpace(t *testing.T) { disk := useFakeDisk(t, 100<<20, 50<<20) cache := NewTieredChunkCache(2, t.TempDir(), 1024, 1024, minFreeSpace(t, "10")) defer cache.Shutdown() holdAllBlocks(cache) // The disk sits just under its floor, as it does when the cache // preallocated everything above it and something else wrote a little. disk.setFree(10<<20 - 4096) // Chunks keep landing in the blocks the front file already holds. front := cache.diskCaches[1].diskCaches[0] fits := int(front.sizeLimit / int64(cacheHeaderSize+4096)) for i := 1; i <= fits; i++ { fid, data := testChunk(i) cache.SetChunk(fid, data) if !cachedChunk(cache, fid, data) { t.Fatalf("chunk %d of %d that fit the held space not cached", i, fits) } } // The next one rotates, emptying the oldest file, and the write into // it needs new space, which the disk under its floor does not give. fid, data := testChunk(fits + 1) cache.SetChunk(fid, data) if cachedChunk(cache, fid, data) { t.Errorf("chunk after the rotation took new space on a disk under its floor") } // The emptied file gave its blocks back; here they lift the disk over // the floor, and the next chunk goes in. disk.setFree(50 << 20) fid, data = testChunk(fits + 2) cache.SetChunk(fid, data) if !cachedChunk(cache, fid, data) { t.Errorf("chunk not cached once the rotation gave space back") } } func TestDiskCacheIgnoresAnUnreadableDisk(t *testing.T) { disk := useFakeDisk(t, 100<<20, 50<<20) disk.err = errors.New("statfs failed") cache := NewTieredChunkCache(2, t.TempDir(), 1024, 1024, minFreeSpace(t, "10")) defer cache.Shutdown() if got, want := diskCacheSize(cache), int64(1024*1024); got != want { t.Errorf("disk cache takes %d bytes, want the configured %d when the disk cannot be read", got, want) } fid, data := "1,1aabbccdd", bytes.Repeat([]byte{1}, 4096) cache.SetChunk(fid, data) if !cache.IsInCache(fid, true) { t.Errorf("chunk not cached when the disk cannot be read") } } // TestDiskCacheFloorUnderConcurrentUse runs writers and readers against a // disk that keeps crossing its floor; run it with -race. func TestDiskCacheFloorUnderConcurrentUse(t *testing.T) { disk := useFakeDisk(t, 100<<20, 50<<20) cache := NewTieredChunkCache(16, t.TempDir(), 2048, 1024, minFreeSpace(t, "10")) defer cache.Shutdown() holdNoBlocks(cache) stop := make(chan struct{}) var flipper sync.WaitGroup flipper.Add(1) go func() { defer flipper.Done() for i := 0; ; i++ { select { case <-stop: return default: } if i%2 == 0 { disk.setFree(5 << 20) } else { disk.setFree(50 << 20) } time.Sleep(time.Millisecond) } }() var workers sync.WaitGroup for w := 0; w < 4; w++ { workers.Add(1) go func(w int) { defer workers.Done() buf := make([]byte, 5000) for i := 0; i < 300; i++ { fid := fmt.Sprintf("%d,%xaabbccdd", w+1, i+1) data := bytes.Repeat([]byte{byte(w*31 + i)}, 512+(i%5)*1000) cache.SetChunk(fid, data) if n, _ := cache.ReadChunkAt(buf[:len(data)], fid, 0); n == len(data) && !bytes.Equal(buf[:n], data) { t.Errorf("chunk %s read back wrong data", fid) } cache.IsInCache(fid, true) } }(w) } workers.Wait() close(stop) flipper.Wait() }