mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 02:57:37 +01:00
filer: read the hard link records of a listing in batches (#13117)
* filer: read the hard link records of a listing in batches A hard-linked entry keeps its attributes and chunks in a record the file's names share, and a listing reads that record for every hard-linked entry it lists. It read them one at a time from the callback of the store's listing: a round trip to the store for each such name, each waiting for the one before, so a directory of hard-linked files listed far slower than one of as many plain files. A store may now say that it reads several KV keys in one round trip (KvBatchReader). For a listing by such a store the wrapper holds the entries back from the first hard-linked one on, up to 256 of them, reads their records together and hands them on. The caller of the listing gets the same entries in the same order, and the name of the entry it ended the listing at. TiKV implements it with the client's batch get. With the store on the client library's in-process TiKV, the records of a directory of 200 hard-linked names take one batch get instead of 200 gets. The TiKV tests run the store on that in-process TiKV, which needs pingcap/goleveldb as an indirect dependency. * filer: end a listing where its caller ended it, whatever the store met behind The store goes on past the entry its caller ends the listing at, to the entries that wait for their records with it, and may fail there. The listing then returned the store's error, though a caller handed each entry as it arrived would have stopped the store before it got that far. The listing now ends at the entry its caller ended it at, and a caller that fails among the waiting entries gets its own error, not the store's. The same holds for the step a store takes after it is told to stop, when the caller ended the listing at an entry the store had already passed. At the last entry that waited the step's error is still returned, as it is from a store that hands each entry on as it arrives. * filer: finish a hard link listing on every return of the listing The listing hands on the entries that wait from a deferred finish, so a return path that lists from elsewhere with the same callback hands them on too. The callback keeps the adjustedEntryFunc shape the prefixed listing already had. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.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:
7 files changed
+791
-9
No files matched your search
@@ -384,6 +384,7 @@ require (
|
||||
github.com/pierrre/geohash v1.0.0 // indirect
|
||||
github.com/pingcap/errors v0.11.5-0.20211224045212-9687c2b0f87c // indirect
|
||||
github.com/pingcap/failpoint v0.0.0-20220801062533-2eaa32854a6c // indirect
|
||||
github.com/pingcap/goleveldb v0.0.0-20191226122134-f82aafb29989 // indirect
|
||||
github.com/pingcap/kvproto v0.0.0-20230403051650-e166ae588106 // indirect
|
||||
github.com/pingcap/log v1.1.1-0.20221110025148-ca232912c9f3 // indirect
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
|
||||
|
||||
@@ -0,0 +1,439 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// What a listing reads the store for besides the listing itself: the shared
|
||||
// record of every hard-linked entry. A store that reads KV keys in batches is
|
||||
// asked for the records of the waiting entries together; the caller of the
|
||||
// listing must not be able to tell, except by how long it takes.
|
||||
|
||||
// rowListingStore hands over an entry of its own for each name it lists, as a
|
||||
// store that decodes rows does. It can fail a listing part of the way.
|
||||
type rowListingStore struct {
|
||||
*stubFilerStore
|
||||
failAfter int // fail the listing once it has handed over this many entries
|
||||
listErr error // with this
|
||||
// A store may take one more step after its caller ended the listing, as
|
||||
// TiKV moves its iterator on before it looks at the answer. stopErr is
|
||||
// that step failing behind the entry numbered failStopAt.
|
||||
failStopAt int
|
||||
stopErr error
|
||||
}
|
||||
|
||||
func (s *rowListingStore) list(listed func(each ListEachEntryFunc) (string, error), eachEntryFunc ListEachEntryFunc) (string, error) {
|
||||
handed, endedAt := 0, 0
|
||||
lastFileName, err := listed(func(entry *Entry) (bool, error) {
|
||||
if s.listErr != nil && handed == s.failAfter {
|
||||
return false, s.listErr
|
||||
}
|
||||
handed++
|
||||
more, err := eachEntryFunc(entry.ShallowClone())
|
||||
if err == nil && !more {
|
||||
endedAt = handed
|
||||
}
|
||||
return more, err
|
||||
})
|
||||
if err == nil && s.stopErr != nil && endedAt == s.failStopAt {
|
||||
return lastFileName, s.stopErr
|
||||
}
|
||||
return lastFileName, err
|
||||
}
|
||||
|
||||
func (s *rowListingStore) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc ListEachEntryFunc) (string, error) {
|
||||
return s.list(func(each ListEachEntryFunc) (string, error) {
|
||||
return s.stubFilerStore.ListDirectoryEntries(ctx, dirPath, startFileName, includeStartFile, limit, each)
|
||||
}, eachEntryFunc)
|
||||
}
|
||||
|
||||
func (s *rowListingStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc ListEachEntryFunc) (string, error) {
|
||||
return s.list(func(each ListEachEntryFunc) (string, error) {
|
||||
return s.stubFilerStore.ListDirectoryPrefixedEntries(ctx, dirPath, startFileName, includeStartFile, limit, prefix, each)
|
||||
}, eachEntryFunc)
|
||||
}
|
||||
|
||||
// batchReadingStore also reads KV keys in batches.
|
||||
type batchReadingStore struct {
|
||||
*rowListingStore
|
||||
batches [][]string // the keys of each batch it was asked for
|
||||
batchErr error
|
||||
}
|
||||
|
||||
func (s *batchReadingStore) KvBatchGet(_ context.Context, keys [][]byte) (map[string][]byte, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
batch := make([]string, 0, len(keys))
|
||||
for _, key := range keys {
|
||||
batch = append(batch, string(key))
|
||||
}
|
||||
s.batches = append(s.batches, batch)
|
||||
if s.batchErr != nil {
|
||||
return nil, s.batchErr
|
||||
}
|
||||
values := make(map[string][]byte)
|
||||
for _, key := range keys {
|
||||
if value, found := s.kv[string(key)]; found {
|
||||
values[string(key)] = append([]byte(nil), value...)
|
||||
}
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// linkListingStores returns the same directory in a store that reads records
|
||||
// one at a time and in one that reads them in batches, each with a count of
|
||||
// the single reads it serves.
|
||||
func linkListingStores(t *testing.T, fill func(store *stubFilerStore)) (oneByOne *rowListingStore, oneReads *int, batched *batchReadingStore, batchedReads *int) {
|
||||
t.Helper()
|
||||
build := func() (*rowListingStore, *int) {
|
||||
stub := newStubFilerStore()
|
||||
fill(stub)
|
||||
reads := new(int)
|
||||
stub.kvGetHook = func([]byte) { *reads++ }
|
||||
return &rowListingStore{stubFilerStore: stub}, reads
|
||||
}
|
||||
oneByOne, oneReads = build()
|
||||
rows, batchedReads := build()
|
||||
return oneByOne, oneReads, &batchReadingStore{rowListingStore: rows}, batchedReads
|
||||
}
|
||||
|
||||
// linkedName stores name as one more name of a hard-linked file. The row keeps
|
||||
// what the name was written with; the record, which a listing must answer
|
||||
// with, has moved on: size bytes and count names.
|
||||
func linkedName(t *testing.T, store *stubFilerStore, id HardLinkId, name string, size uint64, count int32) {
|
||||
t.Helper()
|
||||
store.entries[name] = &Entry{
|
||||
FullPath: util.FullPath(name),
|
||||
Attr: Attr{Mode: 0o644, Mtime: time.Unix(1700000000, 0)},
|
||||
HardLinkId: id,
|
||||
HardLinkCounter: 1,
|
||||
}
|
||||
if size == 0 {
|
||||
return // a name whose record is gone
|
||||
}
|
||||
store.kv[string(id)] = encodeLinkRecord(t, &Entry{
|
||||
FullPath: util.FullPath(name),
|
||||
Attr: Attr{Mode: 0o600, Mtime: time.Unix(1700000500, 0), FileSize: size},
|
||||
HardLinkId: id,
|
||||
HardLinkCounter: count,
|
||||
Chunks: []*filer_pb.FileChunk{{FileId: fmt.Sprintf("7,%02x", size), Size: size}},
|
||||
})
|
||||
}
|
||||
|
||||
// listed is what a caller of a listing can see of an entry.
|
||||
type listed struct {
|
||||
Name string
|
||||
Size uint64
|
||||
Mode uint32
|
||||
Links int32
|
||||
Chunks string
|
||||
}
|
||||
|
||||
func see(entry *Entry) listed {
|
||||
return listed{
|
||||
Name: entry.Name(),
|
||||
Size: entry.FileSize,
|
||||
Mode: uint32(entry.Mode),
|
||||
Links: entry.HardLinkCounter,
|
||||
Chunks: strings.Join(filer_pb.FileIdsString(entry.GetChunks()), " "),
|
||||
}
|
||||
}
|
||||
|
||||
func listAll(t *testing.T, store FilerStore, dir string, startFileName string, limit int64) (entries []listed, lastFileName string) {
|
||||
t.Helper()
|
||||
lastFileName, err := NewFilerStoreWrapper(store).ListDirectoryEntries(context.Background(), util.FullPath(dir), startFileName, false, limit, func(entry *Entry) (bool, error) {
|
||||
entries = append(entries, see(entry))
|
||||
return true, nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return entries, lastFileName
|
||||
}
|
||||
|
||||
func mixedDirectory(t *testing.T) func(store *stubFilerStore) {
|
||||
x, y, gone := HardLinkId("link-x-0123456789"), HardLinkId("link-y-0123456789"), HardLinkId("link-gone-0123456")
|
||||
return func(store *stubFilerStore) {
|
||||
store.entries["/d/a"] = fileAt("/d/a")
|
||||
linkedName(t, store, x, "/d/b", 11, 2)
|
||||
store.entries["/d/c"] = fileAt("/d/c")
|
||||
linkedName(t, store, y, "/d/d", 22, 3)
|
||||
linkedName(t, store, x, "/d/e", 11, 2)
|
||||
linkedName(t, store, gone, "/d/f", 0, 0)
|
||||
store.entries["/d/g"] = fileAt("/d/g")
|
||||
linkedName(t, store, y, "/elsewhere/y", 22, 3)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListingReadsHardLinkRecordsTogether(t *testing.T) {
|
||||
oneByOne, oneReads, batched, batchedReads := linkListingStores(t, mixedDirectory(t))
|
||||
|
||||
want, wantLast := listAll(t, oneByOne, "/d", "", 100)
|
||||
got, gotLast := listAll(t, batched, "/d", "", 100)
|
||||
|
||||
require.Equal(t, []string{"a", "b", "c", "d", "e", "f", "g"}, namesOf(want))
|
||||
require.Equal(t, listed{Name: "b", Size: 11, Mode: 0o600, Links: 2, Chunks: "7,0b"}, want[1], "a linked name lists what its record holds")
|
||||
require.Equal(t, listed{Name: "f", Mode: 0o644, Links: 1}, want[5], "a name whose record is gone lists its row")
|
||||
require.Equal(t, want, got, "the entries of a listing do not depend on how their records were read")
|
||||
require.Equal(t, wantLast, gotLast)
|
||||
|
||||
require.Equal(t, 4, *oneReads, "one read for each hard-linked name")
|
||||
require.Zero(t, *batchedReads)
|
||||
require.Equal(t, [][]string{{"link-x-0123456789", "link-y-0123456789", "link-gone-0123456"}}, batched.batches,
|
||||
"one read for all of them, each record asked for once")
|
||||
}
|
||||
|
||||
func TestListingWithAPrefixReadsHardLinkRecordsTogether(t *testing.T) {
|
||||
_, _, batched, batchedReads := linkListingStores(t, func(store *stubFilerStore) {
|
||||
for i := 0; i < 6; i++ {
|
||||
linkedName(t, store, HardLinkId(fmt.Sprintf("link-%d-0123456789", i)), fmt.Sprintf("/d/p%d", i), uint64(10+i), 2)
|
||||
store.entries[fmt.Sprintf("/d/q%d", i)] = fileAt(fmt.Sprintf("/d/q%d", i))
|
||||
}
|
||||
})
|
||||
|
||||
var got []listed
|
||||
lastFileName, err := NewFilerStoreWrapper(batched).ListDirectoryPrefixedEntries(context.Background(), "/d", "", false, 100, "p", func(entry *Entry) (bool, error) {
|
||||
got = append(got, see(entry))
|
||||
return true, nil
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "p5", lastFileName)
|
||||
require.Equal(t, []string{"p0", "p1", "p2", "p3", "p4", "p5"}, namesOf(got))
|
||||
require.Equal(t, uint64(13), got[3].Size)
|
||||
require.Zero(t, *batchedReads)
|
||||
require.Len(t, batched.batches, 1)
|
||||
}
|
||||
|
||||
// More names than wait at once: the entries still come in the store's order,
|
||||
// page after page, each once.
|
||||
func TestListingKeepsItsOrderAcrossBatches(t *testing.T) {
|
||||
const names = 2*hardLinkBatchSize + 300
|
||||
oneByOne, _, batched, batchedReads := linkListingStores(t, func(store *stubFilerStore) {
|
||||
for i := 0; i < names; i++ {
|
||||
name := fmt.Sprintf("/d/n%05d", i)
|
||||
if i%3 == 1 {
|
||||
store.entries[name] = fileAt(name)
|
||||
continue
|
||||
}
|
||||
linkedName(t, store, HardLinkId(fmt.Sprintf("link-%05d-012345", i)), name, uint64(1+i), 2)
|
||||
}
|
||||
})
|
||||
|
||||
want, _ := listAll(t, oneByOne, "/d", "", names+1)
|
||||
got, lastFileName := listAll(t, batched, "/d", "", names+1)
|
||||
|
||||
require.Len(t, got, names)
|
||||
require.Equal(t, want, got)
|
||||
require.Equal(t, fmt.Sprintf("n%05d", names-1), lastFileName)
|
||||
require.Zero(t, *batchedReads)
|
||||
// the first name is linked, so every hardLinkBatchSize entries wait together
|
||||
require.Len(t, batched.batches, (names+hardLinkBatchSize-1)/hardLinkBatchSize)
|
||||
for _, batch := range batched.batches {
|
||||
require.LessOrEqual(t, len(batch), hardLinkBatchSize)
|
||||
}
|
||||
|
||||
// read in pages, as ListEntries reads a directory
|
||||
const pageSize = hardLinkBatchSize + 100
|
||||
var paged []listed
|
||||
for start := ""; ; {
|
||||
page, last := listAll(t, batched, "/d", start, pageSize)
|
||||
paged = append(paged, page...)
|
||||
if len(page) < pageSize {
|
||||
break
|
||||
}
|
||||
start = last
|
||||
}
|
||||
require.Equal(t, want, paged)
|
||||
}
|
||||
|
||||
// The caller ends a listing at an entry whose record was read with those of
|
||||
// the entries behind it. The listing ends there for the caller: it gets none
|
||||
// of the entries behind it, and the listing that continues from the name it
|
||||
// is given back has every one of them.
|
||||
func TestListingEndedByItsCallerContinuesFromWhereItEnded(t *testing.T) {
|
||||
oneByOne, _, batched, _ := linkListingStores(t, mixedDirectory(t))
|
||||
want, _ := listAll(t, oneByOne, "/d", "", 100)
|
||||
|
||||
for stopAt := 1; stopAt <= len(want); stopAt++ {
|
||||
var got []listed
|
||||
lastFileName, err := NewFilerStoreWrapper(batched).ListDirectoryEntries(context.Background(), "/d", "", false, 100, func(entry *Entry) (bool, error) {
|
||||
got = append(got, see(entry))
|
||||
return len(got) < stopAt, nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, want[:stopAt], got, "ended at entry %d", stopAt)
|
||||
require.Equal(t, want[stopAt-1].Name, lastFileName, "ended at entry %d", stopAt)
|
||||
|
||||
rest, _ := listAll(t, batched, "/d", lastFileName, 100)
|
||||
require.Equal(t, want[stopAt:], append([]listed{}, rest...), "continued after entry %d", stopAt)
|
||||
}
|
||||
}
|
||||
|
||||
// A caller's error ends the listing with that error, and with nothing handed
|
||||
// on after it.
|
||||
func TestListingReturnsItsCallersError(t *testing.T) {
|
||||
_, _, batched, _ := linkListingStores(t, mixedDirectory(t))
|
||||
refused := errors.New("refused")
|
||||
|
||||
for failAt := 1; failAt <= 7; failAt++ {
|
||||
handed := 0
|
||||
_, err := NewFilerStoreWrapper(batched).ListDirectoryEntries(context.Background(), "/d", "", false, 100, func(entry *Entry) (bool, error) {
|
||||
handed++
|
||||
if handed == failAt {
|
||||
return false, refused
|
||||
}
|
||||
return true, nil
|
||||
})
|
||||
require.ErrorIs(t, err, refused, "failed at entry %d", failAt)
|
||||
require.Equal(t, failAt, handed, "failed at entry %d", failAt)
|
||||
}
|
||||
}
|
||||
|
||||
// The records are then read one at a time, as from a store without batches.
|
||||
func TestListingReadsRecordsOneByOneWhenTheBatchFails(t *testing.T) {
|
||||
oneByOne, _, batched, batchedReads := linkListingStores(t, mixedDirectory(t))
|
||||
batched.batchErr = errors.New("region unavailable")
|
||||
|
||||
want, _ := listAll(t, oneByOne, "/d", "", 100)
|
||||
got, _ := listAll(t, batched, "/d", "", 100)
|
||||
|
||||
require.Equal(t, want, got)
|
||||
require.Equal(t, 4, *batchedReads)
|
||||
}
|
||||
|
||||
// A store that fails its listing part of the way has handed some entries over
|
||||
// already. They reach the caller before the error does, as they do when each
|
||||
// is handed on as it arrives.
|
||||
func TestListingHandsOnWhatTheStoreListedBeforeItFailed(t *testing.T) {
|
||||
oneByOne, _, batched, _ := linkListingStores(t, mixedDirectory(t))
|
||||
broken := errors.New("iterator closed")
|
||||
want, _ := listAll(t, oneByOne, "/d", "", 100)
|
||||
|
||||
for failAfter := 0; failAfter <= 6; failAfter++ {
|
||||
batched.failAfter, batched.listErr = failAfter, broken
|
||||
var got []listed
|
||||
_, err := NewFilerStoreWrapper(batched).ListDirectoryEntries(context.Background(), "/d", "", false, 100, func(entry *Entry) (bool, error) {
|
||||
got = append(got, see(entry))
|
||||
return true, nil
|
||||
})
|
||||
require.ErrorIs(t, err, broken, "failed after %d entries", failAfter)
|
||||
require.Equal(t, want[:failAfter], append([]listed{}, got...), "failed after %d entries", failAfter)
|
||||
}
|
||||
}
|
||||
|
||||
// listUntil lists dir and ends the listing at its entry numbered stopAt.
|
||||
func listUntil(store FilerStore, dir string, stopAt int) (entries []listed, lastFileName string, err error) {
|
||||
lastFileName, err = NewFilerStoreWrapper(store).ListDirectoryEntries(context.Background(), util.FullPath(dir), "", false, 100000, func(entry *Entry) (bool, error) {
|
||||
entries = append(entries, see(entry))
|
||||
return len(entries) < stopAt, nil
|
||||
})
|
||||
return entries, lastFileName, err
|
||||
}
|
||||
|
||||
// The store goes on past the entry its caller ends the listing at, to the
|
||||
// entries that wait with it, and may fail there. Handed each entry as it
|
||||
// arrived, the caller would have stopped the store before that: the listing
|
||||
// ends where the caller ended it, and its own failure is the one it gets.
|
||||
func TestListingEndedByItsCallerIsNotFailedByWhatTheStoreMetBehind(t *testing.T) {
|
||||
oneByOne, _, batched, _ := linkListingStores(t, mixedDirectory(t))
|
||||
want, _ := listAll(t, oneByOne, "/d", "", 100)
|
||||
broken := errors.New("iterator closed")
|
||||
|
||||
// the store hands over a to e and then fails; b to e wait for their records
|
||||
oneByOne.failAfter, oneByOne.listErr = 5, broken
|
||||
batched.failAfter, batched.listErr = 5, broken
|
||||
for stopAt := 1; stopAt <= 5; stopAt++ {
|
||||
_, _, err := listUntil(oneByOne, "/d", stopAt)
|
||||
require.NoError(t, err, "one at a time, ended at entry %d", stopAt)
|
||||
|
||||
got, lastFileName, err := listUntil(batched, "/d", stopAt)
|
||||
require.NoError(t, err, "ended at entry %d", stopAt)
|
||||
require.Equal(t, want[:stopAt], got, "ended at entry %d", stopAt)
|
||||
require.Equal(t, want[stopAt-1].Name, lastFileName, "ended at entry %d", stopAt)
|
||||
}
|
||||
|
||||
refused := errors.New("refused")
|
||||
for failAt := 2; failAt <= 5; failAt++ {
|
||||
handed := 0
|
||||
_, err := NewFilerStoreWrapper(batched).ListDirectoryEntries(context.Background(), "/d", "", false, 100, func(entry *Entry) (bool, error) {
|
||||
handed++
|
||||
if handed == failAt {
|
||||
return false, refused
|
||||
}
|
||||
return true, nil
|
||||
})
|
||||
require.ErrorIs(t, err, refused, "failed at entry %d", failAt)
|
||||
require.NotErrorIs(t, err, broken, "failed at entry %d", failAt)
|
||||
}
|
||||
}
|
||||
|
||||
// The same for the step a store takes after its caller has ended the listing.
|
||||
// It fails behind the last entry that waits: a caller that ended the listing
|
||||
// at an earlier one had stopped the store before, and a caller that ended it
|
||||
// at that last one gets the failure, as it does from a store that hands each
|
||||
// entry on as it arrives.
|
||||
func TestListingEndedByItsCallerIsNotFailedByTheStoresStepBehind(t *testing.T) {
|
||||
const names = hardLinkBatchSize + 50
|
||||
oneByOne, _, batched, _ := linkListingStores(t, func(store *stubFilerStore) {
|
||||
for i := 0; i < names; i++ {
|
||||
linkedName(t, store, HardLinkId(fmt.Sprintf("link-%05d-012345", i)), fmt.Sprintf("/d/n%05d", i), uint64(1+i), 2)
|
||||
}
|
||||
})
|
||||
broken := errors.New("iterator closed")
|
||||
oneByOne.failStopAt, oneByOne.stopErr = hardLinkBatchSize, broken
|
||||
batched.failStopAt, batched.stopErr = hardLinkBatchSize, broken
|
||||
|
||||
for _, stopAt := range []int{1, 10, hardLinkBatchSize - 1, hardLinkBatchSize, hardLinkBatchSize + 1, names} {
|
||||
want, wantLast, wantErr := listUntil(oneByOne, "/d", stopAt)
|
||||
got, gotLast, gotErr := listUntil(batched, "/d", stopAt)
|
||||
|
||||
require.Equal(t, stopAt == hardLinkBatchSize, wantErr != nil, "one at a time, ended at entry %d", stopAt)
|
||||
require.Equal(t, wantErr, gotErr, "ended at entry %d", stopAt)
|
||||
require.Equal(t, want, got, "ended at entry %d", stopAt)
|
||||
if wantErr == nil {
|
||||
require.Equal(t, wantLast, gotLast, "ended at entry %d", stopAt)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The records are in the default store. A directory another store lists keeps
|
||||
// the read per entry: nothing says that store's listing hands over entries
|
||||
// that can wait.
|
||||
func TestListingOfAPathSpecificStoreReadsRecordsOneByOne(t *testing.T) {
|
||||
_, _, batched, batchedReads := linkListingStores(t, mixedDirectory(t))
|
||||
other := &rowListingStore{stubFilerStore: newStubFilerStore()}
|
||||
// the store keeps its paths without the prefix it is mounted at
|
||||
other.entries["/d/n"] = &Entry{
|
||||
FullPath: "/d/n",
|
||||
Attr: Attr{Mode: 0o644},
|
||||
HardLinkId: HardLinkId("link-x-0123456789"),
|
||||
}
|
||||
wrapper := NewFilerStoreWrapper(batched)
|
||||
wrapper.AddPathSpecificStore("/other/", "other", other)
|
||||
|
||||
var got []listed
|
||||
_, err := wrapper.ListDirectoryEntries(context.Background(), "/other/d", "", false, 100, func(entry *Entry) (bool, error) {
|
||||
got = append(got, see(entry))
|
||||
return true, nil
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []listed{{Name: "n", Size: 11, Mode: 0o600, Links: 2, Chunks: "7,0b"}}, got)
|
||||
require.Equal(t, 1, *batchedReads)
|
||||
require.Empty(t, batched.batches)
|
||||
}
|
||||
|
||||
func namesOf(entries []listed) (names []string) {
|
||||
for _, entry := range entries {
|
||||
names = append(names, entry.Name)
|
||||
}
|
||||
return names
|
||||
}
|
||||
@@ -72,6 +72,19 @@ type EntryScanner interface {
|
||||
ScanEntries(ctx context.Context, dirPath util.FullPath, fn func(ctx context.Context, entry *Entry) error) error
|
||||
}
|
||||
|
||||
// KvBatchReader is implemented by a store that reads several KV keys in one
|
||||
// round trip. A directory listing reads the shared record of every hard-linked
|
||||
// entry it lists; from such a store it reads the records of a run of entries
|
||||
// together, instead of one at a time while the store iterates.
|
||||
//
|
||||
// The listing keeps the entries the store hands over until their records are
|
||||
// read, so each of them is an *Entry of its own.
|
||||
type KvBatchReader interface {
|
||||
// KvBatchGet returns the values of the keys the store holds, by key. A
|
||||
// key it does not hold is left out.
|
||||
KvBatchGet(ctx context.Context, keys [][]byte) (values map[string][]byte, err error)
|
||||
}
|
||||
|
||||
type BucketAware interface {
|
||||
OnBucketCreation(bucket string)
|
||||
OnBucketDeletion(bucket string)
|
||||
|
||||
@@ -456,6 +456,139 @@ func (fsw *FilerStoreWrapper) maybeReadHardLink(ctx context.Context, entry *Entr
|
||||
return nil
|
||||
}
|
||||
|
||||
// hardLinkBatchSize is how many entries of a listing wait for their hard link
|
||||
// records at most, and so how many records are read together at most. The
|
||||
// entries that wait are held in memory, chunk lists and all.
|
||||
const hardLinkBatchSize = 256
|
||||
|
||||
// hardLinkListing hands the entries of one store listing on to the listing's
|
||||
// caller, each with its hard link read as maybeReadHardLink reads it.
|
||||
//
|
||||
// Read as each entry arrives, that is a round trip to the store for every
|
||||
// hard-linked name, made one after the other while the store iterates: a
|
||||
// directory of hard-linked files lists many times slower than one of plain
|
||||
// files. Where the store that lists is the default store, which holds the
|
||||
// records, and reads KV keys in batches (KvBatchReader), the entries from the
|
||||
// first hard-linked one on wait, up to hardLinkBatchSize of them, and their
|
||||
// records are read together. The caller gets the entries in the order the
|
||||
// store lists them either way.
|
||||
type hardLinkListing struct {
|
||||
fsw *FilerStoreWrapper
|
||||
ctx context.Context
|
||||
each ListEachEntryFunc
|
||||
reader KvBatchReader // nil: a record is read when its entry arrives
|
||||
held []*Entry // waiting for their records; the first has a hard link
|
||||
last string // the name of the last entry handed on
|
||||
ended bool // each ended the listing or failed
|
||||
passed bool // each ended it at an entry with others waiting behind
|
||||
}
|
||||
|
||||
func (fsw *FilerStoreWrapper) newHardLinkListing(ctx context.Context, actualStore FilerStore, eachEntryFunc ListEachEntryFunc) *hardLinkListing {
|
||||
listing := &hardLinkListing{fsw: fsw, ctx: ctx, each: eachEntryFunc}
|
||||
if actualStore == fsw.defaultStore {
|
||||
listing.reader, _ = actualStore.(KvBatchReader)
|
||||
}
|
||||
return listing
|
||||
}
|
||||
|
||||
// add takes the next entry of the store's listing.
|
||||
func (l *hardLinkListing) add(entry *Entry) (bool, error) {
|
||||
if l.reader == nil {
|
||||
l.fsw.maybeReadHardLink(l.ctx, entry)
|
||||
return l.handOn(entry)
|
||||
}
|
||||
if len(l.held) == 0 && len(entry.HardLinkId) == 0 {
|
||||
return l.handOn(entry)
|
||||
}
|
||||
l.held = append(l.held, entry)
|
||||
if len(l.held) < hardLinkBatchSize {
|
||||
return true, nil
|
||||
}
|
||||
return l.release()
|
||||
}
|
||||
|
||||
// release reads the records of the entries that wait and hands the entries on.
|
||||
func (l *hardLinkListing) release() (bool, error) {
|
||||
held := l.held
|
||||
l.held = nil
|
||||
keys := make([][]byte, 0, len(held))
|
||||
asked := make(map[string]struct{}, len(held))
|
||||
for _, entry := range held {
|
||||
if len(entry.HardLinkId) == 0 {
|
||||
continue
|
||||
}
|
||||
// a directory may hold several names of one file
|
||||
if _, found := asked[string(entry.HardLinkId)]; !found {
|
||||
asked[string(entry.HardLinkId)] = struct{}{}
|
||||
keys = append(keys, entry.HardLinkId)
|
||||
}
|
||||
}
|
||||
records, batchErr := l.reader.KvBatchGet(l.ctx, keys)
|
||||
if batchErr != nil {
|
||||
glog.ErrorfCtx(l.ctx, "read %d hard link records together: %v", len(keys), batchErr)
|
||||
}
|
||||
for i, entry := range held {
|
||||
if len(entry.HardLinkId) != 0 {
|
||||
if batchErr != nil {
|
||||
// one at a time, as from a store without batches
|
||||
l.fsw.maybeReadHardLink(l.ctx, entry)
|
||||
} else if record, found := records[string(entry.HardLinkId)]; found {
|
||||
if err := entry.DecodeAttributesAndChunks(record); err != nil {
|
||||
glog.ErrorfCtx(l.ctx, "decode %s HardLinkId %x: %v", entry.FullPath, entry.HardLinkId, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if more, err := l.handOn(entry); err != nil || !more {
|
||||
l.passed = err == nil && i < len(held)-1
|
||||
return more, err
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (l *hardLinkListing) handOn(entry *Entry) (bool, error) {
|
||||
filer_pb.AfterEntryDeserialization(entry.GetChunks())
|
||||
more, err := l.each(entry)
|
||||
if err != nil {
|
||||
l.ended = true
|
||||
return more, err
|
||||
}
|
||||
l.last = entry.Name()
|
||||
l.ended = !more
|
||||
return more, nil
|
||||
}
|
||||
|
||||
// finish takes what the store's listing returned, hands on the entries that
|
||||
// still wait, and returns what the listing returns to its caller.
|
||||
//
|
||||
// The store may have gone past the entry its caller ended the listing at,
|
||||
// with entries that waited behind it. The last name listed is then the one
|
||||
// the caller ended at, and a listing that continues from there has them. An
|
||||
// error the store ran into past that entry is not the caller's either: handed
|
||||
// each entry as it arrived, the caller would have stopped the store before.
|
||||
func (l *hardLinkListing) finish(lastFileName string, err error) (string, error) {
|
||||
if l.reader == nil {
|
||||
return lastFileName, err
|
||||
}
|
||||
if !l.ended && len(l.held) > 0 {
|
||||
// The store handed these over and went on, to the end of its listing
|
||||
// or to an error. Where the caller ends the listing among them, or
|
||||
// fails, that is how the listing ends.
|
||||
more, eachErr := l.release()
|
||||
if eachErr != nil {
|
||||
return lastFileName, eachErr
|
||||
}
|
||||
if !more {
|
||||
return l.last, nil
|
||||
}
|
||||
return lastFileName, err
|
||||
}
|
||||
if l.ended && (err == nil || l.passed) {
|
||||
return l.last, nil
|
||||
}
|
||||
return lastFileName, err
|
||||
}
|
||||
|
||||
func (fsw *FilerStoreWrapper) DeleteHardLink(ctx context.Context, hardLinkId HardLinkId) error {
|
||||
if !fsw.countsLinks {
|
||||
return fsw.deleteHardLink(ctx, hardLinkId)
|
||||
|
||||
@@ -380,7 +380,7 @@ func (fsw *FilerStoreWrapper) DeleteFolderChildren(ctx context.Context, fp util.
|
||||
return actualStore.DeleteFolderChildren(ctx, fp)
|
||||
}
|
||||
|
||||
func (fsw *FilerStoreWrapper) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc ListEachEntryFunc) (string, error) {
|
||||
func (fsw *FilerStoreWrapper) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc ListEachEntryFunc) (lastFileName string, err error) {
|
||||
ctx = context.WithoutCancel(ctx)
|
||||
actualStore := fsw.getActualStore(dirPath + "/")
|
||||
stats.FilerStoreCounter.WithLabelValues(actualStore.GetName(), "list").Inc()
|
||||
@@ -389,12 +389,15 @@ func (fsw *FilerStoreWrapper) ListDirectoryEntries(ctx context.Context, dirPath
|
||||
stats.FilerStoreHistogram.WithLabelValues(actualStore.GetName(), "list").Observe(time.Since(start).Seconds())
|
||||
}()
|
||||
|
||||
listing := fsw.newHardLinkListing(ctx, actualStore, eachEntryFunc)
|
||||
defer func() {
|
||||
lastFileName, err = listing.finish(lastFileName, err)
|
||||
}()
|
||||
// glog.V(4).Infof("ListDirectoryEntries %s from %s limit %d", dirPath, startFileName, limit)
|
||||
return actualStore.ListDirectoryEntries(ctx, dirPath, startFileName, includeStartFile, limit, func(entry *Entry) (bool, error) {
|
||||
fsw.maybeReadHardLink(ctx, entry)
|
||||
filer_pb.AfterEntryDeserialization(entry.GetChunks())
|
||||
return eachEntryFunc(entry)
|
||||
})
|
||||
adjustedEntryFunc := func(entry *Entry) (bool, error) {
|
||||
return listing.add(entry)
|
||||
}
|
||||
return actualStore.ListDirectoryEntries(ctx, dirPath, startFileName, includeStartFile, limit, adjustedEntryFunc)
|
||||
}
|
||||
|
||||
func (fsw *FilerStoreWrapper) ListDirectoryPrefixedEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc ListEachEntryFunc) (lastFileName string, err error) {
|
||||
@@ -408,11 +411,13 @@ func (fsw *FilerStoreWrapper) ListDirectoryPrefixedEntries(ctx context.Context,
|
||||
if limit > math.MaxInt32-1 {
|
||||
limit = math.MaxInt32 - 1
|
||||
}
|
||||
listing := fsw.newHardLinkListing(ctx, actualStore, eachEntryFunc)
|
||||
defer func() {
|
||||
lastFileName, err = listing.finish(lastFileName, err)
|
||||
}()
|
||||
// glog.V(4).Infof("ListDirectoryPrefixedEntries %s from %s prefix %s limit %d", dirPath, startFileName, prefix, limit)
|
||||
adjustedEntryFunc := func(entry *Entry) (bool, error) {
|
||||
fsw.maybeReadHardLink(ctx, entry)
|
||||
filer_pb.AfterEntryDeserialization(entry.GetChunks())
|
||||
return eachEntryFunc(entry)
|
||||
return listing.add(entry)
|
||||
}
|
||||
lastFileName, err = actualStore.ListDirectoryPrefixedEntries(ctx, dirPath, startFileName, includeStartFile, limit, prefix, adjustedEntryFunc)
|
||||
if err == ErrUnsupportedListDirectoryPrefixed {
|
||||
|
||||
@@ -34,6 +34,23 @@ func (store *TikvStore) KvGet(ctx context.Context, key []byte) ([]byte, error) {
|
||||
return data, err
|
||||
}
|
||||
|
||||
// KvBatchGet reads the keys with one request for each region they are in.
|
||||
func (store *TikvStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
|
||||
tw, err := store.getTxn(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var values map[string][]byte
|
||||
err = tw.RunInTxn(ctx, func(txn *txnkv.KVTxn) error {
|
||||
var err error
|
||||
values, err = txn.BatchGet(ctx, keys)
|
||||
return err
|
||||
})
|
||||
return values, err
|
||||
}
|
||||
|
||||
var _ filer.KvBatchReader = (*TikvStore)(nil)
|
||||
|
||||
func (store *TikvStore) KvDelete(ctx context.Context, key []byte) error {
|
||||
return store.runTxn(ctx, func(txn *txnkv.KVTxn) error {
|
||||
return txn.Delete(key)
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
//go:build tikv
|
||||
|
||||
package tikv
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/tikv/client-go/v2/testutils"
|
||||
"github.com/tikv/client-go/v2/tikv"
|
||||
"github.com/tikv/client-go/v2/tikvrpc"
|
||||
"github.com/tikv/client-go/v2/txnkv"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// kvRequests counts the requests the store sends to TiKV, by kind.
|
||||
type kvRequests struct {
|
||||
tikv.Client
|
||||
mu sync.Mutex
|
||||
sent map[tikvrpc.CmdType]int
|
||||
}
|
||||
|
||||
func (r *kvRequests) SendRequest(ctx context.Context, addr string, req *tikvrpc.Request, timeout time.Duration) (*tikvrpc.Response, error) {
|
||||
r.mu.Lock()
|
||||
r.sent[req.Type]++
|
||||
r.mu.Unlock()
|
||||
return r.Client.SendRequest(ctx, addr, req, timeout)
|
||||
}
|
||||
|
||||
// during runs f and returns the gets and batch gets it sent.
|
||||
func (r *kvRequests) during(f func()) (gets, batchGets int) {
|
||||
r.mu.Lock()
|
||||
r.sent = map[tikvrpc.CmdType]int{}
|
||||
r.mu.Unlock()
|
||||
f()
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return r.sent[tikvrpc.CmdGet], r.sent[tikvrpc.CmdBatchGet]
|
||||
}
|
||||
|
||||
// newStoreOnMockTiKV is a store on the client library's in-process TiKV.
|
||||
func newStoreOnMockTiKV(t *testing.T) (*TikvStore, *kvRequests) {
|
||||
t.Helper()
|
||||
client, cluster, pdClient, err := testutils.NewMockTiKV("", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("mock tikv: %v", err)
|
||||
}
|
||||
testutils.BootstrapWithSingleStore(cluster)
|
||||
requests := &kvRequests{sent: map[tikvrpc.CmdType]int{}}
|
||||
kvStore, err := tikv.NewTestTiKVStore(client, pdClient, func(c tikv.Client) tikv.Client {
|
||||
requests.Client = c
|
||||
return requests
|
||||
}, nil, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("mock tikv store: %v", err)
|
||||
}
|
||||
store := &TikvStore{client: &txnkv.Client{KVStore: kvStore}}
|
||||
t.Cleanup(store.Shutdown)
|
||||
return store, requests
|
||||
}
|
||||
|
||||
func TestKvBatchGetReadsItsKeysInOneRequest(t *testing.T) {
|
||||
store, requests := newStoreOnMockTiKV(t)
|
||||
ctx := context.Background()
|
||||
for _, key := range []string{"a", "b", "c"} {
|
||||
if err := store.KvPut(ctx, []byte(key), []byte("value of "+key)); err != nil {
|
||||
t.Fatalf("put %s: %v", key, err)
|
||||
}
|
||||
}
|
||||
|
||||
var values map[string][]byte
|
||||
gets, batchGets := requests.during(func() {
|
||||
var err error
|
||||
if values, err = store.KvBatchGet(ctx, [][]byte{[]byte("a"), []byte("missing"), []byte("c")}); err != nil {
|
||||
t.Fatalf("batch get: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
want := map[string][]byte{"a": []byte("value of a"), "c": []byte("value of c")}
|
||||
if !reflect.DeepEqual(values, want) {
|
||||
t.Errorf("batch get = %q, want %q: the keys held, and no others", values, want)
|
||||
}
|
||||
if gets != 0 || batchGets != 1 {
|
||||
t.Errorf("sent %d gets and %d batch gets, want one batch get", gets, batchGets)
|
||||
}
|
||||
|
||||
// inside a transaction it reads what the transaction wrote
|
||||
txCtx, err := store.BeginTransaction(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("begin: %v", err)
|
||||
}
|
||||
defer store.RollbackTransaction(txCtx)
|
||||
if err := store.KvPut(txCtx, []byte("d"), []byte("value of d")); err != nil {
|
||||
t.Fatalf("put in transaction: %v", err)
|
||||
}
|
||||
if err := store.KvDelete(txCtx, []byte("a")); err != nil {
|
||||
t.Fatalf("delete in transaction: %v", err)
|
||||
}
|
||||
values, err = store.KvBatchGet(txCtx, [][]byte{[]byte("a"), []byte("c"), []byte("d")})
|
||||
if err != nil {
|
||||
t.Fatalf("batch get in transaction: %v", err)
|
||||
}
|
||||
want = map[string][]byte{"c": []byte("value of c"), "d": []byte("value of d")}
|
||||
if !reflect.DeepEqual(values, want) {
|
||||
t.Errorf("batch get in transaction = %q, want %q", values, want)
|
||||
}
|
||||
}
|
||||
|
||||
// oneByOne hides the store's batch read, which leaves a listing to read each
|
||||
// hard link record as its entry arrives.
|
||||
type oneByOne struct{ filer.FilerStore }
|
||||
|
||||
// A page of hard-linked names costs one request for their records, where it
|
||||
// cost one for each name.
|
||||
func TestListingReadsTheHardLinkRecordsOfAPageInOneRequest(t *testing.T) {
|
||||
store, requests := newStoreOnMockTiKV(t)
|
||||
ctx := context.Background()
|
||||
const names = 200
|
||||
writer := filer.NewFilerStoreWrapper(store)
|
||||
for i := 0; i < names; i++ {
|
||||
entry := &filer.Entry{
|
||||
FullPath: util.FullPath(fmt.Sprintf("/d/n%03d", i)),
|
||||
Attr: filer.Attr{Mode: 0644, Mtime: time.Unix(1700000000, 0), FileSize: uint64(1 + i)},
|
||||
HardLinkId: filer.HardLinkId(fmt.Sprintf("link-%03d-01234567", i)),
|
||||
HardLinkCounter: 2,
|
||||
Chunks: []*filer_pb.FileChunk{{FileId: fmt.Sprintf("3,%04x", i), Size: uint64(1 + i)}},
|
||||
}
|
||||
if err := writer.InsertEntry(ctx, entry); err != nil {
|
||||
t.Fatalf("insert %s: %v", entry.FullPath, err)
|
||||
}
|
||||
}
|
||||
|
||||
type seen struct {
|
||||
name string
|
||||
size uint64
|
||||
links int32
|
||||
chunk string
|
||||
}
|
||||
list := func(listing filer.FilerStore) (entries []seen, gets, batchGets int) {
|
||||
gets, batchGets = requests.during(func() {
|
||||
_, err := filer.NewFilerStoreWrapper(listing).ListDirectoryEntries(ctx, "/d", "", false, 1024, func(entry *filer.Entry) (bool, error) {
|
||||
entries = append(entries, seen{entry.Name(), entry.FileSize, entry.HardLinkCounter, entry.GetChunks()[0].FileId})
|
||||
return true, nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("list: %v", err)
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
want, gets, batchGets := list(oneByOne{store})
|
||||
if len(want) != names || want[7] != (seen{"n007", 8, 2, "3,0007"}) {
|
||||
t.Fatalf("listed %d entries, the eighth %+v", len(want), want[7])
|
||||
}
|
||||
if gets != names || batchGets != 0 {
|
||||
t.Errorf("read one at a time, the records took %d gets and %d batch gets, want %d gets", gets, batchGets, names)
|
||||
}
|
||||
|
||||
got, gets, batchGets := list(store)
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("read together, the listing differs from the one read one at a time")
|
||||
}
|
||||
if gets != 0 || batchGets != 1 {
|
||||
t.Errorf("read together, the records took %d gets and %d batch gets, want one batch get", gets, batchGets)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user