Files
seaweedfs/weed/filer/filerstore.go
T
e9ea21340b filer: a lookup removes what a redis-expired entry left behind (#13397)
* filer: a lookup removes what a redis-expired entry left behind

Redis expires an entry's value on its own and leaves the name in the
parent directory's list. A listing drops such a member when it meets it,
but a lookup finds nothing and returns, so the names of entries nobody
lists stay, and so do the directories they leave empty. The filer_ttl
job expires entries by looking them up and cannot reach them either.

A lookup that finds nothing under a filer.conf TTL rule now asks the
store for what expiry left of that name. The redis stores remove the
list member, guarded against a concurrent recreate as on a listing, and
when there was one the filer removes the directories this leaves empty,
as a listing that meets an expired entry does. A miss with no member to
remove costs one command, and only under a TTL rule.

* filer: keep a directory that holds an object when removing empty parents

A file promoted to a directory by a child write keeps its own object data.
Once its last child expires the directory is empty, and the cleanup
deleted it along with that object.

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

* filer: report a failed removal of a redis-expired leftover

RemoveExpiredLeftover returned a nil error even when the redis SREM or
ZREM failed, so the filer could not log why an expired name stayed.

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

* filer: check a redis orphan repair's keys on the master

With useReadOnly or routeByLatency the cluster client sends EXISTS to a
replica. A lagging replica misreads a just-written value as absent, and
the repair then drops a live entry from its directory list. A lookup miss
now reaches this repair, so check the keys with a script, which runs on
the master, as the redis2 store already does.

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

* filer: a lookup's cleanup leaves directories alone and asks the master first

Removing the directory a redis-expired entry left empty from the lookup
went through DeleteEmptyParentDirectories, which makes none of the empty
folder cleaner's checks. With a leftover as the trigger it removed a
multipart upload's staging directory together with .uploads, a directory
of a bucket that keeps empty folders, an S3 Tables catalog directory,
and the directory of a file written between its emptiness check and its
delete, which strands that file. The lookup now only has the store
remove the name; the directory stays.

The redis stores also check the master for the value before they touch
the list. A lookup that missed on a lagging replica used to remove a live
entry's member and put it back, and a failure in between lost it.

* redis: a lookup's cleanup looks for the member before it asks the master

Most lookups that find nothing are of a name that was never written.
Those now cost one read of the directory list instead of a script and
a removal; only a name the list still holds is checked on the master.

* redis: retry the restore of a directory list member, and report a failure

The orphan repair removes a member and puts it back when the value turns
out to be stored, because an insert got in between. Nothing else puts
that member back, and a failed restore was only logged, so the entry
stayed out of its directory's listing until it was written again. The
restore is now retried a few times, and a restore that still fails is
returned as an error.

* redis: keep restoring a directory list member until redis takes it

A restore that failed every attempt left a live entry out of its directory
list for good, since nothing else puts the member back. Retry it in the
background until it lands or the store closes; the repair still reports
the failure.

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>
2026-12-04 11:30:04 -08:00

188 lines
7.9 KiB
Go

package filer
import (
"context"
"errors"
"io"
"sync"
"github.com/seaweedfs/seaweedfs/weed/util"
"golang.org/x/sync/errgroup"
)
const CountEntryChunksForGzip = 50
var (
ErrUnsupportedListDirectoryPrefixed = errors.New("unsupported directory prefix listing")
ErrUnsupportedSuperLargeDirectoryListing = errors.New("unsupported super large directory listing")
ErrKvNotImplemented = errors.New("kv not implemented yet")
ErrKvNotFound = errors.New("kv: not found")
// ErrTransactionConflict marks a commit the store refused because another
// writer changed a key the transaction read or wrote. No writes from the
// refused transaction were committed; an unknown commit result must not
// carry this sentinel. Running the transaction again reads the other write.
ErrTransactionConflict = errors.New("transaction conflict")
)
type ListEachEntryFunc func(entry *Entry) (bool, error)
type FilerStore interface {
// GetName gets the name to locate the configuration in filer.toml file
GetName() string
// Initialize initializes the file store
Initialize(configuration util.Configuration, prefix string) error
InsertEntry(context.Context, *Entry) error
UpdateEntry(context.Context, *Entry) (err error)
// err == filer_pb.ErrNotFound if not found
FindEntry(context.Context, util.FullPath) (entry *Entry, err error)
DeleteEntry(context.Context, util.FullPath) (err error)
DeleteFolderChildren(context.Context, util.FullPath) (err error)
ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc ListEachEntryFunc) (lastFileName string, err error)
ListDirectoryPrefixedEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc ListEachEntryFunc) (lastFileName string, err error)
BeginTransaction(ctx context.Context) (context.Context, error)
CommitTransaction(ctx context.Context) error
RollbackTransaction(ctx context.Context) error
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")
// UnorderedListingStore is implemented by a store whose directory listings do
// not come in file name order (Elasticsearch pages by a hash of the entry
// path), so a listing there cannot start at a name the store did not return.
type UnorderedListingStore interface {
ListsUnordered() bool
}
// EntryScanner is an optional FilerStore capability: visit every entry at and
// below dirPath, in any order, from one consistent snapshot of the store.
//
// A directory walk sees each directory at a different time, so an entry
// renamed from a directory not yet listed into one already listed is never
// seen; volume.fsck then purges its chunks as orphans. A snapshot sees it
// exactly once. The context handed to fn carries the snapshot, so store reads
// made with it (hard-link records) see the same instant.
type EntryScanner interface {
ScanEntries(ctx context.Context, dirPath util.FullPath, fn func(ctx context.Context, entry *Entry) error) error
}
// ErrUnsupportedRecursiveListing is returned by RecursiveLister, before any
// entry is listed, when the store cannot list below dirPath in path order.
var ErrUnsupportedRecursiveListing = errors.New("recursive listing not supported by this filer store")
// RecursiveLister is an optional FilerStore capability: list the entries below
// dirPath, directories included, in byte order of their full paths. Only
// paths after startPath that start with dirPath + "/" + prefix are listed;
// prefix may hold "/". lastPath is the last path the store read, and a
// listing continues after it.
type RecursiveLister interface {
ListRecursivePrefixedEntries(ctx context.Context, dirPath, startPath util.FullPath, prefix string, limit int64, eachEntryFunc ListEachEntryFunc) (lastPath util.FullPath, err error)
}
type BucketAware interface {
OnBucketCreation(bucket string)
OnBucketDeletion(bucket string)
CanDropWholeBucket() bool
}
type Debuggable interface {
Debug(writer io.Writer)
}
// IsolatingTransactionStore is implemented by a store whose transactions are
// real: the entry and KV writes made under the context BeginTransaction
// returns go through that transaction, stay invisible to other readers until
// CommitTransaction, and are undone by RollbackTransaction. A store says so
// itself, once that has been checked for it: the SQL stores and TiKV do. It
// cannot be told from the context a store hands back, which may carry a
// transaction that its writes do not use.
type IsolatingTransactionStore interface {
IsolatesTransactions() bool
}
// ConflictRefusingStore protects a read-modify-write of one entry and its
// shared KV records. Entry and KV operations must use the context's transaction,
// keep its writes invisible until commit, and leave none behind on rollback.
// If another writer changes a key this transaction both reads and writes after
// its read version, CommitTransaction must refuse with ErrTransactionConflict.
// Read/write conflicts suffice; blind writes need not conflict with each other.
//
// TiKV and FoundationDB implement this capability. It does not promise that
// bulk operations such as DeleteFolderChildren stay inside the transaction.
// Other stores must opt in only after their entry and KV paths, isolation and
// conflict errors have been checked; having BeginTransaction alone is not enough.
type ConflictRefusingStore interface {
RefusesConflictingCommits() bool
}
// ExpiredLeftoverStore is implemented by a store whose rows expire on their
// own and can leave part of an entry behind, as the redis stores leave its
// name in the parent directory's list.
type ExpiredLeftoverStore interface {
// RemoveExpiredLeftover removes what is left of the entry at fullpath
// once its row is gone, and reports whether there was anything.
RemoveExpiredLeftover(ctx context.Context, fullpath util.FullPath) (removed bool, err error)
}
// OverwritingStore is implemented by a store without transactions whose
// InsertEntry over an existing entry replaces it at once and whole: the stored
// entry, its expiry, and its listing in the directory. A rename can then write
// a file over its target instead of deleting the target first. A store says so
// itself, once its insert has been checked: an upsert may leave part of the
// old row in place. The Redis stores do.
type OverwritingStore interface {
OverwritesAtOnce() bool
}