diff --git a/weed/filer/filer.go b/weed/filer/filer.go index 612cd73820..351c52d9c0 100644 --- a/weed/filer/filer.go +++ b/weed/filer/filer.go @@ -99,6 +99,10 @@ type Filer struct { // aggregator across a replayed peer change's check-and-apply, so the two // cannot interleave on the same path. EntryLockTable *util.LockTable[util.FullPath] + // directoryCreateLock covers a directory row's re-check and insert, so a + // missing parent filled in by a nested create cannot replace a directory + // created at the same time. + directoryCreateLock *util.LockTable[util.FullPath] // remoteTombstonesDone, when non-nil, is closed once the startup tombstone // rebuild finishes; lazy remote reads wait on it so a pending delete // cannot resurrect in the gap. @@ -154,6 +158,7 @@ func NewFiler(masters pb.ServerDiscovery, dialOptions *DialOptions, filerHost pb persistedLogCache: newPersistedLogCache(persistedLogCacheMaxBytes), remoteTombstones: newRemoteDeletionTombstones(), EntryLockTable: util.NewLockTable[util.FullPath](), + directoryCreateLock: util.NewLockTable[util.FullPath](), } f.flushCtx, f.flushCancel = context.WithCancel(context.Background()) if f.UniqueFilerId < 0 { @@ -526,6 +531,7 @@ func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, existing *Entry, entry.Attr.Atime = entryInitialAtime(entry.Attr) } + unlockDirectory := func() {} oldEntry := existing if oldEntry == nil { var findErr error @@ -542,6 +548,13 @@ func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, existing *Entry, // itself failed; proceeding would upsert over it. return fmt.Errorf("find entry %s: %w", entry.FullPath, findErr) } + if oldEntry == nil && entry.IsDirectory() { + unlockDirectory = f.lockDirectoryCreate(ctx, entry.FullPath) + defer unlockDirectory() + if oldEntry, findErr = f.FindEntry(context.WithValue(ctx, lazyFetchContextKey{}, true), entry.FullPath); findErr != nil && !errors.Is(findErr, filer_pb.ErrNotFound) { + return fmt.Errorf("find entry %s: %w", entry.FullPath, findErr) + } + } } /* @@ -572,6 +585,7 @@ func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, existing *Entry, glog.ErrorfCtx(ctx, "insert entry %s: %v", entry.FullPath, err) return fmt.Errorf("insert entry %s: %v", entry.FullPath, err) } + unlockDirectory() // Parents go after the entry: one checked first can be taken by the // empty-folder cleaner before the entry lands, and nothing would look again. @@ -593,6 +607,7 @@ func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, existing *Entry, stats.FilerObjectSizeBytesHistogram.Observe(float64(entry.Size())) } } else { + unlockDirectory() if o_excl { glog.V(3).InfofCtx(ctx, "EEXIST: entry %s already exists", entry.FullPath) return fmt.Errorf("%s: %w", entry.FullPath, filer_pb.ErrEntryAlreadyExists) @@ -639,6 +654,18 @@ func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, existing *Entry, return nil } +// lockDirectoryCreate holds the path's directoryCreateLock; the returned +// unlock may be called more than once. A store transaction keeps its +// connection until it commits, and a holder may need that connection, so +// writes inside one do not take the lock. +func (f *Filer) lockDirectoryCreate(ctx context.Context, p util.FullPath) (unlock func()) { + if f.directoryCreateLock == nil || ctx.Value(storeTransactionKey{}) != nil { + return func() {} + } + lock := f.directoryCreateLock.AcquireLock("createDirectory", p, util.ExclusiveLock) + return sync.OnceFunc(func() { f.directoryCreateLock.ReleaseLock(p, lock) }) +} + func (f *Filer) ensureParentDirectoryEntry(ctx context.Context, entry *Entry, dirParts []string, level int, isFromOtherCluster bool) (err error) { if level == 0 { @@ -695,8 +722,18 @@ func (f *Filer) ensureParentDirectoryEntry(ctx context.Context, entry *Entry, di } glog.V(2).InfofCtx(ctx, "create directory: %s %v", dirPath, dirEntry.Mode) + unlock := f.lockDirectoryCreate(ctx, dirEntry.FullPath) + if current, findErr := f.FindEntry(context.WithValue(ctx, lazyFetchContextKey{}, true), dirEntry.FullPath); current != nil || (findErr != nil && !errors.Is(findErr, filer_pb.ErrNotFound)) { + unlock() + if current == nil { + return findErr + } + // Created since the lookup above: take it as found. + return f.ensureParentDirectoryEntry(ctx, entry, dirParts, level, isFromOtherCluster) + } f.stampEntryCommitTsNs(dirEntry) mkdirErr := f.Store.InsertEntry(ctx, dirEntry) + unlock() if mkdirErr != nil { f.releaseEntryCommitTsNs(dirEntry.CommitTsNs) if fEntry, err := f.FindEntry(ctx, util.FullPath(dirPath)); err == filer_pb.ErrNotFound || fEntry == nil { diff --git a/weed/filer/filer_implicit_dir_test.go b/weed/filer/filer_implicit_dir_test.go new file mode 100644 index 0000000000..61c53545d6 --- /dev/null +++ b/weed/filer/filer_implicit_dir_test.go @@ -0,0 +1,119 @@ +package filer + +import ( + "context" + "errors" + "os" + "runtime" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + "github.com/seaweedfs/seaweedfs/weed/util" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// missHookStore runs onMiss, outside the store lock, right after the miss-th +// lookup of path that finds nothing. +type missHookStore struct { + *stubFilerStore + path util.FullPath + miss int32 + misses atomic.Int32 + onMiss func() +} + +func (s *missHookStore) FindEntry(ctx context.Context, p util.FullPath) (*Entry, error) { + e, err := s.stubFilerStore.FindEntry(ctx, p) + if p == s.path && errors.Is(err, filer_pb.ErrNotFound) && s.misses.Add(1) == s.miss { + s.onMiss() + } + return e, err +} + +func directoryMarker(p util.FullPath) *Entry { + return &Entry{ + FullPath: p, + Attr: Attr{Mode: os.ModeDir | 0o755, Mime: s3_constants.FolderMimeType}, + Extended: map[string][]byte{s3_constants.ExtETagKey: []byte("d41d8cd98f00b204e9800998ecf8427e")}, + } +} + +func assertDirectoryMarker(t *testing.T, store *stubFilerStore, p util.FullPath) { + t.Helper() + dir, err := store.FindEntry(context.Background(), p) + require.NoError(t, err) + assert.True(t, dir.IsDirectory()) + assert.Equal(t, s3_constants.FolderMimeType, dir.Attr.Mime, "the implicit parent replaced the directory created meanwhile") + assert.Contains(t, dir.Extended, s3_constants.ExtETagKey) +} + +// A directory created while a nested create is filling in that directory as +// a missing parent keeps what it was created with: the parent row is only +// written where none exists. +func TestImplicitParentKeepsConcurrentDirectory(t *testing.T) { + f, stub := newTestFilerWithStubStore(t) + ctx := context.Background() + dirPath := util.FullPath("/buckets/bkt/markers/dir") + + store := &missHookStore{stubFilerStore: stub, path: dirPath, miss: 1} + f.Store = NewFilerStoreWrapper(store) + store.onMiss = func() { + require.NoError(t, f.CreateEntry(ctx, directoryMarker(dirPath), nil, false, false, nil, false, f.MaxFilenameLength)) + } + + child := &Entry{FullPath: dirPath.Child("child"), Attr: Attr{Mode: 0o644}} + require.NoError(t, f.CreateEntry(ctx, child, nil, false, false, nil, false, f.MaxFilenameLength)) + + assertDirectoryMarker(t, stub, dirPath) +} + +// A directory create arriving after the parent's re-check, before its insert, +// waits for that insert and then updates the row rather than being replaced. +func TestDirectoryCreateWaitsForImplicitParentInsert(t *testing.T) { + f, stub := newTestFilerWithStubStore(t) + ctx := context.Background() + dirPath := util.FullPath("/buckets/bkt/markers/dir") + + markerDone := make(chan error, 1) + store := &missHookStore{stubFilerStore: stub, path: dirPath, miss: 2} + f.Store = NewFilerStoreWrapper(store) + store.onMiss = func() { + go func() { + markerDone <- f.CreateEntry(ctx, directoryMarker(dirPath), nil, false, false, nil, false, f.MaxFilenameLength) + }() + waitForDirectoryCreateWaiter(t, markerDone) + } + + child := &Entry{FullPath: dirPath.Child("child"), Attr: Attr{Mode: 0o644}} + require.NoError(t, f.CreateEntry(ctx, child, nil, false, false, nil, false, f.MaxFilenameLength)) + require.GreaterOrEqual(t, store.misses.Load(), int32(2), "the parent was inserted without a re-check") + require.NoError(t, <-markerDone) + + assertDirectoryMarker(t, stub, dirPath) +} + +// waitForDirectoryCreateWaiter returns once a goroutine waits in +// lockDirectoryCreate, or once the create has finished without waiting. +func waitForDirectoryCreateWaiter(t *testing.T, done chan error) { + t.Helper() + buf := make([]byte, 1<<20) + for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(time.Millisecond) { + select { + case err := <-done: + done <- err + return + default: + } + for _, g := range strings.Split(string(buf[:runtime.Stack(buf, true)]), "\n\n") { + if strings.Contains(g, "sync.(*Cond).Wait") && strings.Contains(g, "lockDirectoryCreate") { + return + } + } + } + t.Fatal("the directory create neither waited nor finished") +}