filer: every filer store reads KV keys in batches (#13119)

* filer: read KV keys a few at a time for a store without batch reads

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* abstract_sql: read KV keys with one query

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* redis: read KV keys in one pipeline

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* etcd: read KV keys in read-only transactions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mongodb: read KV keys with one query

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* cassandra: read KV keys concurrently

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* hbase: read KV keys concurrently

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* elastic: read KV keys concurrently

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* arangodb: read KV keys with one request

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* foundationdb: read KV keys in one transaction

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ydb: read KV keys with one query

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tarantool: send KV reads before waiting for any

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: every filer store reads KV keys in batches

KvBatchGet moves from the optional KvBatchReader onto FilerStore. A listing
now reads the hard link records of its waiting entries together from any
store, a path-specific one included.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tikv: count only the record reads of a listing in its test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: return every batched key that pads to the same stored row

SQL, MongoDB and YDB pad a short KV key with zero bytes, so "short" and
"short\x00" read the same row. KvBatchGet kept only the last such key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: read keys in a plain loop when KvGetEach runs one at a time

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Chris LuandClaude Opus 5.5 authored and GitHub committed 2026-11-29 23:10:49 -08:00
1 parent 604d391012
commit d49876a7aa
47 files changed
+1193 -94

No files matched your search

@@ -187,6 +187,10 @@ func (store *MockFoundationDBStore) KvGet(ctx context.Context, key []byte) ([]by
return value, nil
}
func (store *MockFoundationDBStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, store.KvGet, keys, 1)
}
func (store *MockFoundationDBStore) KvDelete(ctx context.Context, key []byte) error {
delete(store.kvStore, string(key))
return nil
+4
View File
@@ -27,6 +27,10 @@ func (s *kvOnlyStore) KvGet(_ context.Context, key []byte) ([]byte, error) {
return value, nil
}
func (s *kvOnlyStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, s.KvGet, keys, 1)
}
func (s *kvOnlyStore) KvPut(_ context.Context, key []byte, value []byte) error {
s.kv[string(key)] = value
return nil
@@ -19,6 +19,9 @@ type SqlGenerator interface {
GetSqlInsert(tableName string) string
GetSqlUpdate(tableName string) string
GetSqlFind(tableName string) string
// GetSqlFindBatch selects dirhash, name, directory and meta of the rows
// matching count (dirhash, name, directory) triples, as GetSqlFind does one.
GetSqlFindBatch(tableName string, count int) string
GetSqlDelete(tableName string) string
GetSqlDeleteFolderChildren(tableName string) string
GetSqlListExclusive(tableName string) string
@@ -76,6 +76,51 @@ func (store *AbstractSqlStore) KvGet(ctx context.Context, key []byte) (value []b
return
}
// kvBatchGetSize bounds the keys of one query, well under the bind parameter
// limit of every SQL store.
const kvBatchGetSize = 256
func (store *AbstractSqlStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
db := store.kvDB(ctx)
values := make(map[string][]byte, len(keys))
for start := 0; start < len(keys); start += kvBatchGetSize {
batch := keys[start:min(start+kvBatchGetSize, len(keys))]
type row struct {
dirHash int64
name, directory string
}
asked := make(map[row][]string, len(batch))
args := make([]interface{}, 0, 3*len(batch))
for _, key := range batch {
dirStr, dirHash, name := GenDirAndName(key)
r := row{dirHash, name, dirStr}
asked[r] = append(asked[r], string(key))
args = append(args, dirHash, name, dirStr)
}
if err := func() error {
rows, err := db.QueryContext(ctx, store.GetSqlFindBatch(DEFAULT_TABLE, len(batch)), args...)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var r row
var value []byte
if err := rows.Scan(&r.dirHash, &r.name, &r.directory, &value); err != nil {
return err
}
for _, key := range asked[r] {
values[key] = value
}
}
return rows.Err()
}(); err != nil {
return nil, fmt.Errorf("kv batch get: %w", err)
}
}
return values, nil
}
func (store *AbstractSqlStore) KvDelete(ctx context.Context, key []byte) (err error) {
db := store.kvDB(ctx)
+26
View File
@@ -44,6 +44,32 @@ func (store *ArangodbStore) KvGet(ctx context.Context, key []byte) (value []byte
return arrayToBytes(model.Meta), nil
}
func (store *ArangodbStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
values := make(map[string][]byte, len(keys))
if len(keys) == 0 {
return values, nil
}
docKeys := make([]string, len(keys))
for i, key := range keys {
docKeys[i] = hashString(".kvstore." + string(key))
}
models := make([]Model, len(keys))
_, errs, err := store.kvCollection.ReadDocuments(ctx, docKeys, models)
if err != nil {
return nil, fmt.Errorf("kv batch get: %w", err)
}
for i, key := range keys {
if i < len(errs) && errs[i] != nil {
if driver.IsNotFound(errs[i]) {
continue
}
return nil, fmt.Errorf("kv batch get: %w", errs[i])
}
values[string(key)] = arrayToBytes(models[i].Meta)
}
return values, nil
}
func (store *ArangodbStore) KvDelete(ctx context.Context, key []byte) (err error) {
_, err = store.kvCollection.RemoveDocument(ctx, hashString(".kvstore."+string(key)))
if err != nil {
@@ -0,0 +1,39 @@
package arangodb
import (
"context"
"crypto/rand"
"fmt"
"testing"
)
func TestKvBatchGetReadsTheKeysHeld(t *testing.T) {
store := newTestStore(t)
ctx := context.Background()
var keys [][]byte
want := map[string][]byte{}
for i := 0; i < 30; i++ {
key := make([]byte, 16)
rand.Read(key)
keys = append(keys, key)
if i%3 != 0 {
want[string(key)] = []byte(fmt.Sprintf("value-%d", i))
if err := store.KvPut(ctx, key, want[string(key)]); err != nil {
t.Fatal(err)
}
}
}
values, err := store.KvBatchGet(ctx, keys)
if err != nil {
t.Fatal(err)
}
if len(values) != len(want) {
t.Fatalf("%d values, want %d", len(values), len(want))
}
for key, value := range want {
if string(values[key]) != string(value) {
t.Fatalf("key %x: %q, want %q", key, values[key], value)
}
}
}
@@ -41,6 +41,14 @@ func (store *CassandraStore) KvGet(ctx context.Context, key []byte) (data []byte
return data, nil
}
// KvBatchGet runs the reads concurrently: CQL has no read of several
// partitions that is cheaper than one query each.
func (store *CassandraStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, store.KvGet, keys, kvBatchGetConcurrency)
}
const kvBatchGetConcurrency = 16
func (store *CassandraStore) KvDelete(ctx context.Context, key []byte) (err error) {
dir, name := genDirAndName(key)
@@ -42,6 +42,14 @@ func (store *Cassandra2Store) KvGet(ctx context.Context, key []byte) (data []byt
return data, nil
}
// KvBatchGet runs the reads concurrently: CQL has no read of several
// partitions that is cheaper than one query each.
func (store *Cassandra2Store) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, store.KvGet, keys, kvBatchGetConcurrency)
}
const kvBatchGetConcurrency = 16
func (store *Cassandra2Store) KvDelete(ctx context.Context, key []byte) (err error) {
dir, name := genDirAndName(key)
@@ -50,6 +50,15 @@ func (store *ElasticStore) KvGet(ctx context.Context, key []byte) (value []byte,
return value, filer.ErrKvNotFound
}
// KvBatchGet runs the reads concurrently. A multi-get sends the ids in its
// JSON body, which does not carry a key that is not UTF-8 the way the URL of
// KvGet and KvPut does.
func (store *ElasticStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, store.KvGet, keys, kvBatchGetConcurrency)
}
const kvBatchGetConcurrency = 16
func (store *ElasticStore) KvPut(ctx context.Context, key []byte, value []byte) (err error) {
esEntry := &ESKVEntry{value}
val, err := jsoniter.Marshal(esEntry)
@@ -0,0 +1,52 @@
//go:build elastic
package elastic
import (
"context"
"crypto/rand"
"fmt"
"os"
"testing"
elastic "github.com/olivere/elastic/v7"
)
func TestKvBatchGetReadsWhatKvGetReads(t *testing.T) {
url := os.Getenv("ELASTIC_URL")
if url == "" {
t.Skip("set ELASTIC_URL to an Elasticsearch server to run")
}
store := &ElasticStore{}
if err := store.initialize([]elastic.ClientOptionFunc{elastic.SetURL(url), elastic.SetSniff(false)}); err != nil {
t.Fatal(err)
}
ctx := context.Background()
keys := [][]byte{[]byte("plain-key")}
for i := 0; i < 20; i++ {
key := make([]byte, 17)
rand.Read(key)
keys = append(keys, key)
}
for i, key := range keys {
if i%3 != 2 {
if err := store.KvPut(ctx, key, []byte(fmt.Sprintf("value-%d", i))); err != nil {
t.Fatal(err)
}
}
}
values, err := store.KvBatchGet(ctx, keys)
if err != nil {
t.Fatal(err)
}
for i, key := range keys {
value, kvErr := store.KvGet(ctx, key)
if got, found := values[string(key)]; string(got) != string(value) || found != (kvErr == nil) {
t.Fatalf("key %d: batch read %q (found %v), KvGet read %q (%v)", i, got, found, value, kvErr)
}
}
if string(values["plain-key"]) != "value-0" {
t.Fatalf("plain-key: %q", values["plain-key"])
}
}
+29
View File
@@ -5,6 +5,7 @@ import (
"fmt"
"github.com/seaweedfs/seaweedfs/weed/filer"
clientv3 "go.etcd.io/etcd/client/v3"
)
// KvPut has no request deadline, like InsertEntry: the filer stores a hard-linked
@@ -38,6 +39,34 @@ func (store *EtcdStore) KvGet(ctx context.Context, key []byte) (value []byte, er
return resp.Kvs[0].Value, nil
}
// kvBatchGetSize keeps a transaction within etcd's default --max-txn-ops.
const kvBatchGetSize = 128
// KvBatchGet reads the keys with one read-only transaction per kvBatchGetSize.
func (store *EtcdStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
opCtx, cancel := store.withTimeout(ctx)
defer cancel()
values := make(map[string][]byte, len(keys))
for start := 0; start < len(keys); start += kvBatchGetSize {
batch := keys[start:min(start+kvBatchGetSize, len(keys))]
ops := make([]clientv3.Op, len(batch))
for i, key := range batch {
ops[i] = clientv3.OpGet(store.etcdKeyPrefix+string(key), atScanRevision(ctx)...)
}
resp, err := store.client.Txn(opCtx).Then(ops...).Commit()
if err != nil {
return nil, fmt.Errorf("kv batch get: %w", err)
}
for i, r := range resp.Responses {
if kvs := r.GetResponseRange().GetKvs(); len(kvs) > 0 {
values[string(batch[i])] = kvs[0].Value
}
}
}
return values, nil
}
func (store *EtcdStore) KvDelete(ctx context.Context, key []byte) (err error) {
opCtx, cancel := store.withTimeout(ctx)
defer cancel()
@@ -0,0 +1,65 @@
package etcd
import (
"context"
"fmt"
"os"
"testing"
"time"
)
func TestKvBatchGetReadsTheKeysHeld(t *testing.T) {
addr := os.Getenv("ETCD_ADDR")
if addr == "" {
t.Skip("set ETCD_ADDR to an etcd server to run")
}
store := &EtcdStore{etcdKeyPrefix: fmt.Sprintf("kvbatch%d/", time.Now().UnixNano()), timeout: 3 * time.Second}
if err := store.initialize(addr, "", "", 3*time.Second, nil); err != nil {
t.Fatal(err)
}
defer store.Shutdown()
ctx := context.Background()
var keys [][]byte
for i := 0; i < 300; i++ {
key := []byte(fmt.Sprintf("hardlink-%04d", i))
keys = append(keys, key)
if i%3 != 0 {
if err := store.KvPut(ctx, key, []byte(fmt.Sprintf("value-%d", i))); err != nil {
t.Fatal(err)
}
}
}
values, err := store.KvBatchGet(ctx, keys)
if err != nil {
t.Fatal(err)
}
if len(values) != 200 {
t.Fatalf("%d values, want 200", len(values))
}
for i := 0; i < 300; i++ {
value, found := values[fmt.Sprintf("hardlink-%04d", i)]
if i%3 == 0 {
if found {
t.Fatalf("key %d was never written but read %q", i, value)
}
} else if want := fmt.Sprintf("value-%d", i); string(value) != want {
t.Fatalf("key %d: %q, want %q", i, value, want)
}
}
rev, err := store.client.Get(ctx, store.etcdKeyPrefix+"hardlink-0001")
if err != nil {
t.Fatal(err)
}
if err := store.KvPut(ctx, keys[1], []byte("newer")); err != nil {
t.Fatal(err)
}
values, err = store.KvBatchGet(context.WithValue(ctx, scanRevisionKey{}, rev.Header.Revision), keys[1:3])
if err != nil {
t.Fatal(err)
}
if string(values["hardlink-0001"]) != "value-1" {
t.Fatalf("read %q at the scan revision, want value-1", values["hardlink-0001"])
}
}
+4
View File
@@ -671,6 +671,10 @@ func (s *versionedStore) KvGet(ctx context.Context, key []byte) ([]byte, error)
return value, err
}
func (s *versionedStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return KvGetEach(ctx, s.KvGet, keys, 1)
}
func (s *versionedStore) KvPut(ctx context.Context, key []byte, value []byte) error {
if txn := s.txn(ctx); txn != nil {
txn.keys[string(key)] = append([]byte{}, value...)
+65 -38
View File
@@ -14,9 +14,10 @@ import (
)
// 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.
// record of every hard-linked entry. The store is asked for the records of the
// waiting entries together; the caller of the listing must not be able to tell
// that from a listing that reads each record as its entry arrives, 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.
@@ -62,7 +63,7 @@ func (s *rowListingStore) ListDirectoryPrefixedEntries(ctx context.Context, dirP
}, eachEntryFunc)
}
// batchReadingStore also reads KV keys in batches.
// batchReadingStore also records the batches it is asked for.
type batchReadingStore struct {
*rowListingStore
batches [][]string // the keys of each batch it was asked for
@@ -89,9 +90,9 @@ func (s *batchReadingStore) KvBatchGet(_ context.Context, keys [][]byte) (map[st
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.
// linkListingStores returns the same directory in two stores, one to list with
// oneAtATime and one that records its 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) {
@@ -148,9 +149,31 @@ func see(entry *Entry) listed {
}
}
func listAll(t *testing.T, store FilerStore, dir string, startFileName string, limit int64) (entries []listed, lastFileName string) {
type lister func(ctx context.Context, dir util.FullPath, startFileName string, limit int64, each ListEachEntryFunc) (string, error)
// throughWrapper lists as the filer does.
func throughWrapper(store FilerStore) lister {
return func(ctx context.Context, dir util.FullPath, startFileName string, limit int64, each ListEachEntryFunc) (string, error) {
return NewFilerStoreWrapper(store).ListDirectoryEntries(ctx, dir, startFileName, false, limit, each)
}
}
// oneAtATime lists reading each record as its entry arrives, and hands the
// entry on before the store lists the next one.
func oneAtATime(store FilerStore) lister {
fsw := NewFilerStoreWrapper(store)
return func(ctx context.Context, dir util.FullPath, startFileName string, limit int64, each ListEachEntryFunc) (string, error) {
return store.ListDirectoryEntries(ctx, dir, startFileName, false, limit, func(entry *Entry) (bool, error) {
fsw.maybeReadHardLink(ctx, entry)
filer_pb.AfterEntryDeserialization(entry.GetChunks())
return each(entry)
})
}
}
func listAll(t *testing.T, list lister, 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) {
lastFileName, err := list(context.Background(), util.FullPath(dir), startFileName, limit, func(entry *Entry) (bool, error) {
entries = append(entries, see(entry))
return true, nil
})
@@ -175,8 +198,8 @@ func mixedDirectory(t *testing.T) func(store *stubFilerStore) {
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)
want, wantLast := listAll(t, oneAtATime(oneByOne), "/d", "", 100)
got, gotLast := listAll(t, throughWrapper(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")
@@ -227,8 +250,8 @@ func TestListingKeepsItsOrderAcrossBatches(t *testing.T) {
}
})
want, _ := listAll(t, oneByOne, "/d", "", names+1)
got, lastFileName := listAll(t, batched, "/d", "", names+1)
want, _ := listAll(t, oneAtATime(oneByOne), "/d", "", names+1)
got, lastFileName := listAll(t, throughWrapper(batched), "/d", "", names+1)
require.Len(t, got, names)
require.Equal(t, want, got)
@@ -244,7 +267,7 @@ func TestListingKeepsItsOrderAcrossBatches(t *testing.T) {
const pageSize = hardLinkBatchSize + 100
var paged []listed
for start := ""; ; {
page, last := listAll(t, batched, "/d", start, pageSize)
page, last := listAll(t, throughWrapper(batched), "/d", start, pageSize)
paged = append(paged, page...)
if len(page) < pageSize {
break
@@ -260,7 +283,7 @@ func TestListingKeepsItsOrderAcrossBatches(t *testing.T) {
// 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)
want, _ := listAll(t, oneAtATime(oneByOne), "/d", "", 100)
for stopAt := 1; stopAt <= len(want); stopAt++ {
var got []listed
@@ -272,7 +295,7 @@ func TestListingEndedByItsCallerContinuesFromWhereItEnded(t *testing.T) {
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)
rest, _ := listAll(t, throughWrapper(batched), "/d", lastFileName, 100)
require.Equal(t, want[stopAt:], append([]listed{}, rest...), "continued after entry %d", stopAt)
}
}
@@ -297,13 +320,13 @@ func TestListingReturnsItsCallersError(t *testing.T) {
}
}
// The records are then read one at a time, as from a store without batches.
// The records are then read one at a time.
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)
want, _ := listAll(t, oneAtATime(oneByOne), "/d", "", 100)
got, _ := listAll(t, throughWrapper(batched), "/d", "", 100)
require.Equal(t, want, got)
require.Equal(t, 4, *batchedReads)
@@ -315,7 +338,7 @@ func TestListingReadsRecordsOneByOneWhenTheBatchFails(t *testing.T) {
func TestListingHandsOnWhatTheStoreListedBeforeItFailed(t *testing.T) {
oneByOne, _, batched, _ := linkListingStores(t, mixedDirectory(t))
broken := errors.New("iterator closed")
want, _ := listAll(t, oneByOne, "/d", "", 100)
want, _ := listAll(t, oneAtATime(oneByOne), "/d", "", 100)
for failAfter := 0; failAfter <= 6; failAfter++ {
batched.failAfter, batched.listErr = failAfter, broken
@@ -330,8 +353,8 @@ func TestListingHandsOnWhatTheStoreListedBeforeItFailed(t *testing.T) {
}
// 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) {
func listUntil(list lister, dir string, stopAt int) (entries []listed, lastFileName string, err error) {
lastFileName, err = list(context.Background(), util.FullPath(dir), "", 100000, func(entry *Entry) (bool, error) {
entries = append(entries, see(entry))
return len(entries) < stopAt, nil
})
@@ -344,17 +367,17 @@ func listUntil(store FilerStore, dir string, stopAt int) (entries []listed, last
// 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)
want, _ := listAll(t, oneAtATime(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)
_, _, err := listUntil(oneAtATime(oneByOne), "/d", stopAt)
require.NoError(t, err, "one at a time, ended at entry %d", stopAt)
got, lastFileName, err := listUntil(batched, "/d", stopAt)
got, lastFileName, err := listUntil(throughWrapper(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)
@@ -392,8 +415,8 @@ func TestListingEndedByItsCallerIsNotFailedByTheStoresStepBehind(t *testing.T) {
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)
want, wantLast, wantErr := listUntil(oneAtATime(oneByOne), "/d", stopAt)
got, gotLast, gotErr := listUntil(throughWrapper(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)
@@ -404,17 +427,18 @@ func TestListingEndedByItsCallerIsNotFailedByTheStoresStepBehind(t *testing.T) {
}
}
// 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) {
// The records are in the default store, and a directory another store lists
// reads them from there together too.
func TestListingOfAPathSpecificStoreReadsRecordsTogether(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"),
for _, name := range []string{"/d/m", "/d/n"} {
other.entries[name] = &Entry{
FullPath: util.FullPath(name),
Attr: Attr{Mode: 0o644},
HardLinkId: HardLinkId("link-x-0123456789"),
}
}
wrapper := NewFilerStoreWrapper(batched)
wrapper.AddPathSpecificStore("/other/", "other", other)
@@ -426,9 +450,12 @@ func TestListingOfAPathSpecificStoreReadsRecordsOneByOne(t *testing.T) {
})
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)
linked := listed{Size: 11, Mode: 0o600, Links: 2, Chunks: "7,0b"}
m, n := linked, linked
m.Name, n.Name = "m", "n"
require.Equal(t, []listed{m, n}, got)
require.Zero(t, *batchedReads)
require.Equal(t, [][]string{{"link-x-0123456789"}}, batched.batches)
}
func namesOf(entries []listed) (names []string) {
+4
View File
@@ -107,6 +107,10 @@ func (s *stubFilerStore) KvGet(_ context.Context, key []byte) ([]byte, error) {
}
return append([]byte(nil), value...), nil
}
func (s *stubFilerStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return KvGetEach(ctx, s.KvGet, keys, 1)
}
func (s *stubFilerStore) KvDelete(_ context.Context, key []byte) error {
s.mu.Lock()
defer s.mu.Unlock()
+3
View File
@@ -39,6 +39,9 @@ func (s *bucketTrackingStore) KvPut(context.Context, []byte, []byte) error { ret
func (s *bucketTrackingStore) KvGet(context.Context, []byte) ([]byte, error) {
return nil, ErrKvNotFound
}
func (s *bucketTrackingStore) KvBatchGet(context.Context, [][]byte) (map[string][]byte, error) {
return map[string][]byte{}, nil
}
func (s *bucketTrackingStore) KvDelete(context.Context, []byte) error { return nil }
func (s *bucketTrackingStore) Shutdown() {}
func (s *bucketTrackingStore) OnBucketCreation(bucket string) { s.created = append(s.created, bucket) }
+46 -13
View File
@@ -4,8 +4,10 @@ import (
"context"
"errors"
"io"
"sync"
"github.com/seaweedfs/seaweedfs/weed/util"
"golang.org/x/sync/errgroup"
)
const CountEntryChunksForGzip = 50
@@ -44,11 +46,55 @@ type FilerStore interface {
KvPut(ctx context.Context, key []byte, value []byte) (err error)
KvGet(ctx context.Context, key []byte) (value []byte, err error)
// 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)
KvDelete(ctx context.Context, key []byte) (err error)
Shutdown()
}
// KvGetEach reads the keys with kvGet, up to concurrency of them at a time,
// for a store without a batch read of its own. A key not found is left out.
func KvGetEach(ctx context.Context, kvGet func(context.Context, []byte) ([]byte, error), keys [][]byte, concurrency int) (map[string][]byte, error) {
values := make(map[string][]byte, len(keys))
if concurrency <= 1 {
for _, key := range keys {
value, err := kvGet(ctx, key)
if errors.Is(err, ErrKvNotFound) {
continue
}
if err != nil {
return nil, err
}
values[string(key)] = value
}
return values, nil
}
var mu sync.Mutex
g, gCtx := errgroup.WithContext(ctx)
g.SetLimit(concurrency)
for _, key := range keys {
g.Go(func() error {
value, err := kvGet(gCtx, key)
if errors.Is(err, ErrKvNotFound) {
return nil
}
if err != nil {
return err
}
mu.Lock()
values[string(key)] = value
mu.Unlock()
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err
}
return values, nil
}
// ErrUnsupportedEntryScan is returned by EntryScanner.ScanEntries, before
// any entry is visited, when the store cannot serve the scan.
var ErrUnsupportedEntryScan = errors.New("entry scan not supported by this filer store")
@@ -72,19 +118,6 @@ 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)
+13 -25
View File
@@ -467,36 +467,27 @@ const hardLinkBatchSize = 256
// 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.
// files. Instead the entries from the first hard-linked one on wait, up to
// hardLinkBatchSize of them, and their records are read together with
// KvBatchGet. Every store's listing hands over an *Entry of its own for each
// name, so the entries can wait. The caller gets them in the order the store
// lists them.
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
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
func (fsw *FilerStoreWrapper) newHardLinkListing(ctx context.Context, eachEntryFunc ListEachEntryFunc) *hardLinkListing {
return &hardLinkListing{fsw: fsw, ctx: ctx, each: eachEntryFunc}
}
// 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)
}
@@ -523,14 +514,14 @@ func (l *hardLinkListing) release() (bool, error) {
keys = append(keys, entry.HardLinkId)
}
}
records, batchErr := l.reader.KvBatchGet(l.ctx, keys)
records, batchErr := l.fsw.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
// one at a time
l.fsw.maybeReadHardLink(l.ctx, entry)
} else if record, found := records[string(entry.HardLinkId)]; found {
if err := entry.DecodeAttributesAndChunks(record); err != nil {
@@ -567,9 +558,6 @@ func (l *hardLinkListing) handOn(entry *Entry) (bool, error) {
// 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
+55
View File
@@ -0,0 +1,55 @@
package filer
import (
"context"
"errors"
"sync/atomic"
"testing"
)
func TestKvGetEachLeavesOutMissingKeys(t *testing.T) {
held := map[string][]byte{"a": []byte("1"), "c": []byte("3")}
var running, most atomic.Int32
kvGet := func(_ context.Context, key []byte) ([]byte, error) {
n := running.Add(1)
defer running.Add(-1)
for {
m := most.Load()
if n <= m || most.CompareAndSwap(m, n) {
break
}
}
if v, ok := held[string(key)]; ok {
return v, nil
}
return nil, ErrKvNotFound
}
for _, concurrency := range []int32{1, 2} {
most.Store(0)
values, err := KvGetEach(context.Background(), kvGet, [][]byte{[]byte("a"), []byte("b"), []byte("c"), []byte("a")}, int(concurrency))
if err != nil {
t.Fatal(err)
}
if len(values) != 2 || string(values["a"]) != "1" || string(values["c"]) != "3" {
t.Fatalf("concurrency %d: values = %q", concurrency, values)
}
if most.Load() > concurrency {
t.Fatalf("%d reads at a time, want at most %d", most.Load(), concurrency)
}
}
}
func TestKvGetEachFailsOnAReadError(t *testing.T) {
failure := errors.New("store down")
kvGet := func(_ context.Context, key []byte) ([]byte, error) {
if string(key) == "b" {
return nil, failure
}
return key, nil
}
for _, concurrency := range []int{1, 2} {
if _, err := KvGetEach(context.Background(), kvGet, [][]byte{[]byte("a"), []byte("b")}, concurrency); !errors.Is(err, failure) {
t.Fatalf("concurrency %d: err = %v, want %v", concurrency, err, failure)
}
}
}
+4
View File
@@ -154,6 +154,10 @@ func (t *FilerStorePathTranslator) KvPut(ctx context.Context, key []byte, value
func (t *FilerStorePathTranslator) KvGet(ctx context.Context, key []byte) (value []byte, err error) {
return t.actualStore.KvGet(ctx, key)
}
func (t *FilerStorePathTranslator) KvBatchGet(ctx context.Context, keys [][]byte) (values map[string][]byte, err error) {
return t.actualStore.KvBatchGet(ctx, keys)
}
func (t *FilerStorePathTranslator) KvDelete(ctx context.Context, key []byte) (err error) {
return t.actualStore.KvDelete(ctx, key)
}
+6 -2
View File
@@ -389,7 +389,7 @@ 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)
listing := fsw.newHardLinkListing(ctx, eachEntryFunc)
defer func() {
lastFileName, err = listing.finish(lastFileName, err)
}()
@@ -411,7 +411,7 @@ func (fsw *FilerStoreWrapper) ListDirectoryPrefixedEntries(ctx context.Context,
if limit > math.MaxInt32-1 {
limit = math.MaxInt32 - 1
}
listing := fsw.newHardLinkListing(ctx, actualStore, eachEntryFunc)
listing := fsw.newHardLinkListing(ctx, eachEntryFunc)
defer func() {
lastFileName, err = listing.finish(lastFileName, err)
}()
@@ -569,6 +569,10 @@ func (fsw *FilerStoreWrapper) KvGet(ctx context.Context, key []byte) (value []by
ctx = context.WithoutCancel(ctx)
return fsw.getDefaultStore().KvGet(ctx, key)
}
func (fsw *FilerStoreWrapper) KvBatchGet(ctx context.Context, keys [][]byte) (values map[string][]byte, err error) {
ctx = context.WithoutCancel(ctx)
return fsw.getDefaultStore().KvBatchGet(ctx, keys)
}
func (fsw *FilerStoreWrapper) KvDelete(ctx context.Context, key []byte) (err error) {
if err := ctx.Err(); err != nil {
return err
@@ -766,6 +766,39 @@ func (store *FoundationDBStore) KvGet(ctx context.Context, key []byte) ([]byte,
return data, nil
}
// KvBatchGet issues every read of one transaction before it waits for any.
func (store *FoundationDBStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
read := func(rtr fdb.ReadTransaction) (interface{}, error) {
futures := make([]fdb.FutureByteSlice, len(keys))
for i, key := range keys {
futures[i] = rtr.Get(store.kvDir.Pack(tuple.Tuple{key}))
}
values := make(map[string][]byte, len(keys))
for i, future := range futures {
data, err := future.Get()
if err != nil {
return nil, err
}
if data != nil {
values[string(keys[i])] = data
}
}
return values, nil
}
var result interface{}
var err error
if tx, exists := store.getTransactionFromContext(ctx); exists {
result, err = read(tx)
} else {
result, err = store.database.ReadTransact(read)
}
if err != nil {
return nil, fmt.Errorf("kv batch get: %w", err)
}
return result.(map[string][]byte), nil
}
func (store *FoundationDBStore) KvDelete(ctx context.Context, key []byte) error {
fdbKey := store.kvDir.Pack(tuple.Tuple{key})
@@ -0,0 +1,72 @@
//go:build foundationdb
package foundationdb
import (
"context"
"fmt"
"os"
"testing"
"time"
)
func TestKvBatchGetReadsTheKeysHeld(t *testing.T) {
clusterFile := getTestClusterFile()
if _, err := os.Stat(clusterFile); os.IsNotExist(err) {
t.Skip("FoundationDB cluster file not found, skipping")
}
store := &FoundationDBStore{}
if err := store.initialize(clusterFile, 740); err != nil {
t.Skipf("Failed to initialize FoundationDB store: %v", err)
}
defer store.Shutdown()
ctx := context.Background()
prefix := fmt.Sprintf("kvbatch-%d-", time.Now().UnixNano())
var keys [][]byte
for i := 0; i < 50; i++ {
key := []byte(fmt.Sprintf("%s%02d", prefix, i))
keys = append(keys, key)
if i%3 != 0 {
if err := store.KvPut(ctx, key, []byte(fmt.Sprintf("value-%d", i))); err != nil {
t.Fatal(err)
}
}
}
check := func(values map[string][]byte, rewritten string) {
t.Helper()
for i := 0; i < 50; i++ {
value, found := values[fmt.Sprintf("%s%02d", prefix, i)]
want := fmt.Sprintf("value-%d", i)
if i == 1 && rewritten != "" {
want = rewritten
}
if i%3 == 0 {
if found {
t.Fatalf("key %d was never written but read %q", i, value)
}
} else if string(value) != want {
t.Fatalf("key %d: %q, want %q", i, value, want)
}
}
}
values, err := store.KvBatchGet(ctx, keys)
if err != nil {
t.Fatal(err)
}
check(values, "")
txCtx, err := store.BeginTransaction(ctx)
if err != nil {
t.Fatal(err)
}
defer store.RollbackTransaction(txCtx)
if err := store.KvPut(txCtx, keys[1], []byte("in transaction")); err != nil {
t.Fatal(err)
}
if values, err = store.KvBatchGet(txCtx, keys); err != nil {
t.Fatal(err)
}
check(values, "in transaction")
}
+8
View File
@@ -20,6 +20,14 @@ func (store *HbaseStore) KvGet(ctx context.Context, key []byte) (value []byte, e
return store.doGet(ctx, store.cfKv, key)
}
// KvBatchGet runs the reads concurrently; the client sends the ones bound for
// one region server together.
func (store *HbaseStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, store.KvGet, keys, kvBatchGetConcurrency)
}
const kvBatchGetConcurrency = 16
func (store *HbaseStore) KvDelete(ctx context.Context, key []byte) (err error) {
return store.doDelete(ctx, store.cfKv, key)
}
+5
View File
@@ -50,6 +50,11 @@ func (store *LevelDBStore) VisitKvPrefix(ctx context.Context, prefix []byte, vis
return iter.Error()
}
// KvBatchGet reads the keys one at a time: the reads are local.
func (store *LevelDBStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, store.KvGet, keys, 1)
}
func (store *LevelDBStore) KvDelete(ctx context.Context, key []byte) (err error) {
err = store.db.Delete(key, nil)
+5
View File
@@ -38,6 +38,11 @@ func (store *LevelDB2Store) KvGet(ctx context.Context, key []byte) (value []byte
return
}
// KvBatchGet reads the keys one at a time: the reads are local.
func (store *LevelDB2Store) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, store.KvGet, keys, 1)
}
func (store *LevelDB2Store) KvDelete(ctx context.Context, key []byte) (err error) {
partitionId := bucketKvKey(key, store.dbCount)
+5
View File
@@ -34,6 +34,11 @@ func (store *LevelDB3Store) KvGet(ctx context.Context, key []byte) (value []byte
return
}
// KvBatchGet reads the keys one at a time: the reads are local.
func (store *LevelDB3Store) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, store.KvGet, keys, 1)
}
func (store *LevelDB3Store) KvDelete(ctx context.Context, key []byte) (err error) {
err = store.dbs[DEFAULT].Delete(key, nil)
+36
View File
@@ -56,6 +56,42 @@ func (store *MongodbStore) KvGet(ctx context.Context, key []byte) (value []byte,
return data.Meta, nil
}
func (store *MongodbStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
values := make(map[string][]byte, len(keys))
if len(keys) == 0 {
return values, nil
}
asked := make(map[[2]string][]string, len(keys))
match := make([]bson.M, 0, len(keys))
for _, key := range keys {
dir, name := genDirAndName(key)
pair := [2]string{dir, name}
asked[pair] = append(asked[pair], string(key))
match = append(match, bson.M{"directory": dir, "name": name})
}
cur, err := store.connect.Database(store.database).Collection(store.collectionName).Find(ctx, bson.M{"$or": match})
if err != nil {
return nil, fmt.Errorf("kv batch get: %w", err)
}
defer cur.Close(ctx)
for cur.Next(ctx) {
var data Model
if err := cur.Decode(&data); err != nil {
return nil, fmt.Errorf("kv batch get: %w", err)
}
if len(data.Meta) == 0 {
continue
}
for _, key := range asked[[2]string{data.Directory, data.Name}] {
values[key] = data.Meta
}
}
if err := cur.Err(); err != nil {
return nil, fmt.Errorf("kv batch get: %w", err)
}
return values, nil
}
func (store *MongodbStore) KvDelete(ctx context.Context, key []byte) (err error) {
dir, name := genDirAndName(key)
@@ -0,0 +1,56 @@
package mongodb
import (
"context"
"crypto/rand"
"fmt"
"os"
"testing"
"time"
)
func TestKvBatchGetReadsTheKeysHeld(t *testing.T) {
uri := os.Getenv("MONGODB_URI")
if uri == "" {
t.Skip("set MONGODB_URI to a MongoDB server to run")
}
store := &MongodbStore{database: "seaweedfs_test", collectionName: fmt.Sprintf("kvbatch%d", time.Now().UnixNano())}
if err := store.connection(uri, 4, false, "", "", "", "", "", false); err != nil {
t.Fatal(err)
}
ctx := context.Background()
defer store.connect.Database(store.database).Collection(store.collectionName).Drop(ctx)
var keys [][]byte
want := map[string][]byte{}
for i := 0; i < 50; i++ {
key := make([]byte, 16)
rand.Read(key)
keys = append(keys, key)
if i%3 != 0 {
want[string(key)] = []byte(fmt.Sprintf("value-%d", i))
if err := store.KvPut(ctx, key, want[string(key)]); err != nil {
t.Fatal(err)
}
}
}
if err := store.KvPut(ctx, []byte("short"), []byte("s")); err != nil {
t.Fatal(err)
}
want["short"] = []byte("s")
want["short\x00"] = []byte("s")
keys = append(keys, []byte("short"), []byte("short\x00"))
values, err := store.KvBatchGet(ctx, keys)
if err != nil {
t.Fatal(err)
}
if len(values) != len(want) {
t.Fatalf("%d values, want %d", len(values), len(want))
}
for key, value := range want {
if string(values[key]) != string(value) {
t.Fatalf("key %x: %q, want %q", key, values[key], value)
}
}
}
+8
View File
@@ -2,6 +2,7 @@ package mysql
import (
"fmt"
"strings"
_ "github.com/go-sql-driver/mysql"
"github.com/seaweedfs/seaweedfs/weed/filer/abstract_sql"
@@ -46,6 +47,13 @@ func (gen *SqlGenMysql) GetSqlFind(tableName string) string {
return fmt.Sprintf("SELECT `meta` FROM `%s` WHERE `dirhash` = ? AND `name` = ? AND `directory` = ?", tableName)
}
// GetSqlFindBatch matches each row by equality, which MySQL turns into one
// primary-key lookup per key.
func (gen *SqlGenMysql) GetSqlFindBatch(tableName string, count int) string {
match := strings.TrimSuffix(strings.Repeat("(`dirhash` = ? AND `name` = ? AND `directory` = ?) OR ", count), " OR ")
return fmt.Sprintf("SELECT `dirhash`, `name`, `directory`, `meta` FROM `%s` WHERE %s", tableName, match)
}
func (gen *SqlGenMysql) GetSqlDelete(tableName string) string {
return fmt.Sprintf("DELETE FROM `%s` WHERE `dirhash` = ? AND `name` = ? AND `directory` = ?", tableName)
}
+9
View File
@@ -2,6 +2,7 @@ package postgres
import (
"fmt"
"strings"
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/seaweedfs/seaweedfs/weed/filer/abstract_sql"
@@ -59,6 +60,14 @@ func (gen *SqlGenPostgres) GetSqlFind(tableName string) string {
return fmt.Sprintf(`SELECT meta FROM "%s" WHERE dirhash=$1 AND name=$2 AND directory=$3`, tableName)
}
func (gen *SqlGenPostgres) GetSqlFindBatch(tableName string, count int) string {
rows := make([]string, count)
for i := range rows {
rows[i] = fmt.Sprintf("($%d,$%d,$%d)", 3*i+1, 3*i+2, 3*i+3)
}
return fmt.Sprintf(`SELECT dirhash, name, directory, meta FROM "%s" WHERE (dirhash, name, directory) IN (%s)`, tableName, strings.Join(rows, ","))
}
func (gen *SqlGenPostgres) GetSqlDelete(tableName string) string {
return fmt.Sprintf(`DELETE FROM "%s" WHERE dirhash=$1 AND name=$2 AND directory=$3`, tableName)
}
@@ -30,6 +30,33 @@ func (store *UniversalRedisStore) KvGet(ctx context.Context, key []byte) (value
return []byte(data), err
}
// KvBatchGet sends the reads in one pipeline, which a cluster client splits
// by node, where MGET would fail across slots.
func (store *UniversalRedisStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
cmds := make([]*redis.StringCmd, len(keys))
_, err := store.Client.Pipelined(ctx, func(pipe redis.Pipeliner) error {
for i, key := range keys {
cmds[i] = pipe.Get(ctx, string(key))
}
return nil
})
if err != nil && err != redis.Nil {
return nil, fmt.Errorf("kv batch get: %w", err)
}
values := make(map[string][]byte, len(keys))
for i, cmd := range cmds {
value, err := cmd.Bytes()
if err == redis.Nil {
continue
}
if err != nil {
return nil, fmt.Errorf("kv batch get: %w", err)
}
values[string(keys[i])] = value
}
return values, nil
}
func (store *UniversalRedisStore) KvDelete(ctx context.Context, key []byte) (err error) {
_, err = store.Client.Del(ctx, string(key)).Result()
@@ -0,0 +1,26 @@
package redis
import (
"context"
"fmt"
"testing"
)
func TestKvBatchGetReadsTheKeysHeld(t *testing.T) {
store, dir := newTestStore(t)
ctx := context.Background()
held := []byte(string(dir) + "/held")
missing := []byte(string(dir) + "/missing")
t.Cleanup(func() { _ = store.KvDelete(ctx, held) })
if err := store.KvPut(ctx, held, []byte("value")); err != nil {
t.Fatal(err)
}
values, err := store.KvBatchGet(ctx, [][]byte{held, missing, held})
if err != nil {
t.Fatal(err)
}
if got := fmt.Sprintf("%q", values); got != fmt.Sprintf("%q", map[string][]byte{string(held): []byte("value")}) {
t.Fatalf("values = %s", got)
}
}
@@ -30,6 +30,33 @@ func (store *UniversalRedis2Store) KvGet(ctx context.Context, key []byte) (value
return []byte(data), err
}
// KvBatchGet sends the reads in one pipeline, which a cluster client splits
// by node, where MGET would fail across slots.
func (store *UniversalRedis2Store) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
cmds := make([]*redis.StringCmd, len(keys))
_, err := store.Client.Pipelined(ctx, func(pipe redis.Pipeliner) error {
for i, key := range keys {
cmds[i] = pipe.Get(ctx, store.getKey(string(key)))
}
return nil
})
if err != nil && err != redis.Nil {
return nil, fmt.Errorf("kv batch get: %w", err)
}
values := make(map[string][]byte, len(keys))
for i, cmd := range cmds {
value, err := cmd.Bytes()
if err == redis.Nil {
continue
}
if err != nil {
return nil, fmt.Errorf("kv batch get: %w", err)
}
values[string(keys[i])] = value
}
return values, nil
}
func (store *UniversalRedis2Store) KvDelete(ctx context.Context, key []byte) (err error) {
_, err = store.Client.Del(ctx, store.getKey(string(key))).Result()
@@ -0,0 +1,26 @@
package redis2
import (
"context"
"fmt"
"testing"
)
func TestKvBatchGetReadsTheKeysHeld(t *testing.T) {
store, dir := newTestStore(t, "kvbatch:")
ctx := context.Background()
held := []byte(string(dir) + "/held")
missing := []byte(string(dir) + "/missing")
t.Cleanup(func() { _ = store.KvDelete(ctx, held) })
if err := store.KvPut(ctx, held, []byte("value")); err != nil {
t.Fatal(err)
}
values, err := store.KvBatchGet(ctx, [][]byte{held, missing, held})
if err != nil {
t.Fatal(err)
}
if got := fmt.Sprintf("%q", values); got != fmt.Sprintf("%q", map[string][]byte{string(held): []byte("value")}) {
t.Fatalf("values = %s", got)
}
}
@@ -30,6 +30,33 @@ func (store *UniversalRedis3Store) KvGet(ctx context.Context, key []byte) (value
return []byte(data), err
}
// KvBatchGet sends the reads in one pipeline, which a cluster client splits
// by node, where MGET would fail across slots.
func (store *UniversalRedis3Store) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
cmds := make([]*redis.StringCmd, len(keys))
_, err := store.Client.Pipelined(ctx, func(pipe redis.Pipeliner) error {
for i, key := range keys {
cmds[i] = pipe.Get(ctx, store.getKey(string(key)))
}
return nil
})
if err != nil && err != redis.Nil {
return nil, fmt.Errorf("kv batch get: %w", err)
}
values := make(map[string][]byte, len(keys))
for i, cmd := range cmds {
value, err := cmd.Bytes()
if err == redis.Nil {
continue
}
if err != nil {
return nil, fmt.Errorf("kv batch get: %w", err)
}
values[string(keys[i])] = value
}
return values, nil
}
func (store *UniversalRedis3Store) KvDelete(ctx context.Context, key []byte) (err error) {
_, err = store.Client.Del(ctx, store.getKey(string(key))).Result()
@@ -0,0 +1,26 @@
package redis3
import (
"context"
"fmt"
"testing"
)
func TestKvBatchGetReadsTheKeysHeld(t *testing.T) {
store, dir := newTestStore(t)
ctx := context.Background()
held := []byte(string(dir) + "/held")
missing := []byte(string(dir) + "/missing")
t.Cleanup(func() { _ = store.KvDelete(ctx, held) })
if err := store.KvPut(ctx, held, []byte("value")); err != nil {
t.Fatal(err)
}
values, err := store.KvBatchGet(ctx, [][]byte{held, missing, held})
if err != nil {
t.Fatal(err)
}
if got := fmt.Sprintf("%q", values); got != fmt.Sprintf("%q", map[string][]byte{string(held): []byte("value")}) {
t.Fatalf("values = %s", got)
}
}
+5
View File
@@ -36,6 +36,11 @@ func (store *RocksDBStore) KvGet(ctx context.Context, key []byte) (value []byte,
return
}
// KvBatchGet reads the keys one at a time: the reads are local.
func (store *RocksDBStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, store.KvGet, keys, 1)
}
func (store *RocksDBStore) KvDelete(ctx context.Context, key []byte) (err error) {
err = store.db.Delete(store.wo, key)
@@ -0,0 +1,56 @@
//go:build (linux || darwin || windows) && sqlite
package sqlite
import (
"context"
"fmt"
"path/filepath"
"testing"
)
func TestKvBatchGetReadsTheKeysHeld(t *testing.T) {
store := &SqliteStore{}
if err := store.initialize(filepath.Join(t.TempDir(), "filer.db"), createTableSql, upsertQuerySql); err != nil {
t.Fatal(err)
}
defer store.Shutdown()
ctx := context.Background()
var keys [][]byte
for i := 0; i < 600; i++ {
key := []byte(fmt.Sprintf("hardlink-%08d", i))
keys = append(keys, key)
if i%3 == 0 {
continue
}
if err := store.KvPut(ctx, key, []byte(fmt.Sprintf("value-%d", i))); err != nil {
t.Fatal(err)
}
}
if err := store.KvPut(ctx, []byte("short"), []byte("s")); err != nil {
t.Fatal(err)
}
keys = append(keys, []byte("short"), []byte("short\x00"), []byte("missing"))
values, err := store.KvBatchGet(ctx, keys)
if err != nil {
t.Fatal(err)
}
if len(values) != 402 {
t.Fatalf("%d values, want 402", len(values))
}
for i := 0; i < 600; i++ {
value, found := values[fmt.Sprintf("hardlink-%08d", i)]
if i%3 == 0 {
if found {
t.Fatalf("key %d was never written but read %q", i, value)
}
} else if want := fmt.Sprintf("value-%d", i); string(value) != want {
t.Fatalf("key %d: %q, want %q", i, value, want)
}
}
if string(values["short"]) != "s" || string(values["short\x00"]) != "s" {
t.Fatalf("short keys: %q %q", values["short"], values["short\x00"])
}
}
+40 -8
View File
@@ -4,11 +4,13 @@ package tarantool
import (
"context"
"errors"
"fmt"
"reflect"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/tarantool/go-option"
"github.com/tarantool/go-tarantool/v3"
"github.com/tarantool/go-tarantool/v3/crud"
"github.com/tarantool/go-tarantool/v3/pool"
)
@@ -42,6 +44,41 @@ func (store *TarantoolStore) KvPut(ctx context.Context, key []byte, value []byte
func (store *TarantoolStore) KvGet(ctx context.Context, key []byte) (value []byte, err error) {
resp := crud.Result{}
err = store.pool.Do(kvGetRequest(ctx, key), pool.ModePreferRO).GetTyped(&resp)
if err != nil {
return nil, err
}
return kvGetValue(resp)
}
// KvBatchGet sends every read before it waits for any.
func (store *TarantoolStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
futures := make([]tarantool.Future, len(keys))
for i, key := range keys {
futures[i] = store.pool.Do(kvGetRequest(ctx, key), pool.ModePreferRO)
}
values := make(map[string][]byte, len(keys))
for i, future := range futures {
resp := crud.Result{}
if err := future.GetTyped(&resp); err != nil {
return nil, err
}
value, err := kvGetValue(resp)
if errors.Is(err, filer.ErrKvNotFound) {
continue
}
if err != nil {
return nil, err
}
values[string(keys[i])] = value
}
return values, nil
}
func kvGetRequest(ctx context.Context, key []byte) crud.GetRequest {
getOpts := crud.GetOpts{
Fields: option.SomeAny([]interface{}{"value"}),
Mode: option.SomeString("read"),
@@ -49,18 +86,13 @@ func (store *TarantoolStore) KvGet(ctx context.Context, key []byte) (value []byt
Balance: option.SomeBool(true),
}
req := crud.NewGetRequest(tarantoolKVSpaceName).
return crud.NewGetRequest(tarantoolKVSpaceName).
Key([]interface{}{string(key)}).
Opts(getOpts).
Context(ctx)
}
resp := crud.Result{}
err = store.pool.Do(req, pool.ModePreferRO).GetTyped(&resp)
if err != nil {
return nil, err
}
func kvGetValue(resp crud.Result) ([]byte, error) {
results, ok := resp.Rows.([]interface{})
if !ok || len(results) != 1 {
return nil, filer.ErrKvNotFound
@@ -0,0 +1,53 @@
//go:build tarantool
package tarantool
import (
"context"
"fmt"
"os"
"testing"
"time"
)
func TestKvBatchGetReadsTheKeysHeld(t *testing.T) {
if os.Getenv("RUN_TARANTOOL_TESTS") != "1" {
t.Skip("Tarantool tests are disabled. Set RUN_TARANTOOL_TESTS=1 to enable.")
}
store := &TarantoolStore{}
if err := store.initialize([]string{"127.0.0.1:3303"}, "client", "client", 5*time.Second); err != nil {
t.Fatal(err)
}
defer store.Shutdown()
ctx := context.Background()
prefix := fmt.Sprintf("kvbatch-%d-", time.Now().UnixNano())
var keys [][]byte
for i := 0; i < 30; i++ {
key := []byte(fmt.Sprintf("%s%02d", prefix, i))
keys = append(keys, key)
if i%3 != 0 {
if err := store.KvPut(ctx, key, []byte(fmt.Sprintf("value-%d", i))); err != nil {
t.Fatal(err)
}
defer store.KvDelete(ctx, key)
}
}
values, err := store.KvBatchGet(ctx, keys)
if err != nil {
t.Fatal(err)
}
if len(values) != 20 {
t.Fatalf("%d values, want 20", len(values))
}
for i := 0; i < 30; i++ {
value, found := values[fmt.Sprintf("%s%02d", prefix, i)]
if i%3 == 0 {
if found {
t.Fatalf("key %d was never written but read %q", i, value)
}
} else if want := fmt.Sprintf("value-%d", i); string(value) != want {
t.Fatalf("key %d: %q, want %q", i, value, want)
}
}
}
-2
View File
@@ -49,8 +49,6 @@ func (store *TikvStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[stri
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)
+32 -6
View File
@@ -3,6 +3,7 @@
package tikv
import (
"bytes"
"context"
"fmt"
"reflect"
@@ -20,20 +21,41 @@ import (
"github.com/seaweedfs/seaweedfs/weed/util"
)
// kvRequests counts the requests the store sends to TiKV, by kind.
// kvRequests counts the requests the store sends to TiKV, by kind: all of
// them, or with keyPrefix set, those that read a key with that prefix.
type kvRequests struct {
tikv.Client
mu sync.Mutex
sent map[tikvrpc.CmdType]int
mu sync.Mutex
sent map[tikvrpc.CmdType]int
keyPrefix []byte
}
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]++
if r.reads(req) {
r.sent[req.Type]++
}
r.mu.Unlock()
return r.Client.SendRequest(ctx, addr, req, timeout)
}
func (r *kvRequests) reads(req *tikvrpc.Request) bool {
if r.keyPrefix == nil {
return true
}
switch req.Type {
case tikvrpc.CmdGet:
return bytes.HasPrefix(req.Get().GetKey(), r.keyPrefix)
case tikvrpc.CmdBatchGet:
for _, key := range req.BatchGet().GetKeys() {
if bytes.HasPrefix(key, r.keyPrefix) {
return true
}
}
}
return false
}
// during runs f and returns the gets and batch gets it sent.
func (r *kvRequests) during(f func()) (gets, batchGets int) {
r.mu.Lock()
@@ -113,10 +135,13 @@ func TestKvBatchGetReadsItsKeysInOneRequest(t *testing.T) {
}
}
// oneByOne hides the store's batch read, which leaves a listing to read each
// hard link record as its entry arrives.
// oneByOne serves a batch read with a get for each key.
type oneByOne struct{ filer.FilerStore }
func (s oneByOne) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, s.KvGet, keys, 1)
}
// A page of hard-linked names costs one request for their records, where it
// cost one for each name.
func TestListingReadsTheHardLinkRecordsOfAPageInOneRequest(t *testing.T) {
@@ -137,6 +162,7 @@ func TestListingReadsTheHardLinkRecordsOfAPageInOneRequest(t *testing.T) {
}
}
requests.keyPrefix = []byte("link-")
type seen struct {
name string
size uint64
+8
View File
@@ -37,6 +37,14 @@ const (
FROM ` + asql.DEFAULT_TABLE + `
WHERE dir_hash = $dir_hash AND directory = $directory AND name = $name;`
findBatchQuery = `
PRAGMA TablePathPrefix("%v");
DECLARE $keys AS List<Tuple<int64, Utf8, Utf8>>;
SELECT directory, name, meta
FROM ` + asql.DEFAULT_TABLE + `
WHERE (dir_hash, directory, name) IN $keys;`
deleteFolderChildrenQuery = `
PRAGMA TablePathPrefix("%v");
DECLARE $dir_hash AS int64;
+50
View File
@@ -65,6 +65,56 @@ func (store *YdbStore) KvGet(ctx context.Context, key []byte) (value []byte, err
return value, nil
}
// kvBatchGetSize bounds the keys of one query.
const kvBatchGetSize = 256
func (store *YdbStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
values := make(map[string][]byte, len(keys))
for start := 0; start < len(keys); start += kvBatchGetSize {
batch := keys[start:min(start+kvBatchGetSize, len(keys))]
asked := make(map[[2]string][]string, len(batch))
tuples := make([]types.Value, len(batch))
for i, key := range batch {
dirStr, dirHash, name := abstract_sql.GenDirAndName(key)
pair := [2]string{dirStr, name}
asked[pair] = append(asked[pair], string(key))
tuples[i] = types.TupleValue(types.Int64Value(dirHash), types.UTF8Value(dirStr), types.UTF8Value(name))
}
err := store.DB.Query().Do(ctx, func(ctx context.Context, s query.Session) error {
res, err := s.Query(ctx, *withPragma(&store.tablePathPrefix, findBatchQuery),
query.WithParameters(table.NewQueryParameters(
table.ValueParam("$keys", types.ListValue(tuples...)))), roQC)
if err != nil {
return fmt.Errorf("kv batch get execute: %v", err)
}
defer func() { _ = res.Close(ctx) }()
for rs, err := range res.ResultSets(ctx) {
if err != nil {
return err
}
for row, err := range rs.Rows(ctx) {
if err != nil {
return err
}
var dirStr, name string
var value []byte
if err := row.Scan(&dirStr, &name, &value); err != nil {
return fmt.Errorf("kv batch get scan: %v", err)
}
for _, key := range asked[[2]string{dirStr, name}] {
values[key] = value
}
}
}
return nil
}, query.WithIdempotent())
if err != nil {
return nil, err
}
}
return values, nil
}
func (store *YdbStore) KvDelete(ctx context.Context, key []byte) (err error) {
dirStr, dirHash, name := abstract_sql.GenDirAndName(key)
return store.DB.Query().Do(ctx, func(ctx context.Context, s query.Session) (err error) {
+57
View File
@@ -0,0 +1,57 @@
//go:build ydb
package ydb
import (
"context"
"crypto/rand"
"fmt"
"os"
"testing"
)
func TestKvBatchGetReadsTheKeysHeld(t *testing.T) {
dsn := os.Getenv("YDB_DSN")
if dsn == "" {
t.Skip("set YDB_DSN to a YDB database to run, e.g. grpc://localhost:2136/?database=local")
}
store := &YdbStore{}
if err := store.initialize("/buckets", dsn, "seaweedfs", true, 10, 50, true, 200, true, 5, 1000, 2000); err != nil {
t.Fatal(err)
}
defer store.Shutdown()
ctx := context.Background()
var keys [][]byte
want := map[string][]byte{}
for i := 0; i < 300; i++ {
key := make([]byte, 17)
rand.Read(key)
keys = append(keys, key)
if i%3 != 0 {
want[string(key)] = []byte(fmt.Sprintf("value-%d", i))
if err := store.KvPut(ctx, key, want[string(key)]); err != nil {
t.Fatal(err)
}
}
}
if err := store.KvPut(ctx, []byte("short"), []byte("s")); err != nil {
t.Fatal(err)
}
want["short"] = []byte("s")
want["short\x00"] = []byte("s")
keys = append(keys, []byte("short"), []byte("short\x00"))
values, err := store.KvBatchGet(ctx, keys)
if err != nil {
t.Fatal(err)
}
if len(values) != len(want) {
t.Fatalf("%d values, want %d", len(values), len(want))
}
for key, value := range want {
if string(values[key]) != string(value) {
t.Fatalf("key %x: %q, want %q", key, values[key], value)
}
}
}
@@ -136,6 +136,10 @@ func (s *renameTestStore) KvGet(_ context.Context, key []byte) ([]byte, error) {
}
return nil, filer.ErrKvNotFound
}
func (s *renameTestStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, s.KvGet, keys, 1)
}
func (s *renameTestStore) KvDelete(_ context.Context, key []byte) error {
s.mu.Lock()
defer s.mu.Unlock()