mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
mount: leave -cacheMinFreeSpace free on the chunk cache's disk (#13124)
* mount: leave -cacheMinFreeSpace free on the chunk cache's disk weed mount sizes its on-disk chunk cache by -cacheCapacityMB alone and preallocates each cache file in full when it creates it. With a capacity larger than the free space of the disk holding -cacheDir, the cache takes that disk down to nothing: the preallocations run until fallocate fails, and chunk writes fill the rest. The mount's metadata cache (a leveldb store under -cacheDir) and the swap files of dirty pages (-cacheDirWrite, which defaults to -cacheDir) live on the same disk, so once it is full their writes fail with ENOSPC, and writes whose dirty pages spill to swap return EIO to the application. The same happens when several mounts share a cache disk and together are configured beyond it. -cacheMinFreeSpace is the free space the cache leaves on that disk, written like the volume server's -minFreeSpace: a percentage like 1 or a size like 10GiB, 1 by default, as for volume servers. - When the cache opens, its disk layers shrink to the space above the floor, counting the cache files already in the directory as the cache's own. With no room the disk tier keeps no files. - Each new cache file preallocates only what the disk holds above the floor at that moment, so the files of one cache, or the caches of several mounts opening together, stop reserving at the floor. - A chunk write that lands in blocks its file already holds, preallocated or written, goes ahead as before, even with the disk under the floor. A write that takes new disk space, into a file a rotation truncated or where nothing could be preallocated, goes ahead only while the space above the floor covers it. The disk is read at most once a second, and the cache counts what it takes in between, so it cannot run past the floor between readings. A rotation gives the truncated file's blocks back, so the write after it reads the disk again. A chunk the cache cannot place is not cached, like any other miss. The webdav server's cache passes no floor and behaves as before. * mount: read the cache disk on every write that takes space, leave the index files room Review follow-ups. - take reads the disk each time, instead of once a second less what the cache took since, so a write sees what other mounts sharing the disk wrote, and what a rotation gave back. It runs only for writes past the blocks a file already holds, and a statfs costs little next to the write. - The index files (.idx and the leveldb maps) grow by a few dozen bytes a chunk beside the data files that the cache size counts. Sizing leaves them a sixteenth of the room above the floor. - The cache's own files count as room by the blocks they hold, so a file that was preallocated but not yet written when the mount exited counts in full when the cache reopens. - weed fuse checks -o cacheMinFreeSpace in the parent as well: the parent waits for the child's signal, and a child that rejects the value never sends it. * mount: keep the resolveCacheDirs doc comment on resolveCacheDirs Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: say -cacheMinFreeSpace stops new disk space, not every chunk Under the floor the cache still fills the blocks its files already hold. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
18 files changed
+762
-16
No files matched your search
@@ -191,6 +191,8 @@ func runFuse(cmd *Command, args []string) bool {
|
||||
}
|
||||
case "cacheDirWrite":
|
||||
mountOptions.cacheDirForWrite = ¶meter.value
|
||||
case "cacheMinFreeSpace":
|
||||
mountOptions.cacheMinFreeSpace = ¶meter.value
|
||||
case "writeBufferSizeMB":
|
||||
if parsed, err := strconv.ParseInt(parameter.value, 0, 64); err == nil {
|
||||
mountOptions.writeBufferSizeMB = &parsed
|
||||
@@ -328,6 +330,11 @@ func runFuse(cmd *Command, args []string) bool {
|
||||
if err := checkIdmap(runtime.GOOS, *mountOptions.idmap, *mountOptions.defaultPermissions); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
// The child checks it as well, but by then the parent only waits for
|
||||
// its signal, so a bad value has to fail here.
|
||||
if _, err := parseCacheMinFreeSpace(&mountOptions); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
util_http.InitGlobalHttpClient()
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ type MountOptions struct {
|
||||
cacheDirForRead *string
|
||||
cacheDirForWrite *string
|
||||
cacheSizeMBForRead *int64
|
||||
cacheMinFreeSpace *string
|
||||
writeBufferSizeMB *int64
|
||||
dataCenter *string
|
||||
allowOthers *bool
|
||||
@@ -120,6 +121,7 @@ func init() {
|
||||
mountOptions.readerCacheSizeMB = cmdMount.Flag.Int64("readerCacheSizeMB", 256, "memory budget in MiB for downloaded and in-flight reader buffers across all files; must fit the largest pooled chunk buffer")
|
||||
mountOptions.cacheDirForRead = cmdMount.Flag.String("cacheDir", os.TempDir(), "local cache directory for file chunks and meta data")
|
||||
mountOptions.cacheSizeMBForRead = cmdMount.Flag.Int64("cacheCapacityMB", 128, "file chunk read cache capacity in MB")
|
||||
mountOptions.cacheMinFreeSpace = cmdMount.Flag.String("cacheMinFreeSpace", "1", "free space the chunk cache leaves on the disk holding -cacheDir, as a percentage like 1 or a size like 10GiB: the cache shrinks to fit above it and takes no new disk space while the disk is under it")
|
||||
mountOptions.cacheDirForWrite = cmdMount.Flag.String("cacheDirWrite", "", "buffer writes mostly for large files")
|
||||
mountOptions.writeBufferSizeMB = cmdMount.Flag.Int64("writeBufferSizeMB", 0, "global cap on the per-mount write buffer (memory + swap) in MB, 0 means unlimited. Bounds /tmp growth when volume uploads stall")
|
||||
mountOptions.cacheMetaTtlSec = cmdMount.Flag.Int("cacheMetaTtlSec", 60, "metadata cache validity seconds")
|
||||
|
||||
@@ -198,6 +198,7 @@ type fileSystemParams struct {
|
||||
chunkSizeLimitMB int
|
||||
cacheDirForRead string
|
||||
cacheDirForWrite string
|
||||
cacheMinFree *util.MinFreeSpace // the parsed -cacheMinFreeSpace
|
||||
|
||||
// eagerFilerCreate persists a created file's entry at create time rather
|
||||
// than at flush. A platform sets it when it cannot run the flush before
|
||||
@@ -230,6 +231,7 @@ func buildSeaweedFileSystem(option *MountOptions, p fileSystemParams) *mount.WFS
|
||||
ReaderCacheSizeMB: readerCacheSizeMB,
|
||||
CacheDirForRead: p.cacheDirForRead,
|
||||
CacheSizeMBForRead: *option.cacheSizeMBForRead,
|
||||
CacheMinFreeSpace: p.cacheMinFree,
|
||||
CacheDirForWrite: p.cacheDirForWrite,
|
||||
WriteBufferSizeMB: *option.writeBufferSizeMB,
|
||||
CacheMetaTTlSec: *option.cacheMetaTtlSec,
|
||||
@@ -362,6 +364,19 @@ func resolveMountRoot(filerMountRootPath string) string {
|
||||
return mountRoot
|
||||
}
|
||||
|
||||
// parseCacheMinFreeSpace reads -cacheMinFreeSpace, written like the volume
|
||||
// server's -minFreeSpace.
|
||||
func parseCacheMinFreeSpace(option *MountOptions) (*util.MinFreeSpace, error) {
|
||||
if option.cacheMinFreeSpace == nil {
|
||||
return nil, nil
|
||||
}
|
||||
minFreeSpace, err := util.ParseMinFreeSpace(*option.cacheMinFreeSpace)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cacheMinFreeSpace %q: want a percentage like 1 or a size like 10GiB", *option.cacheMinFreeSpace)
|
||||
}
|
||||
return minFreeSpace, nil
|
||||
}
|
||||
|
||||
// resolveCacheDirs falls back to the read cache when no write cache is set.
|
||||
func resolveCacheDirs(option *MountOptions) (string, string) {
|
||||
cacheDirForRead := util.ResolvePath(*option.cacheDirForRead)
|
||||
|
||||
@@ -471,3 +471,36 @@ func Test_ensureMountRootDirectory(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func Test_parseCacheMinFreeSpace(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
value string
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{value: "1", want: "1.00%"},
|
||||
{value: "0", want: "0.00%"},
|
||||
{value: "10GiB", want: "10GiB"},
|
||||
{value: "101", wantErr: true},
|
||||
{value: "lots", wantErr: true},
|
||||
} {
|
||||
value := tc.value
|
||||
got, err := parseCacheMinFreeSpace(&MountOptions{cacheMinFreeSpace: &value})
|
||||
if tc.wantErr {
|
||||
if err == nil {
|
||||
t.Errorf("-cacheMinFreeSpace=%s: no error", tc.value)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("-cacheMinFreeSpace=%s: %v", tc.value, err)
|
||||
continue
|
||||
}
|
||||
if got.String() != tc.want {
|
||||
t.Errorf("-cacheMinFreeSpace=%s: %s, want %s", tc.value, got, tc.want)
|
||||
}
|
||||
}
|
||||
if got, err := parseCacheMinFreeSpace(&MountOptions{}); got != nil || err != nil {
|
||||
t.Errorf("unset -cacheMinFreeSpace: %v, %v; want no floor", got, err)
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,11 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
fmt.Println(err)
|
||||
return false
|
||||
}
|
||||
cacheMinFree, parseErr := parseCacheMinFreeSpace(option)
|
||||
if parseErr != nil {
|
||||
fmt.Println(parseErr)
|
||||
return false
|
||||
}
|
||||
|
||||
// basic checks
|
||||
chunkSizeLimitMB := *mountOptions.chunkSizeLimitMB
|
||||
@@ -264,6 +269,7 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
chunkSizeLimitMB: chunkSizeLimitMB,
|
||||
cacheDirForRead: cacheDirForRead,
|
||||
cacheDirForWrite: cacheDirForWrite,
|
||||
cacheMinFree: cacheMinFree,
|
||||
})
|
||||
|
||||
if !createMountRoot(seaweedFileSystem, mountRoot, bucketRootPath, filerAddresses) {
|
||||
|
||||
@@ -34,6 +34,11 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
fmt.Println(err)
|
||||
return false
|
||||
}
|
||||
cacheMinFree, parseErr := parseCacheMinFreeSpace(option)
|
||||
if parseErr != nil {
|
||||
fmt.Println(parseErr)
|
||||
return false
|
||||
}
|
||||
|
||||
chunkSizeLimitMB := *mountOptions.chunkSizeLimitMB
|
||||
if chunkSizeLimitMB <= 0 {
|
||||
@@ -105,6 +110,7 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
chunkSizeLimitMB: chunkSizeLimitMB,
|
||||
cacheDirForRead: cacheDirForRead,
|
||||
cacheDirForWrite: cacheDirForWrite,
|
||||
cacheMinFree: cacheMinFree,
|
||||
// WinFsp posts the cleanup and close that carry the flush after
|
||||
// CloseHandle has already returned, so entry creation cannot wait
|
||||
// for the flush the way it does when close(2) runs it synchronously.
|
||||
|
||||
@@ -58,6 +58,9 @@ type Option struct {
|
||||
ReaderCacheSizeMB int64
|
||||
CacheDirForRead string
|
||||
CacheSizeMBForRead int64
|
||||
// CacheMinFreeSpace is the free space the chunk cache leaves on the disk
|
||||
// holding CacheDirForRead; nil leaves the cache its full size.
|
||||
CacheMinFreeSpace *util.MinFreeSpace
|
||||
CacheDirForWrite string
|
||||
WriteBufferSizeMB int64
|
||||
CacheMetaTTlSec int
|
||||
@@ -346,7 +349,7 @@ func NewSeaweedFileSystem(option *Option) *WFS {
|
||||
wfs.option.filerIndex = int32(rand.IntN(len(option.FilerAddresses)))
|
||||
wfs.option.setupUniqueCacheDirectory()
|
||||
if option.CacheSizeMBForRead > 0 {
|
||||
wfs.chunkCache = chunk_cache.NewTieredChunkCache(256, option.getUniqueCacheDirForRead(), option.CacheSizeMBForRead, 1024*1024)
|
||||
wfs.chunkCache = chunk_cache.NewTieredChunkCache(256, option.getUniqueCacheDirForRead(), option.CacheSizeMBForRead, 1024*1024, option.CacheMinFreeSpace)
|
||||
}
|
||||
if option.WriteBufferSizeMB > 0 {
|
||||
wfs.writeBufferAccountant = page_writer.NewWriteBufferAccountant(option.WriteBufferSizeMB * 1024 * 1024)
|
||||
|
||||
@@ -413,7 +413,7 @@ func NewWebDavFileSystem(option *WebDavOption) (webdav.FileSystem, error) {
|
||||
cacheDir := path.Join(option.CacheDir, cacheUniqueId)
|
||||
|
||||
os.MkdirAll(cacheDir, os.FileMode(0755))
|
||||
chunkCache := chunk_cache.NewTieredChunkCache(256, cacheDir, option.CacheSizeMB, 1024*1024)
|
||||
chunkCache := chunk_cache.NewTieredChunkCache(256, cacheDir, option.CacheSizeMB, 1024*1024, nil)
|
||||
t := &WebDavFileSystem{
|
||||
option: option,
|
||||
chunkCache: chunkCache,
|
||||
|
||||
@@ -122,6 +122,17 @@ func NewDiskStatus(path string) (disk *volume_server_pb.DiskStatus) {
|
||||
return
|
||||
}
|
||||
|
||||
// DiskUsage reads the size and free space of the disk holding path. Unlike
|
||||
// NewDiskStatus it returns the statfs error and logs nothing, for callers
|
||||
// that read it often. All is 0 where the platform cannot tell.
|
||||
func DiskUsage(path string) (*volume_server_pb.DiskStatus, error) {
|
||||
disk := &volume_server_pb.DiskStatus{Dir: path}
|
||||
if err := fillInDiskStatus(disk); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return disk, nil
|
||||
}
|
||||
|
||||
func NewDiskStatusOnStart(path string, config DiskIOProbeConfig) (disk *volume_server_pb.DiskStatus) {
|
||||
disk = &volume_server_pb.DiskStatus{Dir: path}
|
||||
diskProbe(disk, config)
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
//go:build !unix
|
||||
|
||||
package chunk_cache
|
||||
|
||||
import "os"
|
||||
|
||||
// allocatedSize is how many bytes of disk f holds; here only what it has
|
||||
// written counts, since this platform does not preallocate.
|
||||
func allocatedSize(f *os.File) int64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func allocatedSizeOf(info os.FileInfo) int64 {
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
//go:build unix
|
||||
|
||||
package chunk_cache
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// allocatedSize is how many bytes of disk f holds, preallocated blocks past
|
||||
// its end included.
|
||||
func allocatedSize(f *os.File) int64 {
|
||||
info, err := f.Stat()
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return allocatedSizeOf(info)
|
||||
}
|
||||
|
||||
func allocatedSizeOf(info os.FileInfo) int64 {
|
||||
if st, ok := info.Sys().(*syscall.Stat_t); ok {
|
||||
return int64(st.Blocks) * 512
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
var ErrorOutOfBounds = errors.New("attempt to read out of bounds")
|
||||
@@ -37,22 +38,35 @@ type TieredChunkCache struct {
|
||||
onDiskCacheSizeLimit1 uint64
|
||||
onDiskCacheSizeLimit2 uint64
|
||||
maxFilePartSizeInCache uint64
|
||||
// diskSpace keeps the disk layers above the disk's minimum free space;
|
||||
// nil when there is none to keep.
|
||||
diskSpace *diskSpaceGuard
|
||||
}
|
||||
|
||||
var _ ChunkCache = &TieredChunkCache{}
|
||||
|
||||
func NewTieredChunkCache(maxEntries int64, dir string, diskSizeInUnit int64, unitSize int64) *TieredChunkCache {
|
||||
// diskLayerNames prefix the files of the three disk layers, smallest chunks first.
|
||||
var diskLayerNames = [3]string{"c0_2", "c1_3", "c2_2"}
|
||||
|
||||
// NewTieredChunkCache keeps chunks in memory and in up to
|
||||
// diskSizeInUnit*unitSize bytes of files in dir. A non-nil minFreeSpace also
|
||||
// keeps that much of the disk holding dir free: the disk cache shrinks to fit
|
||||
// above it, possibly to nothing, and takes new disk space only while the
|
||||
// space above it covers the write.
|
||||
func NewTieredChunkCache(maxEntries int64, dir string, diskSizeInUnit int64, unitSize int64, minFreeSpace *util.MinFreeSpace) *TieredChunkCache {
|
||||
|
||||
c := &TieredChunkCache{
|
||||
memCache: NewChunkCacheInMemory(maxEntries),
|
||||
memCache: NewChunkCacheInMemory(maxEntries),
|
||||
diskSpace: newDiskSpaceGuard(dir, minFreeSpace),
|
||||
}
|
||||
diskSizeInUnit = c.diskSpace.capacity(diskSizeInUnit*unitSize) / unitSize
|
||||
c.diskCaches = make([]*OnDiskCacheLayer, 3)
|
||||
c.onDiskCacheSizeLimit0 = uint64(unitSize)
|
||||
c.onDiskCacheSizeLimit1 = 4 * c.onDiskCacheSizeLimit0
|
||||
c.onDiskCacheSizeLimit2 = 2 * c.onDiskCacheSizeLimit1
|
||||
c.diskCaches[0] = NewOnDiskCacheLayer(dir, "c0_2", diskSizeInUnit*unitSize/8, 2)
|
||||
c.diskCaches[1] = NewOnDiskCacheLayer(dir, "c1_3", diskSizeInUnit*unitSize/4+diskSizeInUnit*unitSize/8, 3)
|
||||
c.diskCaches[2] = NewOnDiskCacheLayer(dir, "c2_2", diskSizeInUnit*unitSize/2, 2)
|
||||
c.diskCaches[0] = NewOnDiskCacheLayer(dir, diskLayerNames[0], diskSizeInUnit*unitSize/8, 2, c.diskSpace)
|
||||
c.diskCaches[1] = NewOnDiskCacheLayer(dir, diskLayerNames[1], diskSizeInUnit*unitSize/4+diskSizeInUnit*unitSize/8, 3, c.diskSpace)
|
||||
c.diskCaches[2] = NewOnDiskCacheLayer(dir, diskLayerNames[2], diskSizeInUnit*unitSize/2, 2, c.diskSpace)
|
||||
c.maxFilePartSizeInCache = uint64(unitSize*diskSizeInUnit) / 4
|
||||
|
||||
return c
|
||||
|
||||
@@ -26,14 +26,19 @@ type ChunkCacheVolume struct {
|
||||
sizeLimit int64
|
||||
lastModTime time.Time
|
||||
fileSize int64
|
||||
// reserved is how far into the .dat file the disk already holds blocks
|
||||
// for it, preallocated or written; a write past it takes new disk space.
|
||||
reserved int64
|
||||
}
|
||||
|
||||
func LoadOrCreateChunkCacheVolume(fileName string, preallocate int64) (*ChunkCacheVolume, error) {
|
||||
// LoadOrCreateChunkCacheVolume opens the cache file fileName, which takes up
|
||||
// to sizeLimit bytes of chunks. Creating it reserves preallocate bytes of disk.
|
||||
func LoadOrCreateChunkCacheVolume(fileName string, sizeLimit, preallocate int64) (*ChunkCacheVolume, error) {
|
||||
|
||||
v := &ChunkCacheVolume{
|
||||
smallBuffer: make([]byte, types.NeedlePaddingSize),
|
||||
fileName: fileName,
|
||||
sizeLimit: preallocate,
|
||||
sizeLimit: sizeLimit,
|
||||
}
|
||||
|
||||
var err error
|
||||
@@ -70,6 +75,10 @@ func LoadOrCreateChunkCacheVolume(fileName string, preallocate int64) (*ChunkCac
|
||||
}
|
||||
v.lastModTime = time.Now()
|
||||
}
|
||||
if diskFile, ok := v.DataBackend.(*backend.DiskFile); ok {
|
||||
v.reserved = allocatedSize(diskFile.File)
|
||||
}
|
||||
v.reserved = max(v.reserved, v.fileSize)
|
||||
|
||||
if indexFile, err = os.OpenFile(v.fileName+".idx", os.O_RDWR|os.O_CREATE, 0644); err != nil {
|
||||
return nil, fmt.Errorf("cannot write cache index %s.idx: %v", v.fileName, err)
|
||||
@@ -123,7 +132,9 @@ func (v *ChunkCacheVolume) doReset() {
|
||||
|
||||
func (v *ChunkCacheVolume) Reset() (*ChunkCacheVolume, error) {
|
||||
v.doReset()
|
||||
return LoadOrCreateChunkCacheVolume(v.fileName, v.sizeLimit)
|
||||
// A reset reuses the truncated file and reserves nothing, so a rotation
|
||||
// never preallocates past the disk's minimum free space.
|
||||
return LoadOrCreateChunkCacheVolume(v.fileName, v.sizeLimit, 0)
|
||||
}
|
||||
|
||||
// minFadviseSize is the minimum read size (in bytes) before we call fadvise
|
||||
@@ -227,9 +238,21 @@ func (v *ChunkCacheVolume) WriteNeedle(key types.NeedleId, data []byte) error {
|
||||
v.fileSize += int64(types.NeedlePaddingSize - extraSize)
|
||||
}
|
||||
|
||||
v.reserved = max(v.reserved, v.fileSize)
|
||||
|
||||
if err := v.nm.Put(key, types.ToOffset(offset), types.Size(len(data))); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// newSpaceFor is how much new disk space WriteNeedle of n bytes takes: what
|
||||
// it writes past the blocks the file already holds.
|
||||
func (v *ChunkCacheVolume) newSpaceFor(n int) int64 {
|
||||
end := v.fileSize + int64(n)
|
||||
if extra := end % types.NeedlePaddingSize; extra != 0 {
|
||||
end += types.NeedlePaddingSize - extra
|
||||
}
|
||||
return max(0, end-v.reserved)
|
||||
}
|
||||
@@ -17,7 +17,7 @@ func TestOnDisk(t *testing.T) {
|
||||
|
||||
totalDiskSizeInKB := int64(32)
|
||||
|
||||
cache := NewTieredChunkCache(2, tmpDir, totalDiskSizeInKB, 1024)
|
||||
cache := NewTieredChunkCache(2, tmpDir, totalDiskSizeInKB, 1024, nil)
|
||||
|
||||
writeCount := 5
|
||||
type test_data struct {
|
||||
@@ -80,7 +80,7 @@ func TestOnDisk(t *testing.T) {
|
||||
|
||||
cache.Shutdown()
|
||||
|
||||
cache = NewTieredChunkCache(2, tmpDir, totalDiskSizeInKB, 1024)
|
||||
cache = NewTieredChunkCache(2, tmpDir, totalDiskSizeInKB, 1024, nil)
|
||||
|
||||
// After cache restart, entries may or may not be persisted depending on eviction
|
||||
// With new validation system, we should get either correct data or cache misses
|
||||
@@ -152,7 +152,7 @@ func TestLoadOrCreateChunkCacheVolumeClosesFilesOnError(t *testing.T) {
|
||||
|
||||
before := openFDCount()
|
||||
|
||||
_, err := LoadOrCreateChunkCacheVolume(fileName, 1024)
|
||||
_, err := LoadOrCreateChunkCacheVolume(fileName, 1024, 1024)
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
package chunk_cache
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/stats"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// diskStatusOf reads the disk holding the cache directory. It is a variable
|
||||
// so a test can stand in for a disk that is full or near its floor.
|
||||
var diskStatusOf = stats.DiskUsage
|
||||
|
||||
// diskSpaceGuard keeps the disk cache from taking the disk that holds it
|
||||
// under a minimum free space, which the mount's metadata cache and write swap
|
||||
// files share with it. It sizes the cache to fit above that floor when the
|
||||
// cache opens, lets each new cache file preallocate only what the disk holds
|
||||
// above the floor, and lets a chunk write take new disk space only while the
|
||||
// space above the floor covers it. A nil guard limits nothing.
|
||||
type diskSpaceGuard struct {
|
||||
dir string
|
||||
minFreeSpace util.MinFreeSpace
|
||||
|
||||
// Guarded by the TieredChunkCache write lock.
|
||||
refusing bool
|
||||
warnedAt time.Time
|
||||
}
|
||||
|
||||
func newDiskSpaceGuard(dir string, minFreeSpace *util.MinFreeSpace) *diskSpaceGuard {
|
||||
if minFreeSpace == nil {
|
||||
return nil
|
||||
}
|
||||
return &diskSpaceGuard{dir: dir, minFreeSpace: *minFreeSpace}
|
||||
}
|
||||
|
||||
var errDiskSizeUnknown = errors.New("the platform does not report disk sizes")
|
||||
|
||||
// available is how many more bytes the disk holds above the floor. When the
|
||||
// disk cannot be read the caller limits nothing.
|
||||
func (g *diskSpaceGuard) available() (uint64, error) {
|
||||
status, err := diskStatusOf(g.dir)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if status.All == 0 {
|
||||
return 0, errDiskSizeUnknown
|
||||
}
|
||||
return g.minFreeSpace.AvailableSpace(status.Free, status.All), nil
|
||||
}
|
||||
|
||||
// capacity cuts a disk cache of size bytes to what fits above the floor: the
|
||||
// free space over it, plus what the cache's files in dir already hold, since
|
||||
// a cache reopened after an unclean exit reuses them. A sixteenth of that is
|
||||
// left to the index files (.idx and the leveldb maps), which grow by a few
|
||||
// dozen bytes a chunk beside the data files the size counts.
|
||||
func (g *diskSpaceGuard) capacity(size int64) int64 {
|
||||
if g == nil || size <= 0 {
|
||||
return size
|
||||
}
|
||||
available, err := g.available()
|
||||
if err != nil {
|
||||
glog.Warningf("chunk cache %s: keeping no free space on the disk, cannot read it: %v", g.dir, err)
|
||||
return size
|
||||
}
|
||||
budget := available + cacheFilesSize(g.dir)
|
||||
budget -= budget / 16
|
||||
if uint64(size) <= budget {
|
||||
return size
|
||||
}
|
||||
glog.Warningf("chunk cache %s: %s on disk instead of %s, to keep %s of the disk free",
|
||||
g.dir, util.BytesToHumanReadable(budget), util.BytesToHumanReadable(uint64(size)), g.minFreeSpace.String())
|
||||
return int64(budget)
|
||||
}
|
||||
|
||||
// preallocation is how much of want a new cache file may reserve: no more
|
||||
// than the disk holds above the floor now, so the files of one cache, or of
|
||||
// several caches opening on the same disk, stop reserving at the floor.
|
||||
func (g *diskSpaceGuard) preallocation(want int64) int64 {
|
||||
if g == nil || want <= 0 {
|
||||
return want
|
||||
}
|
||||
available, err := g.available()
|
||||
if err != nil || uint64(want) <= available {
|
||||
return want
|
||||
}
|
||||
return int64(available)
|
||||
}
|
||||
|
||||
// take reports whether a chunk write may take n more bytes of the disk and
|
||||
// leave the floor free. It reads the disk each time, so it sees what other
|
||||
// mounts sharing the disk wrote, and what a rotation gave back. The caller
|
||||
// holds the cache's write lock.
|
||||
func (g *diskSpaceGuard) take(n int64) bool {
|
||||
if g == nil || n <= 0 {
|
||||
return true
|
||||
}
|
||||
available, err := g.available()
|
||||
if err != nil {
|
||||
return true // the disk cannot be read: limit nothing
|
||||
}
|
||||
ok := available >= uint64(n)
|
||||
if ok == g.refusing {
|
||||
g.refusing = !ok
|
||||
if ok {
|
||||
glog.V(1).Infof("chunk cache %s: taking disk space again", g.dir)
|
||||
} else if now := time.Now(); now.Sub(g.warnedAt) >= time.Minute {
|
||||
g.warnedAt = now
|
||||
glog.Warningf("chunk cache %s: taking no more disk space, %s left above the %s of the disk kept free",
|
||||
g.dir, util.BytesToHumanReadable(available), g.minFreeSpace.String())
|
||||
}
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
// cacheFilesSize adds up the disk the files of the disk layers already in dir
|
||||
// hold, preallocated blocks past their ends included.
|
||||
func cacheFilesSize(dir string) (size uint64) {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if !entry.Type().IsRegular() || !isDiskLayerFile(entry.Name()) {
|
||||
continue
|
||||
}
|
||||
if info, err := entry.Info(); err == nil {
|
||||
size += uint64(max(info.Size(), allocatedSizeOf(info)))
|
||||
}
|
||||
}
|
||||
return size
|
||||
}
|
||||
|
||||
func isDiskLayerFile(name string) bool {
|
||||
if !strings.HasSuffix(name, ".dat") && !strings.HasSuffix(name, ".idx") {
|
||||
return false
|
||||
}
|
||||
for _, layerName := range diskLayerNames {
|
||||
if strings.HasPrefix(name, layerName+"_") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
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()
|
||||
}
|
||||
@@ -12,19 +12,25 @@ import (
|
||||
|
||||
type OnDiskCacheLayer struct {
|
||||
diskCaches []*ChunkCacheVolume
|
||||
diskSpace *diskSpaceGuard
|
||||
}
|
||||
|
||||
func NewOnDiskCacheLayer(dir, namePrefix string, diskSize int64, segmentCount int) *OnDiskCacheLayer {
|
||||
func NewOnDiskCacheLayer(dir, namePrefix string, diskSize int64, segmentCount int, diskSpace *diskSpaceGuard) *OnDiskCacheLayer {
|
||||
|
||||
c := &OnDiskCacheLayer{diskSpace: diskSpace}
|
||||
if diskSize <= 0 {
|
||||
// no room for this layer: it keeps no files and caches nothing
|
||||
return c
|
||||
}
|
||||
|
||||
volumeCount, volumeSize := int(diskSize/(30000*1024*1024)), int64(30000*1024*1024)
|
||||
if volumeCount < segmentCount {
|
||||
volumeCount, volumeSize = segmentCount, diskSize/int64(segmentCount)
|
||||
}
|
||||
|
||||
c := &OnDiskCacheLayer{}
|
||||
for i := 0; i < volumeCount; i++ {
|
||||
fileName := path.Join(dir, fmt.Sprintf("%s_%d", namePrefix, i))
|
||||
diskCache, err := LoadOrCreateChunkCacheVolume(fileName, volumeSize)
|
||||
diskCache, err := LoadOrCreateChunkCacheVolume(fileName, volumeSize, diskSpace.preallocation(volumeSize))
|
||||
if err != nil {
|
||||
glog.Errorf("failed to add cache %s : %v", fileName, err)
|
||||
} else {
|
||||
@@ -57,6 +63,12 @@ func (c *OnDiskCacheLayer) setChunk(needleId types.NeedleId, data []byte) {
|
||||
c.diskCaches[0] = t
|
||||
}
|
||||
|
||||
// A chunk always lands where the file already holds the blocks; past
|
||||
// them it takes new disk space, which must leave the disk's floor free.
|
||||
if !c.diskSpace.take(c.diskCaches[0].newSpaceFor(len(data))) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := c.diskCaches[0].WriteNeedle(needleId, data); err != nil {
|
||||
glog.V(0).Infof("cache write %v size %d: %v", needleId, len(data), err)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user