diff --git a/weed/filer/reader_at.go b/weed/filer/reader_at.go index cb52d9177e..0bd4318a0b 100644 --- a/weed/filer/reader_at.go +++ b/weed/filer/reader_at.go @@ -285,21 +285,14 @@ func (c *ChunkReadAt) doReadAt(ctx context.Context, p []byte, offset int64) (n i // 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. + // read holds, and one goroutine started before the others reads them, so + // it never waits for a slot, as evicting the chunk 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 { @@ -319,22 +312,24 @@ func (c *ChunkReadAt) doReadAt(ctx context.Context, p []byte, offset int64) (n i if concurrency > len(tasks) { concurrency = len(tasks) } - slots := make(chan struct{}, concurrency) + g.SetLimit(concurrency) - for _, task := range ordered { + if len(held) > 0 { + g.Go(func() error { + return c.readHeld(gCtx, p, tasks, held) + }) + } + for _, task := range tasks { + if held[task] != nil { + continue + } 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, stream, held[task]) + copied, readErr := c.readChunkSliceAtForParallel(gCtx, p[task.bufferStart:task.bufferEnd], task.chunk, task.chunkOffset, stream) task.bytesRead = copied task.modifiedTsNs = task.chunk.ModifiedTsNs return readErr @@ -439,14 +434,8 @@ 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) -// 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 - } - } +// A non-nil stream moves to the chunk as in readChunkSliceAt. +func (c *ChunkReadAt) readChunkSliceAtForParallel(ctx context.Context, buffer []byte, chunkView *ChunkView, offset uint64, stream *chunkStream) (n int, err error) { if c.readsRange(chunkView) { c.readerCache.releaseStream(stream) n, err = c.readerCache.chunkCache.ReadChunkAt(buffer, chunkView.FileId, offset) @@ -459,6 +448,39 @@ func (c *ChunkReadAt) readChunkSliceAtForParallel(ctx context.Context, buffer [] return c.readerCache.readChunkAt(ctx, stream, buffer, chunkView.FileId, chunkView.CipherKey, chunkView.IsGzipped, int64(offset), int(chunkView.ChunkSize), shouldCache) } +// readHeld reads the views of the chunk the stream left from the download held +// for each, one after another, as they all wait for that download. Every hold +// is released before a view the download can't serve falls back to a read of +// its own, as that read can make room and evicting the chunk waits for the holds. +func (c *ChunkReadAt) readHeld(ctx context.Context, p []byte, tasks []*chunkReadTask, held map[*chunkReadTask]*SingleChunkCacher) (err error) { + var unserved []*chunkReadTask + for _, task := range tasks { + cacher := held[task] + if cacher == nil { + continue + } + n, readErr := cacher.readChunkAt(ctx, p[task.bufferStart:task.bufferEnd], int64(task.chunkOffset)) + task.bytesRead = n + task.modifiedTsNs = task.chunk.ModifiedTsNs + if readErr != nil { + if err == nil { + err = readErr + } + } else if n == 0 { + unserved = append(unserved, task) + } + } + if err != nil { + return err + } + for _, task := range unserved { + if task.bytesRead, err = c.readChunkSliceAtForParallel(ctx, p[task.bufferStart:task.bufferEnd], task.chunk, task.chunkOffset, nil); err != nil { + return err + } + } + return nil +} + func zero(buffer []byte, start, length int64) int { if length <= 0 { return 0 diff --git a/weed/filer/reader_at_shared_test.go b/weed/filer/reader_at_shared_test.go index 26ab206a0f..b8f5c51227 100644 --- a/weed/filer/reader_at_shared_test.go +++ b/weed/filer/reader_at_shared_test.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "io" + "runtime" "sync" "sync/atomic" "testing" @@ -611,7 +612,8 @@ func newReaderCacheWithPrefetch(limit int, release chan struct{}, chunk0Fetches // 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) { +func startPrefetch(t *testing.T, rc *ReaderCache, chunkSize int) { + t.Helper() rc.Lock() cacher := newSingleChunkCacher(rc, "prefetched", nil, false, chunkSize, false) cacher.wg.Add(1) @@ -619,14 +621,16 @@ func startPrefetch(rc *ReaderCache, chunkSize int) { rc.Unlock() go cacher.startCaching() <-cacher.cacheStartedCh - for rc.budget != nil { + for deadline := time.Now().Add(5 * time.Second); rc.budget != nil; time.Sleep(time.Millisecond) { rc.budget.Lock() _, reserved := rc.budget.reservations[cacher] rc.budget.Unlock() if reserved { return } - time.Sleep(time.Millisecond) + if time.Now().After(deadline) { + t.Fatal("the prefetch didn't reserve its buffer") + } } } @@ -645,7 +649,7 @@ func TestChunkReadAtPinnedChunkSurvivesARunningPrefetch(t *testing.T) { if _, err := rc.readChunkAt(context.Background(), stream, buf, "chunk0", nil, false, 0, chunkSize, false); err != nil { t.Fatal(err) } - startPrefetch(rc, chunkSize) + startPrefetch(t, rc, chunkSize) if _, err := rc.ReadChunkAt(context.Background(), buf, "chunk1", nil, false, 0, chunkSize, false); err != nil { t.Fatal(err) @@ -672,7 +676,7 @@ func TestChunkReadAtPinnedEvictionFallsBackWhilePrefetchRuns(t *testing.T) { if _, err := rc.readChunkAt(context.Background(), &chunkStream{}, buf, "chunk0", nil, false, 0, chunkSize, false); err != nil { t.Fatal(err) } - startPrefetch(rc, chunkSize) + startPrefetch(t, rc, chunkSize) if _, err := rc.readChunkAt(context.Background(), &chunkStream{}, buf, "chunk1", nil, false, 0, chunkSize, false); err != nil { t.Fatal(err) } @@ -709,7 +713,7 @@ func TestChunkReadAtPinnedChunkSurvivesARunningPrefetchInTheBudget(t *testing.T) if _, err := rc.readChunkAt(context.Background(), stream, buf, "chunk0", nil, false, 0, chunkSize, false); err != nil { t.Fatal(err) } - startPrefetch(rc, chunkSize) + startPrefetch(t, rc, chunkSize) read := waitForBudgetWaiter(t, func() error { _, err := rc.ReadChunkAt(context.Background(), buf, "chunk1", nil, false, 0, chunkSize, false) @@ -780,7 +784,7 @@ func TestChunkReadAtBudgetWaitWakesWhenAStreamReachesARunningDownload(t *testing 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) + startPrefetch(t, rc, chunkSize) read := waitForBudgetWaiter(t, func() error { _, err := rc.ReadChunkAt(context.Background(), make([]byte, 16<<10), "chunk1", nil, false, 0, chunkSize, false) return err @@ -894,7 +898,11 @@ func TestChunkReadAtBoundaryReadKeepsALaterReadsPosition(t *testing.T) { _, err := reader.ReadAt(make([]byte, size), base+56<<10) boundary <- err }() - <-started + select { + case <-started: + case <-time.After(5 * time.Second): + t.Fatal("the read across the boundary didn't fetch chunk1") + } if _, err := reader.ReadAt(make([]byte, 16<<10), base+2*chunkSize); err != nil { t.Fatal(err) } @@ -1060,10 +1068,13 @@ func TestChunkReadAtBoundaryReadDoesNotQueueTheChunkItLeaves(t *testing.T) { // 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. +// even with more views of that chunk than chunks run at once, and it doesn't +// start a goroutine for each of those views. func TestChunkReadAtBoundaryReadDoesNotWaitForTheChunkItLeaves(t *testing.T) { const chunkSize = 64 << 10 const base = 2 << 20 + const views = 4 * minReadConcurrency + const step = chunkSize / views rc := newStreamTestReaderCache(newMockChunkCacheForReaderCache()) defer rc.destroy() gate := make(chan struct{}) @@ -1080,10 +1091,10 @@ func TestChunkReadAtBoundaryReadDoesNotWaitForTheChunkItLeaves(t *testing.T) { return len(buffer), nil } var list []*ChunkView - for i := int64(0); i < minReadConcurrency; i++ { + for i := int64(0); i < views; 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}, + &ChunkView{FileId: "chunk0", IsGzipped: true, OffsetInChunk: i * step, ViewSize: step / 2, ViewOffset: base + i*step, ChunkSize: chunkSize}, + &ChunkView{FileId: fmt.Sprintf("gap%d", i), ViewSize: step / 2, ViewOffset: base + i*step + step/2, ChunkSize: step / 2}, ) } list = append(list, &ChunkView{FileId: "chunk1", ViewSize: chunkSize, ViewOffset: base + chunkSize, ChunkSize: chunkSize}) @@ -1092,7 +1103,7 @@ func TestChunkReadAtBoundaryReadDoesNotWaitForTheChunkItLeaves(t *testing.T) { head := make(chan error, 1) go func() { - _, err := reader.ReadAt(make([]byte, 8<<10), base) + _, err := reader.ReadAt(make([]byte, step/2), base) head <- err }() for deadline := time.Now().Add(5 * time.Second); !reader.stream.in("chunk0"); time.Sleep(time.Millisecond) { @@ -1105,6 +1116,7 @@ func TestChunkReadAtBoundaryReadDoesNotWaitForTheChunkItLeaves(t *testing.T) { t.Fatal("the stream never entered chunk0") } } + before := runtime.NumGoroutine() boundary := make(chan error, 1) go func() { _, err := reader.ReadAt(make([]byte, chunkSize+8<<10), base) @@ -1112,6 +1124,9 @@ func TestChunkReadAtBoundaryReadDoesNotWaitForTheChunkItLeaves(t *testing.T) { }() select { case <-chunk1Started: + if started := runtime.NumGoroutine() - before; started >= views { + t.Errorf("the read runs %d goroutines with %d views of the chunk it leaves", started, views) + } case <-time.After(5 * time.Second): t.Error("chunk1 was not fetched while chunk0 was still downloading") }