diff --git a/weed/filer/reader_at.go b/weed/filer/reader_at.go index 16b7d20958..cb52d9177e 100644 --- a/weed/filer/reader_at.go +++ b/weed/filer/reader_at.go @@ -281,6 +281,32 @@ func (c *ChunkReadAt) doReadAt(ctx context.Context, p []byte, offset int64) (n i n += copied } } else { + // The stream leaves its chunk before any task makes room, as in a read + // of one chunk, or its pin would count against another stream's chunk, + // and the last task takes it to the last chunk. The tasks reading the + // chunk it leaves hold that download first, as leaving drops a chunk no + // read holds, and they start first and take no slot, as evicting it waits + // for them. + last := tasks[len(tasks)-1] + current := c.stream.current() + held := make(map[*chunkReadTask]*SingleChunkCacher) + ordered := make([]*chunkReadTask, 0, len(tasks)) + for _, task := range tasks[:len(tasks)-1] { + if current != nil && task.chunk.FileId == current.chunkFileId && c.readerCache.hold(current) { + held[task] = current + ordered = append(ordered, task) + } + } + for _, task := range tasks { + if held[task] == nil { + ordered = append(ordered, task) + } + } + if current != nil && current.chunkFileId != last.chunk.FileId { + // a concurrent read that moved the stream meanwhile keeps it + c.readerCache.unpin(c.stream.detach(current)) + } + // Parallel chunk fetching for multiple chunks // This significantly improves throughput when chunks are on different volume servers g, gCtx := errgroup.WithContext(ctx) @@ -293,12 +319,22 @@ func (c *ChunkReadAt) doReadAt(ctx context.Context, p []byte, offset int64) (n i if concurrency > len(tasks) { concurrency = len(tasks) } - g.SetLimit(concurrency) + slots := make(chan struct{}, concurrency) - for _, task := range tasks { + for _, task := range ordered { + var stream *chunkStream + if task == last { + stream = &c.stream + } + if held[task] == nil { + slots <- struct{}{} + } g.Go(func() error { + if held[task] == nil { + defer func() { <-slots }() + } // Read directly into the correct position in the output buffer - copied, readErr := c.readChunkSliceAtForParallel(gCtx, p[task.bufferStart:task.bufferEnd], task.chunk, task.chunkOffset) + copied, readErr := c.readChunkSliceAtForParallel(gCtx, p[task.bufferStart:task.bufferEnd], task.chunk, task.chunkOffset, stream, held[task]) task.bytesRead = copied task.modifiedTsNs = task.chunk.ModifiedTsNs return readErr @@ -403,8 +439,16 @@ func (c *ChunkReadAt) readChunkSliceAt(ctx context.Context, buffer []byte, chunk // readChunkSliceAtForParallel is a simplified version for parallel chunk fetching // It doesn't update lastChunkFid or trigger prefetch (handled by the caller) -func (c *ChunkReadAt) readChunkSliceAtForParallel(ctx context.Context, buffer []byte, chunkView *ChunkView, offset uint64) (n int, err error) { +// A non-nil stream moves to the chunk as in readChunkSliceAt, and a download +// the caller holds for this read serves it first. +func (c *ChunkReadAt) readChunkSliceAtForParallel(ctx context.Context, buffer []byte, chunkView *ChunkView, offset uint64, stream *chunkStream, held *SingleChunkCacher) (n int, err error) { + if held != nil { + if n, err = held.readChunkAt(ctx, buffer, int64(offset)); n > 0 || err != nil { + return n, err + } + } if c.readsRange(chunkView) { + c.readerCache.releaseStream(stream) n, err = c.readerCache.chunkCache.ReadChunkAt(buffer, chunkView.FileId, offset) if n > 0 { return n, err @@ -412,7 +456,7 @@ func (c *ChunkReadAt) readChunkSliceAtForParallel(ctx context.Context, buffer [] return c.readerCache.fetchChunkRange(ctx, buffer, chunkView, int64(offset)) } shouldCache := (uint64(chunkView.ViewOffset) + chunkView.ChunkSize) <= c.readerCache.chunkCache.GetMaxFilePartSizeInCache() - return c.readerCache.ReadChunkAt(ctx, buffer, chunkView.FileId, chunkView.CipherKey, chunkView.IsGzipped, int64(offset), int(chunkView.ChunkSize), shouldCache) + return c.readerCache.readChunkAt(ctx, stream, buffer, chunkView.FileId, chunkView.CipherKey, chunkView.IsGzipped, int64(offset), int(chunkView.ChunkSize), shouldCache) } func zero(buffer []byte, start, length int64) int { diff --git a/weed/filer/reader_at_shared_test.go b/weed/filer/reader_at_shared_test.go index 28bb39475d..26ab206a0f 100644 --- a/weed/filer/reader_at_shared_test.go +++ b/weed/filer/reader_at_shared_test.go @@ -7,9 +7,11 @@ import ( "sync" "sync/atomic" "testing" + "time" "github.com/seaweedfs/seaweedfs/weed/util/chunk_cache" util_http "github.com/seaweedfs/seaweedfs/weed/util/http" + "github.com/seaweedfs/seaweedfs/weed/util/mem" ) // Two streams (e.g. two S3 GETs) reading the same object through one shared @@ -98,6 +100,13 @@ func newStreamTestReaderCache(chunkCache chunk_cache.ChunkCache) *ReaderCache { return rc } +// in reports whether the stream is positioned in fileId's chunk. +func (stream *chunkStream) in(fileId string) bool { + stream.mu.Lock() + defer stream.mu.Unlock() + return stream.cacher != nil && stream.cacher.chunkFileId == fileId +} + func isRetained(rc *ReaderCache, fileId string) bool { rc.Lock() defer rc.Unlock() @@ -577,3 +586,578 @@ func TestChunkReadAtPinnedEvictionFallsBackWhenAllPinned(t *testing.T) { t.Fatal("new downloader missing after pinned fallback eviction") } } + +// newReaderCacheWithPrefetch returns a cache whose download of "prefetched" +// runs until release is closed, and counts fetches of chunk0. +func newReaderCacheWithPrefetch(limit int, release chan struct{}, chunk0Fetches *int32, budgets ...*ReaderCacheBudget) *ReaderCache { + rc := NewReaderCache(limit, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) { + return []string{"unused"}, nil + }, nil, budgets...) + rc.fetchChunkDataFn = func(ctx context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, fileId string, _ util_http.RefreshUrlsFunc) (int, error) { + switch fileId { + case "chunk0": + atomic.AddInt32(chunk0Fetches, 1) + case "prefetched": + select { + case <-release: + case <-ctx.Done(): + } + } + return len(buffer), nil + } + return rc +} + +// startPrefetch registers "prefetched" the way MaybeCache does: running and +// pinned by no stream. It returns once the download holds its reservation, +// which it takes after it signals that it started. +func startPrefetch(rc *ReaderCache, chunkSize int) { + rc.Lock() + cacher := newSingleChunkCacher(rc, "prefetched", nil, false, chunkSize, false) + cacher.wg.Add(1) + rc.downloaders["prefetched"] = cacher + rc.Unlock() + go cacher.startCaching() + <-cacher.cacheStartedCh + for rc.budget != nil { + rc.budget.Lock() + _, reserved := rc.budget.reservations[cacher] + rc.budget.Unlock() + if reserved { + return + } + time.Sleep(time.Millisecond) + } +} + +// A running download takes a slot it gives up once it finishes, so a stream's +// chunk is not evicted to make room next to it. +func TestChunkReadAtPinnedChunkSurvivesARunningPrefetch(t *testing.T) { + const chunkSize = 64 << 10 + var fetches int32 + release := make(chan struct{}) + rc := newReaderCacheWithPrefetch(2, release, &fetches) + defer rc.destroy() + defer close(release) + + stream := &chunkStream{} + buf := make([]byte, 16<<10) + if _, err := rc.readChunkAt(context.Background(), stream, buf, "chunk0", nil, false, 0, chunkSize, false); err != nil { + t.Fatal(err) + } + startPrefetch(rc, chunkSize) + + if _, err := rc.ReadChunkAt(context.Background(), buf, "chunk1", nil, false, 0, chunkSize, false); err != nil { + t.Fatal(err) + } + if _, err := rc.readChunkAt(context.Background(), stream, buf, "chunk0", nil, false, 16<<10, chunkSize, false); err != nil { + t.Fatal(err) + } + if got := atomic.LoadInt32(&fetches); got != 1 { + t.Errorf("chunk0 fetched %d times, want 1", got) + } +} + +// Once pinned chunks fill the limit on their own, the oldest is evicted even +// while a download runs, so abandoned pins cannot grow the cache past it. +func TestChunkReadAtPinnedEvictionFallsBackWhilePrefetchRuns(t *testing.T) { + const chunkSize = 64 << 10 + var fetches int32 + release := make(chan struct{}) + rc := newReaderCacheWithPrefetch(2, release, &fetches) + defer rc.destroy() + defer close(release) + + buf := make([]byte, 16<<10) + if _, err := rc.readChunkAt(context.Background(), &chunkStream{}, buf, "chunk0", nil, false, 0, chunkSize, false); err != nil { + t.Fatal(err) + } + startPrefetch(rc, chunkSize) + if _, err := rc.readChunkAt(context.Background(), &chunkStream{}, buf, "chunk1", nil, false, 0, chunkSize, false); err != nil { + t.Fatal(err) + } + if !isRetained(rc, "chunk0") { + t.Fatal("a pinned chunk was evicted while pinned chunks did not fill the limit") + } + + if _, err := rc.readChunkAt(context.Background(), &chunkStream{}, buf, "chunk2", nil, false, 0, chunkSize, false); err != nil { + t.Fatal(err) + } + if isRetained(rc, "chunk0") { + t.Fatal("oldest pinned downloader was not evicted once pinned ones filled the limit") + } + for _, fileId := range []string{"chunk1", "chunk2", "prefetched"} { + if !isRetained(rc, fileId) { + t.Fatalf("%s missing after pinned fallback eviction", fileId) + } + } +} + +// The budget analog: a running download no stream is in holds the rest of the +// budget, so a stream's chunk is not evicted to make room next to it. +func TestChunkReadAtPinnedChunkSurvivesARunningPrefetchInTheBudget(t *testing.T) { + const chunkSize = 64 << 10 + var fetches int32 + release := make(chan struct{}) + budget := NewReaderCacheBudget(int64(2 * mem.AllocationSize(chunkSize))) + rc := newReaderCacheWithPrefetch(8, release, &fetches, budget) + defer rc.destroy() + defer close(release) + + stream := &chunkStream{} + buf := make([]byte, 16<<10) + if _, err := rc.readChunkAt(context.Background(), stream, buf, "chunk0", nil, false, 0, chunkSize, false); err != nil { + t.Fatal(err) + } + startPrefetch(rc, chunkSize) + + read := waitForBudgetWaiter(t, func() error { + _, err := rc.ReadChunkAt(context.Background(), buf, "chunk1", nil, false, 0, chunkSize, false) + return err + }) + if _, err := rc.readChunkAt(context.Background(), stream, make([]byte, 16<<10), "chunk0", nil, false, 16<<10, chunkSize, false); err != nil { + t.Fatal(err) + } + if got := atomic.LoadInt32(&fetches); got != 1 { + t.Errorf("chunk0 fetched %d times, want 1", got) + } + release <- struct{}{} + if err := <-read; err != nil { + t.Fatal(err) + } +} + +// A stream that leaves its chunk before the end frees that chunk's slot, so +// the read it leaves for doesn't evict another stream's chunk. +func TestChunkReadAtLeavingStreamKeepsAnotherStreamsChunk(t *testing.T) { + const chunkSize = 64 << 10 + var fetches int32 + rc := NewReaderCache(2, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) { + return []string{"unused"}, nil + }, nil) + defer rc.destroy() + rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, fileId string, _ util_http.RefreshUrlsFunc) (int, error) { + if fileId == "chunk1" { + atomic.AddInt32(&fetches, 1) + } + return len(buffer), nil + } + + a, b := &chunkStream{}, &chunkStream{} + buf := make([]byte, 16<<10) + if _, err := rc.readChunkAt(context.Background(), b, buf, "chunk1", nil, false, 0, chunkSize, false); err != nil { + t.Fatal(err) + } + if _, err := rc.readChunkAt(context.Background(), a, buf, "chunk0", nil, false, 0, chunkSize, false); err != nil { + t.Fatal(err) + } + if _, err := rc.readChunkAt(context.Background(), a, buf, "chunk2", nil, false, 0, chunkSize, false); err != nil { + t.Fatal(err) + } + if _, err := rc.readChunkAt(context.Background(), b, buf, "chunk1", nil, false, 16<<10, chunkSize, false); err != nil { + t.Fatal(err) + } + if got := atomic.LoadInt32(&fetches); got != 1 { + t.Errorf("chunk1 fetched %d times, want 1", got) + } + if isRetained(rc, "chunk0") { + t.Error("the chunk stream a left is still cached") + } +} + +// A stream reaching a running download can leave pinned chunks filling the +// budget, so a read waiting for that download evicts the oldest pinned chunk +// at once instead. +func TestChunkReadAtBudgetWaitWakesWhenAStreamReachesARunningDownload(t *testing.T) { + const chunkSize = 64 << 10 + var fetches int32 + release := make(chan struct{}) + budget := NewReaderCacheBudget(int64(2 * mem.AllocationSize(chunkSize))) + rc := newReaderCacheWithPrefetch(8, release, &fetches, budget) + defer rc.destroy() + defer close(release) + + if _, err := rc.readChunkAt(context.Background(), &chunkStream{}, make([]byte, 16<<10), "chunk0", nil, false, 0, chunkSize, false); err != nil { + t.Fatal(err) + } + startPrefetch(rc, chunkSize) + read := waitForBudgetWaiter(t, func() error { + _, err := rc.ReadChunkAt(context.Background(), make([]byte, 16<<10), "chunk1", nil, false, 0, chunkSize, false) + return err + }) + go func() { + _, _ = rc.readChunkAt(context.Background(), &chunkStream{}, make([]byte, 16<<10), "prefetched", nil, false, 0, chunkSize, false) + }() + + select { + case err := <-read: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("the read kept waiting for the running download after a stream reached it") + } +} + +// A read across a chunk boundary moves the stream to the chunk it ends in, so +// that chunk keeps its slot while reads without a stream fill the cache. +func TestChunkReadAtBoundaryReadMovesTheStream(t *testing.T) { + const chunkSize = 64 << 10 + // past the mock chunk cache's cutoff, so chunks don't land in it + const base = 2 << 20 + rc := NewReaderCache(2, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) { + return []string{"unused"}, nil + }, nil) + defer rc.destroy() + fetches := fetchRecorder(rc) + reader := NewChunkReaderAtFromClient(context.Background(), rc, sequentialChunkViews(base, chunkSize, 3), base+3*chunkSize, 0) + defer reader.ReleaseStream() + + if _, err := reader.ReadAt(make([]byte, 56<<10), base); err != nil { + t.Fatal(err) + } + if _, err := reader.ReadAt(make([]byte, 16<<10), base+56<<10); err != nil { + t.Fatal(err) + } + if isRetained(rc, "chunk0") { + t.Error("the chunk the stream finished is still cached") + } + for _, fileId := range []string{"filler0", "filler1"} { + if _, err := rc.ReadChunkAt(context.Background(), make([]byte, 1), fileId, nil, false, 0, chunkSize, false); err != nil { + t.Fatal(err) + } + } + if _, err := reader.ReadAt(make([]byte, 16<<10), base+72<<10); err != nil { + t.Fatal(err) + } + if n := countFetches(fetches, "chunk1"); n != 1 { + t.Errorf("chunk1 fetched %d times, want 1", n) + } +} + +func sequentialChunkViews(base int64, chunkSize, count int) *IntervalList[*ChunkView] { + views := NewIntervalList[*ChunkView]() + for i := 0; i < count; i++ { + views.AppendInterval(&Interval[*ChunkView]{ + StartOffset: base + int64(i*chunkSize), + StopOffset: base + int64((i+1)*chunkSize), + Value: &ChunkView{FileId: fmt.Sprintf("chunk%d", i), ViewSize: uint64(chunkSize), ViewOffset: base + int64(i*chunkSize), ChunkSize: uint64(chunkSize)}, + }) + } + return views +} + +func countFetches(fetches *[]recordedFetch, fileId string) (n int) { + for _, f := range *fetches { + if f.fileId == fileId { + n++ + } + } + return n +} + +// A read across a chunk boundary moves the stream when it reaches the last +// chunk, not when it ends, so a later read in another chunk that ends first +// keeps the stream, and its chunk stays cached. +func TestChunkReadAtBoundaryReadKeepsALaterReadsPosition(t *testing.T) { + const chunkSize = 64 << 10 + const base = 2 << 20 + for name, size := range map[string]int{"stays": 16 << 10, "finishes": 8<<10 + chunkSize} { + t.Run(name, func(t *testing.T) { + rc := NewReaderCache(64, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) { + return []string{"unused"}, nil + }, nil) + defer rc.destroy() + var mu sync.Mutex + fetches := map[string]int{} + var once, releaseOnce sync.Once + started, release := make(chan struct{}), make(chan struct{}) + defer releaseOnce.Do(func() { close(release) }) + rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, fileId string, _ util_http.RefreshUrlsFunc) (int, error) { + mu.Lock() + fetches[fileId]++ + mu.Unlock() + if fileId == "chunk1" { + once.Do(func() { close(started) }) + <-release + } + return len(buffer), nil + } + reader := NewChunkReaderAtFromClient(context.Background(), rc, sequentialChunkViews(base, chunkSize, 3), base+3*chunkSize, 0) + defer reader.ReleaseStream() + + if _, err := reader.ReadAt(make([]byte, 56<<10), base); err != nil { + t.Fatal(err) + } + boundary := make(chan error, 1) + go func() { + _, err := reader.ReadAt(make([]byte, size), base+56<<10) + boundary <- err + }() + <-started + if _, err := reader.ReadAt(make([]byte, 16<<10), base+2*chunkSize); err != nil { + t.Fatal(err) + } + releaseOnce.Do(func() { close(release) }) + if err := <-boundary; err != nil { + t.Fatal(err) + } + if _, err := reader.ReadAt(make([]byte, 16<<10), base+2*chunkSize+16<<10); err != nil { + t.Fatal(err) + } + mu.Lock() + defer mu.Unlock() + if fetches["chunk2"] != 1 { + t.Errorf("chunk2 fetched %d times, want 1 (fetches %v)", fetches["chunk2"], fetches) + } + }) + } +} + +// A read across a chunk boundary leaves the stream's chunk before it makes +// room for the chunks it reads, as a read of one chunk does, so with pinned +// chunks at the limit it doesn't evict another stream's chunk. It still reads +// the tail of the chunk it leaves from the cache. +func TestChunkReadAtBoundaryReadLeavesItsChunkBeforeMakingRoom(t *testing.T) { + const chunkSize = 64 << 10 + const base = 2 << 20 + tests := map[string]struct { + offset int64 + size int + }{ + "from its chunk": {base + 56<<10, 16 << 10}, + // more chunks than run at once, so the last one starts after others + // made room, and the last one is read as a range, so the stream is in + // no chunk while they do + "past its chunk": {base + chunkSize + 56<<10, 16<<10 + 3*chunkSize}, + } + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + rc := NewReaderCache(2, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) { + return []string{"unused"}, nil + }, nil) + defer rc.destroy() + fetches := fetchRecorder(rc) + other := &chunkStream{} + if _, err := rc.readChunkAt(context.Background(), other, make([]byte, 1), "other", nil, false, 0, chunkSize, false); err != nil { + t.Fatal(err) + } + views := sequentialChunkViews(base, chunkSize, 5) + views.AppendInterval(&Interval[*ChunkView]{ + StartOffset: base + 5*chunkSize, + StopOffset: base + 5*chunkSize + 8<<10, + Value: &ChunkView{FileId: "chunk5", ViewSize: 8 << 10, ViewOffset: base + 5*chunkSize, ChunkSize: chunkSize}, + }) + reader := NewChunkReaderAtFromClient(context.Background(), rc, views, base+5*chunkSize+8<<10, 0) + defer reader.ReleaseStream() + + if _, err := reader.ReadAt(make([]byte, 56<<10), base); err != nil { + t.Fatal(err) + } + if _, err := reader.ReadAt(make([]byte, tc.size), tc.offset); err != nil && err != io.EOF { + t.Fatal(err) + } + if _, err := rc.readChunkAt(context.Background(), other, make([]byte, 1), "other", nil, false, 1, chunkSize, false); err != nil { + t.Fatal(err) + } + for _, fileId := range []string{"other", "chunk0"} { + if n := countFetches(fetches, fileId); n != 1 { + t.Errorf("%s fetched %d times, want 1", fileId, n) + } + } + }) + } +} + +func chunkViewList(chunkViews ...*ChunkView) *IntervalList[*ChunkView] { + views := NewIntervalList[*ChunkView]() + for _, v := range chunkViews { + views.AppendInterval(&Interval[*ChunkView]{StartOffset: v.ViewOffset, StopOffset: v.ViewOffset + int64(v.ViewSize), Value: v}) + } + return views +} + +// A compressed chunk written over in the middle shows up as two views of it, +// and a read across both that starts in it, where the stream is, downloads it +// once although the stream leaves it for the last chunk. +func TestChunkReadAtBoundaryReadHoldsEveryViewOfTheChunkItLeaves(t *testing.T) { + const chunkSize = 64 << 10 + const base = 2 << 20 + rc := newStreamTestReaderCache(newMockChunkCacheForReaderCache()) + defer rc.destroy() + fetches := fetchRecorder(rc) + views := chunkViewList( + &ChunkView{FileId: "A", IsGzipped: true, ViewSize: 16 << 10, ViewOffset: base, ChunkSize: chunkSize}, + &ChunkView{FileId: "B", ViewSize: 16 << 10, ViewOffset: base + 16<<10, ChunkSize: 16 << 10}, + &ChunkView{FileId: "A", IsGzipped: true, OffsetInChunk: 32 << 10, ViewSize: 32 << 10, ViewOffset: base + 32<<10, ChunkSize: chunkSize}, + &ChunkView{FileId: "C", ViewSize: chunkSize, ViewOffset: base + chunkSize, ChunkSize: chunkSize}, + ) + reader := NewChunkReaderAtFromClient(context.Background(), rc, views, base+2*chunkSize, 0) + defer reader.ReleaseStream() + + if _, err := reader.ReadAt(make([]byte, 8<<10), base); err != nil { + t.Fatal(err) + } + buf := make([]byte, chunkSize) + if _, err := reader.ReadAt(buf, base+8<<10); err != nil { + t.Fatal(err) + } + if n := countFetches(fetches, "A"); n != 1 { + t.Errorf("A fetched %d times, want 1", n) + } + for i, want := range map[int]byte{0: 'A', 8 << 10: 'B', 24 << 10: 'A', 56 << 10: 'C'} { + if buf[i] != want { + t.Errorf("byte %d is %q, want %q", i, buf[i], want) + } + } +} + +// The views of the chunk the stream leaves don't queue for a slot, as evicting +// that chunk waits for them. With more chunks than run at once ahead of one of +// them and the budget full of that chunk, the reads making room would otherwise +// wait for a view that can't start. +func TestChunkReadAtBoundaryReadDoesNotQueueTheChunkItLeaves(t *testing.T) { + const chunkSize = 64 << 10 + const base = 2 << 20 + budget := NewReaderCacheBudget(int64(mem.AllocationSize(chunkSize))) + rc := NewReaderCache(64, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) { + return []string{"unused"}, nil + }, nil, budget) + fetchRecorder(rc) + list := []*ChunkView{{FileId: "A", IsGzipped: true, ViewSize: 16 << 10, ViewOffset: base, ChunkSize: chunkSize}} + end := int64(base + 16<<10) + for i := 0; i <= minReadConcurrency; i++ { + list = append(list, &ChunkView{FileId: fmt.Sprintf("B%d", i), ViewSize: chunkSize, ViewOffset: end, ChunkSize: chunkSize}) + end += chunkSize + } + list = append(list, + &ChunkView{FileId: "A", IsGzipped: true, OffsetInChunk: 16 << 10, ViewSize: 48 << 10, ViewOffset: end, ChunkSize: chunkSize}, + &ChunkView{FileId: "C", ViewSize: chunkSize, ViewOffset: end + 48<<10, ChunkSize: chunkSize}, + ) + end += 48<<10 + 8<<10 + reader := NewChunkReaderAtFromClient(context.Background(), rc, chunkViewList(list...), end+chunkSize, 0) + + if _, err := reader.ReadAt(make([]byte, 8<<10), base); err != nil { + t.Fatal(err) + } + read := make(chan error, 1) + go func() { + _, err := reader.ReadAt(make([]byte, end-(base+8<<10)), base+8<<10) + read <- err + }() + select { + case err := <-read: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + // no cleanup: destroy would wait for the stuck downloads + t.Fatal("the read waited for a view of the chunk it left that couldn't start") + } + reader.ReleaseStream() + rc.destroy() +} + +// A read across a chunk boundary starts its other chunks while the chunk the +// stream leaves still downloads, here for a concurrent read on the same reader, +// even with as many views of that chunk as chunks run at once. +func TestChunkReadAtBoundaryReadDoesNotWaitForTheChunkItLeaves(t *testing.T) { + const chunkSize = 64 << 10 + const base = 2 << 20 + rc := newStreamTestReaderCache(newMockChunkCacheForReaderCache()) + defer rc.destroy() + gate := make(chan struct{}) + var gateOnce sync.Once + defer gateOnce.Do(func() { close(gate) }) + chunk1Started := make(chan struct{}) + rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, fileId string, _ util_http.RefreshUrlsFunc) (int, error) { + switch fileId { + case "chunk0": + <-gate + case "chunk1": + close(chunk1Started) + } + return len(buffer), nil + } + var list []*ChunkView + for i := int64(0); i < minReadConcurrency; i++ { + list = append(list, + &ChunkView{FileId: "chunk0", IsGzipped: true, OffsetInChunk: i * 16 << 10, ViewSize: 8 << 10, ViewOffset: base + i*16<<10, ChunkSize: chunkSize}, + &ChunkView{FileId: fmt.Sprintf("gap%d", i), ViewSize: 8 << 10, ViewOffset: base + i*16<<10 + 8<<10, ChunkSize: 8 << 10}, + ) + } + list = append(list, &ChunkView{FileId: "chunk1", ViewSize: chunkSize, ViewOffset: base + chunkSize, ChunkSize: chunkSize}) + reader := NewChunkReaderAtFromClient(context.Background(), rc, chunkViewList(list...), base+2*chunkSize, 0) + defer reader.ReleaseStream() + + head := make(chan error, 1) + go func() { + _, err := reader.ReadAt(make([]byte, 8<<10), base) + head <- err + }() + for deadline := time.Now().Add(5 * time.Second); !reader.stream.in("chunk0"); time.Sleep(time.Millisecond) { + select { + case err := <-head: + t.Fatalf("the head read finished before the stream entered chunk0: %v", err) + default: + } + if time.Now().After(deadline) { + t.Fatal("the stream never entered chunk0") + } + } + boundary := make(chan error, 1) + go func() { + _, err := reader.ReadAt(make([]byte, chunkSize+8<<10), base) + boundary <- err + }() + select { + case <-chunk1Started: + case <-time.After(5 * time.Second): + t.Error("chunk1 was not fetched while chunk0 was still downloading") + } + gateOnce.Do(func() { close(gate) }) + for _, done := range []chan error{head, boundary} { + if err := <-done; err != nil { + t.Fatal(err) + } + } +} + +// After a read across a chunk boundary the stream stays out of a last chunk it +// finished or read as a range, as after a read of that chunk alone, so it +// doesn't keep that chunk cached once another stream leaves it. +func TestChunkReadAtBoundaryReadLeavesAFinishedOrRangeChunk(t *testing.T) { + const chunkSize = 64 << 10 + const base = 2 << 20 + for name, lastView := range map[string]int{"finished": chunkSize, "range": 8 << 10} { + t.Run(name, func(t *testing.T) { + rc := newStreamTestReaderCache(newMockChunkCacheForReaderCache()) + defer rc.destroy() + views := NewIntervalList[*ChunkView]() + views.AppendInterval(&Interval[*ChunkView]{ + StartOffset: base, + StopOffset: base + chunkSize, + Value: &ChunkView{FileId: "chunk0", ViewSize: chunkSize, ViewOffset: base, ChunkSize: chunkSize}, + }) + views.AppendInterval(&Interval[*ChunkView]{ + StartOffset: base + chunkSize, + StopOffset: base + chunkSize + int64(lastView), + Value: &ChunkView{FileId: "chunk1", ViewSize: uint64(lastView), ViewOffset: base + chunkSize, ChunkSize: chunkSize}, + }) + other := &chunkStream{} + if _, err := rc.readChunkAt(context.Background(), other, make([]byte, 1), "chunk1", nil, false, 0, chunkSize, false); err != nil { + t.Fatal(err) + } + reader := NewChunkReaderAtFromClient(context.Background(), rc, views, base+chunkSize+int64(lastView), 0) + defer reader.ReleaseStream() + + if _, err := reader.ReadAt(make([]byte, 8<<10+lastView), base+chunkSize-8<<10); err != nil && err != io.EOF { + t.Fatal(err) + } + rc.releaseStream(other) + if isRetained(rc, "chunk1") { + t.Error("the stream kept a chunk it is done with cached") + } + }) + } +} diff --git a/weed/filer/reader_cache.go b/weed/filer/reader_cache.go index 063f81ba46..885ee10c60 100644 --- a/weed/filer/reader_cache.go +++ b/weed/filer/reader_cache.go @@ -172,6 +172,9 @@ func (rc *ReaderCache) ReadChunkAt(ctx context.Context, buffer []byte, fileId st } func (rc *ReaderCache) readChunkAt(ctx context.Context, stream *chunkStream, buffer []byte, fileId string, cipherKey []byte, isGzipped bool, offset int64, chunkSize int, shouldCache bool) (int, error) { + // A stream reading another chunk has left its own. It is unpinned before + // this read makes room, or its pin would count against another stream's chunk. + rc.unpin(stream.leave(fileId)) retry: rc.RLock() if cacher, found := rc.downloaders[fileId]; found { @@ -223,16 +226,24 @@ retry: } // clean up old downloaders; prefer one no stream is positioned in, but - // fall back to a pinned one so abandoned pins cannot bypass the limit + // fall back to a pinned one once pinned ones alone fill the limit, so + // abandoned pins cannot bypass it. Below that, a download still running + // holds the rest of the slots and is evicted once it finishes; going over + // the limit until then, as when every download is running, keeps a + // stream's buffer. if len(rc.downloaders) >= rc.limit { oldestFid, oldest := "", int64(0) - pinnedFid, pinnedOldest := "", int64(0) + pinnedFid, pinnedOldest, pinned := "", int64(0), 0 for fid, downloader := range rc.downloaders { + isPinned := atomic.LoadInt32(&downloader.pins) > 0 + if isPinned { + pinned++ + } completed := atomic.LoadInt64(&downloader.completed) if completed == 0 { continue } - if atomic.LoadInt32(&downloader.pins) == 0 { + if !isPinned { if oldestFid == "" || completed < oldest { oldestFid, oldest = fid, completed } @@ -240,7 +251,7 @@ retry: pinnedFid, pinnedOldest = fid, completed } } - if oldestFid == "" { + if oldestFid == "" && pinned >= rc.limit { oldestFid = pinnedFid } if oldestFid != "" { @@ -288,12 +299,37 @@ func (stream *chunkStream) pin(cacher *SingleChunkCacher) (previous *SingleChunk if stream.cacher == cacher { return nil } - atomic.AddInt32(&cacher.pins, 1) + if atomic.AddInt32(&cacher.pins, 1) == 1 { + cacher.parent.budget.pinsChanged(cacher) + } previous = stream.cacher stream.cacher = cacher return previous } +// leave detaches the stream from its chunk if that isn't fileId and returns +// the chunk for the caller to unpin. +func (stream *chunkStream) leave(fileId string) (previous *SingleChunkCacher) { + if stream == nil { + return nil + } + stream.mu.Lock() + defer stream.mu.Unlock() + if stream.cacher == nil || stream.cacher.chunkFileId == fileId { + return nil + } + previous = stream.cacher + stream.cacher = nil + return previous +} + +// current returns the chunk the stream is positioned in. +func (stream *chunkStream) current() *SingleChunkCacher { + stream.mu.Lock() + defer stream.mu.Unlock() + return stream.cacher +} + // detach unpins the stream from its chunk and returns that chunk for the // caller to unpin. A non-nil expected cacher makes the detach conditional on // the stream still being positioned in it. @@ -320,6 +356,21 @@ func (rc *ReaderCache) releaseIfFinished(stream *chunkStream, cacher *SingleChun rc.unpin(stream.detach(cacher)) } +// hold registers a read on the download a stream is positioned in, as +// readChunkAt does, if it is still in the map, so it outlives the stream +// leaving it. The caller must read it once with its readChunkAt, which +// releases the read. +func (rc *ReaderCache) hold(downloader *SingleChunkCacher) bool { + rc.RLock() + defer rc.RUnlock() + if rc.downloaders[downloader.chunkFileId] != downloader || downloader.hasCompletedError() { + return false + } + downloader.wg.Add(1) + atomic.AddInt32(&downloader.readers, 1) + return true +} + // releaseStream unpins whatever chunk the stream is positioned in. func (rc *ReaderCache) releaseStream(stream *chunkStream) { rc.unpin(stream.detach(nil)) @@ -334,6 +385,7 @@ func (rc *ReaderCache) unpin(downloader *SingleChunkCacher) { } if atomic.AddInt32(&downloader.pins, -1) == 0 { atomic.StoreInt32(&downloader.left, 1) + rc.budget.pinsChanged(downloader) } rc.removeConsumed(downloader) } diff --git a/weed/filer/reader_cache_budget.go b/weed/filer/reader_cache_budget.go index 41bd0988c0..209379cead 100644 --- a/weed/filer/reader_cache_budget.go +++ b/weed/filer/reader_cache_budget.go @@ -54,11 +54,18 @@ func (b *ReaderCacheBudget) reserve(s *SingleChunkCacher) error { if size <= b.limit-b.used { b.used += size b.reservations[s] = size + if atomic.LoadInt32(&s.pins) > 0 { + // a stream pins its download before it reserves, so pinsChanged + // missed it, and pinned chunks now hold more of the budget + b.signalLocked() + } b.Unlock() return nil } - // Prefer evicting an idle chunk no stream is positioned in; fall back - // to the oldest pinned one so abandoned pins cannot block the budget. + // Prefer evicting an idle chunk no stream is positioned in. Fall back + // to the oldest pinned one once pinned chunks alone leave no room, so + // abandoned pins cannot block the budget. Below that, a download no + // stream is in holds the rest and becomes idle when it finishes. var victim *SingleChunkCacher var entry *list.Element pinnedVictim := false @@ -74,6 +81,9 @@ func (b *ReaderCacheBudget) reserve(s *SingleChunkCacher) error { pinnedVictim = true } } + if pinnedVictim && size <= b.limit-b.pinnedLocked() { + entry = nil + } if entry != nil { b.idle.Remove(entry) delete(b.idleEntries, victim) @@ -85,6 +95,7 @@ func (b *ReaderCacheBudget) reserve(s *SingleChunkCacher) error { b.Lock() if _, ok := b.reservations[victim]; ok && b.idleEntries[victim] == nil { b.idleEntries[victim] = b.idle.PushBack(victim) + b.signalLocked() } b.Unlock() } @@ -100,6 +111,16 @@ func (b *ReaderCacheBudget) reserve(s *SingleChunkCacher) error { } } +// pinnedLocked sums the reservations of chunks a stream is positioned in. +func (b *ReaderCacheBudget) pinnedLocked() (n int64) { + for s, size := range b.reservations { + if atomic.LoadInt32(&s.pins) > 0 { + n += size + } + } + return n +} + // canFit reports whether a whole-chunk buffer of this size can ever be // reserved. A chunk bigger than the budget cannot be read through the // whole-chunk path at all, so callers must fall back to range fetches. @@ -147,6 +168,7 @@ func (b *ReaderCacheBudget) TryReserveScratch(size int) bool { b.Lock() if _, ok := b.reservations[victim]; ok && b.idleEntries[victim] == nil { b.idleEntries[victim] = b.idle.PushBack(victim) + b.signalLocked() } b.Unlock() return false @@ -162,8 +184,7 @@ func (b *ReaderCacheBudget) ReleaseScratch(size int) { b.Lock() defer b.Unlock() b.used -= int64(mem.AllocationSize(size)) - close(b.changed) - b.changed = make(chan struct{}) + b.signalLocked() } func (b *ReaderCacheBudget) complete(s *SingleChunkCacher) { @@ -174,8 +195,7 @@ func (b *ReaderCacheBudget) complete(s *SingleChunkCacher) { defer b.Unlock() if _, found := b.reservations[s]; found && b.idleEntries[s] == nil { b.idleEntries[s] = b.idle.PushBack(s) - close(b.changed) - b.changed = make(chan struct{}) + b.signalLocked() } } @@ -192,7 +212,26 @@ func (b *ReaderCacheBudget) release(s *SingleChunkCacher) { b.idle.Remove(entry) delete(b.idleEntries, s) } - close(b.changed) - b.changed = make(chan struct{}) + b.signalLocked() } } + +// pinsChanged wakes reservations waiting for room when a stream first enters +// s or the last one leaves it. Whether they wait or evict a pinned chunk +// depends on which chunks have a stream in them, and a chunk out of the map +// isn't released when its last stream leaves. +func (b *ReaderCacheBudget) pinsChanged(s *SingleChunkCacher) { + if b == nil { + return + } + b.Lock() + defer b.Unlock() + if _, found := b.reservations[s]; found { + b.signalLocked() + } +} + +func (b *ReaderCacheBudget) signalLocked() { + close(b.changed) + b.changed = make(chan struct{}) +} diff --git a/weed/filer/reader_cache_destroy_budget_test.go b/weed/filer/reader_cache_destroy_budget_test.go index 4d529ce872..76cc12586e 100644 --- a/weed/filer/reader_cache_destroy_budget_test.go +++ b/weed/filer/reader_cache_destroy_budget_test.go @@ -5,13 +5,16 @@ import ( "errors" "math/rand" "os" + "runtime" "runtime/pprof" + "strings" "sync" "sync/atomic" "testing" "time" util_http "github.com/seaweedfs/seaweedfs/weed/util/http" + "github.com/seaweedfs/seaweedfs/weed/util/mem" ) // budgetTestViews returns one whole-chunk view per file id. The views lie past @@ -26,6 +29,45 @@ func budgetTestViews(chunkSize int, fids ...string) *Interval[*ChunkView] { return views } +// waitForBudgetWaiter runs f in a goroutine and returns once that goroutine, +// or a download it started, waits for room in the budget, failing if f +// finished instead. The returned channel reports what f returns. +func waitForBudgetWaiter(t *testing.T, f func() error) chan error { + t.Helper() + done := make(chan error, 1) + started := make(chan string, 1) + go func() { + buf := make([]byte, 64) + header := strings.TrimPrefix(string(buf[:runtime.Stack(buf, false)]), "goroutine ") + id, _, _ := strings.Cut(header, " ") + started <- id + done <- f() + }() + id := <-started + buf := make([]byte, 1<<20) + for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(time.Millisecond) { + select { + case err := <-done: + t.Fatalf("finished without waiting for room in the budget: %v", err) + default: + } + n := runtime.Stack(buf, true) + for n == len(buf) { + buf = make([]byte, 2*len(buf)) + n = runtime.Stack(buf, true) + } + for _, g := range strings.Split(string(buf[:n]), "\n\n") { + header, _, _ := strings.Cut(g, "\n") + ours := strings.HasPrefix(header, "goroutine "+id+" ") || strings.Contains(g, " in goroutine "+id+"\n") + if ours && strings.Contains(header, "[select") && strings.Contains(g, "(*ReaderCacheBudget).reserve(") { + return done + } + } + } + t.Fatal("the reservation never waited for room in the budget") + return nil +} + // waitBudgetDrained waits until the budget holds nothing. A chunk dropped while // its download still runs is destroyed once that download gives up. func waitBudgetDrained(t *testing.T, b *ReaderCacheBudget) { @@ -386,3 +428,86 @@ func TestReaderCacheBudgetStreamsStress(t *testing.T) { waitBudgetDrained(t, budget) t.Logf("%d reads with data", reads.Load()) } + +// A reservation waiting for room wakes when the last stream leaves an idle +// chunk, also one already out of the map, which leaving doesn't release. +func TestReaderCacheBudgetWaitWakesWhenAStreamLeaves(t *testing.T) { + const chunkSize = 64 << 10 + budget := NewReaderCacheBudget(int64(2 * mem.AllocationSize(chunkSize))) + rc := NewReaderCache(8, newMockChunkCacheForReaderCache(), nil, nil, budget) + defer rc.destroy() + + left := newSingleChunkCacher(rc, "left", nil, false, chunkSize, false) + running := newSingleChunkCacher(rc, "running", nil, false, chunkSize, false) + for _, s := range []*SingleChunkCacher{left, running} { + if err := budget.reserve(s); err != nil { + t.Fatal(err) + } + } + // left has finished and has one stream in it but isn't in the map; running + // holds the rest of the budget and doesn't finish during the test + budget.complete(left) + atomic.StoreInt32(&left.pins, 1) + + waiting := newSingleChunkCacher(rc, "waiting", nil, false, chunkSize, false) + t.Cleanup(waiting.cancel) + reserved := waitForBudgetWaiter(t, func() error { return budget.reserve(waiting) }) + // a stream reaching running takes away what the reservation waits for + atomic.StoreInt32(&running.pins, 1) + rc.unpin(left) + + select { + case err := <-reserved: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("the reservation kept waiting after the last stream left an idle chunk") + } + budget.release(running) + budget.release(waiting) +} + +// A reservation waiting for room wakes when a download a stream is in +// reserves, as pinned chunks then hold more of the budget. A stream pins its +// download before the download reserves. +func TestReaderCacheBudgetWaitWakesWhenAPinnedDownloadReserves(t *testing.T) { + const big, small = 32 << 10, 16 << 10 + budget := NewReaderCacheBudget(2 * big) + rc := NewReaderCache(8, newMockChunkCacheForReaderCache(), nil, nil, budget) + defer rc.destroy() + + // idle has finished and has a stream in it, and running holds part of the + // rest and doesn't finish during the test + idle := newSingleChunkCacher(rc, "idle", nil, false, big, false) + running := newSingleChunkCacher(rc, "running", nil, false, small, false) + for _, s := range []*SingleChunkCacher{idle, running} { + if err := budget.reserve(s); err != nil { + t.Fatal(err) + } + } + budget.complete(idle) + atomic.StoreInt32(&idle.pins, 1) + + waiting := newSingleChunkCacher(rc, "waiting", nil, false, big, false) + t.Cleanup(waiting.cancel) + reserved := waitForBudgetWaiter(t, func() error { return budget.reserve(waiting) }) + // with the rest pinned too, the reservation can only get room from idle + pinned := newSingleChunkCacher(rc, "pinned", nil, false, small, false) + atomic.StoreInt32(&pinned.pins, 1) + if err := budget.reserve(pinned); err != nil { + t.Fatal(err) + } + + select { + case err := <-reserved: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("the reservation kept waiting after a pinned download took the rest of the budget") + } + for _, s := range []*SingleChunkCacher{running, pinned, waiting} { + budget.release(s) + } +}