diff --git a/weed/filer/posixlock/manager.go b/weed/filer/posixlock/manager.go index 8fb56ce53a..429339a82a 100644 --- a/weed/filer/posixlock/manager.go +++ b/weed/filer/posixlock/manager.go @@ -1,6 +1,8 @@ package posixlock import ( + "errors" + "math" "sync" "time" ) @@ -15,76 +17,170 @@ import ( // key is an opaque inode identity supplied by the caller — the file's path, or // "hl:"+hex(HardLinkId) for a hardlinked inode — so all names of one inode share // a Set. The Manager is safe for concurrent use. +// +// Unscoped sessions (empty Principal) are leased as a whole once they renew. +// A scoped session is leased per key from its first acquisition: the lease ends +// at the earlier of Lease.TTL after its last acquisition or renewal on that key +// and Lease.NotAfter; no request moves it earlier, so a late request under an +// older token cannot cut short a replacement's renewal. A renewal also extends +// the session's other keys taken under the same Lease.Grant, skipping the scan +// while those keys already last long enough, so a mount renewing many keys one +// by one costs linear, not quadratic, work. Expired scoped locks are dropped +// before any operation on their key, so they never block a new holder until +// the next sweep. type Manager struct { mu sync.Mutex - byKey map[string]*Set // inode key -> held locks - bySid map[uint64]map[string]bool // session -> keys it currently holds locks on - lastSeen map[uint64]time.Time // session -> last keepalive; only renewing sessions are leased + now func() time.Time + byKey map[string]*Set // inode key -> held locks + sessions map[Session]*sessionState // session -> keys it holds locks on, and its leases +} + +// sessionState is one session's index and lease state. keys maps each key the +// session holds locks on to its lease there, which only a scoped session has. +// lastSeen is an unscoped session's last keepalive, zero until it renews: only +// renewing sessions are leased. floors maps a scoped session's grant to the +// deadline every live key under it reaches. +type sessionState struct { + keys map[string]keyLease + lastSeen time.Time + floors map[string]time.Time +} + +// ErrLeaseEnded refuses a scoped lock whose lease would end before it is +// granted, such as a request admitted just before its token expired. +var ErrLeaseEnded = errors.New("posix lock lease has already ended") + +// Session is a mount session under the authority that holds it. Sid is chosen +// by the client; Principal, set by the server from the verified credential, is +// empty for unscoped callers. +type Session struct { + Principal string + Sid uint64 +} + +// Lease bounds a scoped session's hold on a key. It is ignored for unscoped +// sessions. +// +// Grant identifies the authority the caller holds, such as a digest of its +// verified grants. A key remembers the Grant it was acquired or re-asserted +// under, and a renewal under the same non-empty Grant extends every such key of +// the session: the caller could renew each of them on its own, and renewing +// them together keeps a mount that holds many keys from losing some while it +// renews them one by one. A key taken under another Grant, or under none, is +// renewed only by name. +type Lease struct { + TTL time.Duration + NotAfter time.Time + Grant string +} + +// keyLease is a scoped session's lease on one key. +type keyLease struct { + deadline time.Time + grant string } func NewManager() *Manager { + return NewManagerWithClock(time.Now) +} + +// NewManagerWithClock returns a Manager whose leases follow now. +func NewManagerWithClock(now func() time.Time) *Manager { return &Manager{ + now: now, byKey: make(map[string]*Set), - bySid: make(map[uint64]map[string]bool), - lastSeen: make(map[uint64]time.Time), + sessions: make(map[Session]*sessionState), } } -// Renew records a keepalive from a session, placing it under lease management. -// Only sessions that have renewed are subject to ReapExpired, so a session that -// never sends keepalives (e.g. before the mount keepalive exists) is never reaped. -func (m *Manager) Renew(sid uint64) { +// Renew records a keepalive from a session. An unscoped session is placed under +// lease management as a whole, regardless of key: only sessions that have +// renewed are subject to ReapExpired, so a session that never sends keepalives +// (e.g. before the mount keepalive exists) is never reaped. A scoped session +// renews its existing lease on key, keeping the Grant the key was taken under, +// and its other live leases taken under lease.Grant. +func (m *Manager) Renew(key string, ss Session, lease Lease) { m.mu.Lock() defer m.mu.Unlock() - m.lastSeen[sid] = time.Now() + if ss.Principal == "" { + m.session(ss).lastSeen = m.now() + return + } + m.live(key) + if st := m.sessions[ss]; st != nil { + if l, held := st.keys[key]; held { + l.deadline = laterOf(l.deadline, m.deadline(lease)) + st.keys[key] = l + st.lowerFloor(l) + } + } + m.renewGrant(ss, lease) } -// ReapExpired releases the locks of every leased session whose last keepalive is -// older than ttl — a dead or partitioned mount. Sessions that never renewed are -// left untouched. Returns the reaped session ids. +// ReapExpired releases the locks of every leased unscoped session whose last +// keepalive is older than ttl — a dead or partitioned mount — and of every +// scoped lease past its deadline. Unscoped sessions that never renewed are left +// untouched. Returns the reaped session ids. func (m *Manager) ReapExpired(ttl time.Duration) []uint64 { m.mu.Lock() defer m.mu.Unlock() - cutoff := time.Now().Add(-ttl) + now := m.now() + cutoff := now.Add(-ttl) var reaped []uint64 - for sid, seen := range m.lastSeen { - if seen.After(cutoff) { - continue - } - for key := range m.bySid[sid] { - s := m.byKey[key] - if s == nil { + for ss, st := range m.sessions { + if ss.Principal == "" { + if st.lastSeen.IsZero() || st.lastSeen.After(cutoff) { continue } - s.ReleaseSession(sid) - if s.Empty() { - delete(m.byKey, key) + for key := range st.keys { + m.releaseOn(key, ss) } + delete(m.sessions, ss) + reaped = append(reaped, ss.Sid) + continue + } + expired := false + for key, l := range st.keys { + if now.Before(l.deadline) { + continue + } + m.releaseOn(key, ss) + m.deindex(ss, key) + expired = true + } + if expired { + reaped = append(reaped, ss.Sid) } - delete(m.bySid, sid) - delete(m.lastSeen, sid) - reaped = append(reaped, sid) } return reaped } // TryLock grants lk on key, or returns the conflicting lock and false. The set -// is created on first use and dropped again when it empties. -func (m *Manager) TryLock(key string, lk Range) (Range, bool) { +// is created on first use and dropped again when it empties. A grant to a +// scoped session starts or extends its lease on key; when that lease has +// already ended, nothing is granted and the error is ErrLeaseEnded. +func (m *Manager) TryLock(key string, lk Range, lease Lease) (Range, bool, error) { m.mu.Lock() defer m.mu.Unlock() - s, ok := m.byKey[key] - if !ok { + if lk.Principal != "" && !m.now().Before(m.deadline(lease)) { + return Range{}, false, ErrLeaseEnded + } + s := m.live(key) + created := s == nil + if created { s = &Set{} } if c, granted := s.Acquire(lk); !granted { - return c, false + return c, false, nil } - if !ok { + if created { m.byKey[key] = s } - m.index(lk.Sid, key) - return Range{}, true + m.index(lk.Session(), key) + if lk.Principal != "" { + m.lease(lk.Session(), key, lease) + } + return Range{}, true, nil } // Track records a lock the server already granted, without arbitration. A mount @@ -99,7 +195,7 @@ func (m *Manager) Track(key string, lk Range) { m.byKey[key] = s } s.Grant(lk) - m.index(lk.Sid, key) + m.index(lk.Session(), key) } // Snapshot returns a copy of the held locks per key. A mount calls it to drive @@ -114,17 +210,21 @@ func (m *Manager) Snapshot() map[string][]Range { return out } -// Reassert rebuilds session sid's locks on key from the client's authoritative -// list, renewing the lease. It replaces sid's existing locks on the key, then -// re-acquires each asserted lock — arbitrating against other sessions so it never -// double-grants. Locks that lost to another session in a migration window are -// returned as conflicts. The owner filer calls this on a re-assertion keepalive. -func (m *Manager) Reassert(key string, sid uint64, locks []Range) (conflicts []Range) { +// Reassert rebuilds session ss's locks on key from the client's authoritative +// list, renewing the lease. It replaces ss's existing locks on the key, then +// re-acquires each asserted lock as ss — arbitrating against other sessions so +// it never double-grants. Locks that lost to another session in a migration +// window are returned as conflicts. A scoped re-assertion also renews ss's other +// live leases taken under lease.Grant, as Renew does. The owner filer calls this +// on a re-assertion keepalive. +func (m *Manager) Reassert(key string, ss Session, locks []Range, lease Lease) (conflicts []Range) { m.mu.Lock() defer m.mu.Unlock() - m.lastSeen[sid] = time.Now() + if ss.Principal == "" { + m.session(ss).lastSeen = m.now() + } - s := m.byKey[key] + s := m.live(key) if s == nil { if len(locks) == 0 { return nil @@ -132,21 +232,27 @@ func (m *Manager) Reassert(key string, sid uint64, locks []Range) (conflicts []R s = &Set{} m.byKey[key] = s } - s.ReleaseSession(sid) + s.ReleaseSession(ss) for _, lk := range locks { - lk.Sid = sid + lk.Sid, lk.Principal = ss.Sid, ss.Principal if c, granted := s.Acquire(lk); !granted { conflicts = append(conflicts, c) } } - if setHasSession(s, sid) { - m.index(sid, key) + if setHasSession(s, ss) { + m.index(ss, key) + if ss.Principal != "" { + m.lease(ss, key, lease) + } } else { - m.deindex(sid, key) + m.deindex(ss, key) } if s.Empty() { delete(m.byKey, key) } + if ss.Principal != "" { + m.renewGrant(ss, lease) + } return conflicts } @@ -154,104 +260,240 @@ func (m *Manager) Reassert(key string, sid uint64, locks []Range) (conflicts []R func (m *Manager) Unlock(key string, lk Range) { m.mu.Lock() defer m.mu.Unlock() - s := m.byKey[key] + s := m.live(key) if s == nil { return } s.Release(lk) - m.afterRelease(key, s, lk.Sid) + m.afterRelease(key, s, lk.Session()) } // GetLk reports the lock that would block proposed on key, if any. func (m *Manager) GetLk(key string, proposed Range) (Range, bool) { m.mu.Lock() defer m.mu.Unlock() - s := m.byKey[key] + s := m.live(key) if s == nil { return Range{}, false } return s.Conflict(proposed) } -// ReleasePosixOwner drops (sid, owner)'s fcntl locks on key — the flush-time path. -func (m *Manager) ReleasePosixOwner(key string, sid, owner uint64) { +// ReleasePosixOwner drops (ss, owner)'s fcntl locks on key — the flush-time path. +func (m *Manager) ReleasePosixOwner(key string, ss Session, owner uint64) { m.mu.Lock() defer m.mu.Unlock() - s := m.byKey[key] + s := m.live(key) if s == nil { return } - s.ReleasePosixOwner(sid, owner) - m.afterRelease(key, s, sid) + s.ReleasePosixOwner(ss, owner) + m.afterRelease(key, s, ss) } -// ReleaseFlockOwner drops (sid, owner)'s flock locks on key — the release-time path. -func (m *Manager) ReleaseFlockOwner(key string, sid, owner uint64) { +// ReleaseFlockOwner drops (ss, owner)'s flock locks on key — the release-time path. +func (m *Manager) ReleaseFlockOwner(key string, ss Session, owner uint64) { m.mu.Lock() defer m.mu.Unlock() - s := m.byKey[key] + s := m.live(key) if s == nil { return } - s.ReleaseFlockOwner(sid, owner) - m.afterRelease(key, s, sid) + s.ReleaseFlockOwner(ss, owner) + m.afterRelease(key, s, ss) } // ReleaseSession drops every lock held by a session across all inodes it touched, // reaping a mount whose lease expired. O(locks held by the session). -func (m *Manager) ReleaseSession(sid uint64) { +func (m *Manager) ReleaseSession(ss Session) { m.mu.Lock() defer m.mu.Unlock() - for key := range m.bySid[sid] { - s := m.byKey[key] - if s == nil { - continue - } - s.ReleaseSession(sid) - if s.Empty() { - delete(m.byKey, key) + if st := m.sessions[ss]; st != nil { + for key := range st.keys { + m.releaseOn(key, ss) } } - delete(m.bySid, sid) + delete(m.sessions, ss) } -// afterRelease prunes the session index when sid no longer holds any lock on key, -// and drops the set when it empties. Only sid's presence can have changed, since -// a release only removes sid's locks. -func (m *Manager) afterRelease(key string, s *Set, sid uint64) { +// releaseOn drops ss's locks on key, and the set when it empties. +func (m *Manager) releaseOn(key string, ss Session) { + s := m.byKey[key] + if s == nil { + return + } + s.ReleaseSession(ss) if s.Empty() { delete(m.byKey, key) - m.deindex(sid, key) + } +} + +// live returns key's set after dropping the locks of scoped sessions whose +// lease on key has ended, or nil when nothing is held. +func (m *Manager) live(key string) *Set { + s := m.byKey[key] + if s == nil { + return nil + } + now := m.now() + // One pass finds the expired sessions and one more drops all their ranges, + // however many sessions expired and ranges they hold. + var expired map[Session]struct{} + for _, l := range s.locks { + ss := l.Session() + if ss.Principal == "" { + continue + } + if _, seen := expired[ss]; seen { + continue + } + if st := m.sessions[ss]; st != nil { + if l, ok := st.keys[key]; ok && now.Before(l.deadline) { + continue + } + } + if expired == nil { + expired = make(map[Session]struct{}) + } + expired[ss] = struct{}{} + } + if expired != nil { + s.remove(func(h Range) bool { + _, gone := expired[h.Session()] + return gone + }, 0, math.MaxUint64) + for ss := range expired { + m.deindex(ss, key) + } + } + if s.Empty() { + delete(m.byKey, key) + return nil + } + return s +} + +// lease sets ss's lease on key to lease's deadline, held under lease.Grant. +func (m *Manager) lease(ss Session, key string, lease Lease) { + st := m.session(ss) + l := keyLease{deadline: laterOf(st.keys[key].deadline, m.deadline(lease)), grant: lease.Grant} + st.keys[key] = l + st.lowerFloor(l) +} + +// lowerFloor keeps the floor for l.grant at or below l's deadline, so a key +// leased for less than the last same-grant renewal gave its peers is never +// skipped by the next one. +func (st *sessionState) lowerFloor(l keyLease) { + if f, ok := st.floors[l.grant]; ok && l.deadline.Before(f) { + st.floors[l.grant] = l.deadline + } +} + +// deadline is the earlier of lease.TTL from now and lease.NotAfter. +func (m *Manager) deadline(lease Lease) time.Time { + deadline := m.now().Add(lease.TTL) + if lease.NotAfter.Before(deadline) { + deadline = lease.NotAfter + } + return deadline +} + +// renewGrant extends ss's leases taken under lease.Grant to lease's deadline. +// A lease that has already ended stays ended even before it is swept, so when +// a lease ends never depends on when the sweep runs. +// +// A mount renews its keys one by one, and a scan per renewal would cost N² for +// N keys. So the scan is skipped while every live key under the grant already +// lasts until the earlier of lease's deadline and three quarters of a TTL from +// now: the floor the last scan set, lowered by any key leased for less since. +// A renewal with a later deadline than the floor, such as one under a +// replacement token that expires later, scans as soon as the floor falls short. +func (m *Manager) renewGrant(ss Session, lease Lease) { + st := m.sessions[ss] + if lease.Grant == "" || st == nil { return } - if !setHasSession(s, sid) { - m.deindex(sid, key) + now, deadline := m.now(), m.deadline(lease) + enough := now.Add(lease.TTL * 3 / 4) + if deadline.Before(enough) { + enough = deadline } -} - -func (m *Manager) index(sid uint64, key string) { - keys := m.bySid[sid] - if keys == nil { - keys = make(map[string]bool) - m.bySid[sid] = keys - } - keys[key] = true -} - -func (m *Manager) deindex(sid uint64, key string) { - keys := m.bySid[sid] - if keys == nil { + if f, ok := st.floors[lease.Grant]; ok && !f.Before(enough) { return } - delete(keys, key) - if len(keys) == 0 { - delete(m.bySid, sid) + renewed := false + for key, l := range st.keys { + if l.grant == lease.Grant && now.Before(l.deadline) { + l.deadline = laterOf(l.deadline, deadline) + st.keys[key] = l + renewed = true + } + } + if !renewed { + return + } + if st.floors == nil { + st.floors = make(map[string]time.Time) + } + st.floors[lease.Grant] = deadline +} + +func laterOf(a, b time.Time) time.Time { + if a.After(b) { + return a + } + return b +} + +// afterRelease prunes the session index when ss no longer holds any lock on key, +// and drops the set when it empties. Only ss's presence can have changed, since +// a release only removes ss's locks. +func (m *Manager) afterRelease(key string, s *Set, ss Session) { + if s.Empty() { + delete(m.byKey, key) + m.deindex(ss, key) + return + } + if !setHasSession(s, ss) { + m.deindex(ss, key) } } -func setHasSession(s *Set, sid uint64) bool { +// session returns ss's state, creating it on first use. +func (m *Manager) session(ss Session) *sessionState { + st := m.sessions[ss] + if st == nil { + st = &sessionState{keys: make(map[string]keyLease)} + m.sessions[ss] = st + } + return st +} + +func (m *Manager) index(ss Session, key string) { + st := m.session(ss) + if _, ok := st.keys[key]; !ok { + st.keys[key] = keyLease{} + } +} + +// deindex forgets that ss holds locks on key, along with its lease there. A +// session holding no keys is forgotten, with its floors, unless it is an +// unscoped session that has renewed. +func (m *Manager) deindex(ss Session, key string) { + st := m.sessions[ss] + if st == nil { + return + } + delete(st.keys, key) + if len(st.keys) == 0 && st.lastSeen.IsZero() { + delete(m.sessions, ss) + } +} + +func setHasSession(s *Set, ss Session) bool { for _, l := range s.Locks() { - if l.Sid == sid { + if l.Session() == ss { return true } } diff --git a/weed/filer/posixlock/manager_test.go b/weed/filer/posixlock/manager_test.go index 0c0bc8c5ae..3f2efc9cd9 100644 --- a/weed/filer/posixlock/manager_test.go +++ b/weed/filer/posixlock/manager_test.go @@ -11,14 +11,14 @@ import ( func TestManagerGrantAndConflict(t *testing.T) { m := NewManager() - if _, granted := m.TryLock("a", Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1}); !granted { + if _, granted, _ := m.TryLock("a", Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1}, Lease{}); !granted { t.Fatal("first lock should be granted") } - if c, granted := m.TryLock("a", Range{Start: 50, End: 149, Type: Write, Sid: 2, Owner: 1}); granted { + if c, granted, _ := m.TryLock("a", Range{Start: 50, End: 149, Type: Write, Sid: 2, Owner: 1}, Lease{}); granted { t.Fatalf("overlapping lock from another session should conflict, got grant; conflict=%+v", c) } // A different key is independent. - if _, granted := m.TryLock("b", Range{Start: 0, End: 99, Type: Write, Sid: 2, Owner: 1}); !granted { + if _, granted, _ := m.TryLock("b", Range{Start: 0, End: 99, Type: Write, Sid: 2, Owner: 1}, Lease{}); !granted { t.Fatal("lock on a different key should be granted") } } @@ -26,9 +26,9 @@ func TestManagerGrantAndConflict(t *testing.T) { func TestManagerUnlockCleansEmptyKeyAndIndex(t *testing.T) { m := NewManager() lk := Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1} - m.TryLock("a", lk) + m.TryLock("a", lk, Lease{}) - if !m.bySid[1]["a"] { + if !holds(m, Session{Sid: 1}, "a") { t.Fatal("session index should record the held key") } m.Unlock("a", Range{Start: 0, End: 99, Type: Unlock, Sid: 1, Owner: 1}) @@ -36,19 +36,19 @@ func TestManagerUnlockCleansEmptyKeyAndIndex(t *testing.T) { if _, ok := m.byKey["a"]; ok { t.Fatal("empty set should be dropped from byKey") } - if _, ok := m.bySid[1]; ok { + if _, ok := m.sessions[Session{Sid: 1}]; ok { t.Fatal("session index should be pruned when it holds nothing") } } func TestManagerPartialUnlockKeepsIndex(t *testing.T) { m := NewManager() - m.TryLock("a", Range{Start: 0, End: 49, Type: Write, Sid: 1, Owner: 1}) - m.TryLock("a", Range{Start: 100, End: 149, Type: Write, Sid: 1, Owner: 1}) + m.TryLock("a", Range{Start: 0, End: 49, Type: Write, Sid: 1, Owner: 1}, Lease{}) + m.TryLock("a", Range{Start: 100, End: 149, Type: Write, Sid: 1, Owner: 1}, Lease{}) // Release one of the two ranges; the session still holds the other. m.Unlock("a", Range{Start: 0, End: 49, Type: Unlock, Sid: 1, Owner: 1}) - if !m.bySid[1]["a"] { + if !holds(m, Session{Sid: 1}, "a") { t.Fatal("session still holds a lock on the key; index must remain") } if _, ok := m.byKey["a"]; !ok { @@ -58,7 +58,7 @@ func TestManagerPartialUnlockKeepsIndex(t *testing.T) { func TestManagerGetLk(t *testing.T) { m := NewManager() - m.TryLock("a", Range{Start: 10, End: 50, Type: Write, Sid: 1, Owner: 1, Pid: 7}) + m.TryLock("a", Range{Start: 10, End: 50, Type: Write, Sid: 1, Owner: 1, Pid: 7}, Lease{}) c, found := m.GetLk("a", Range{Start: 30, End: 70, Type: Read, Sid: 2, Owner: 1}) if !found || c.Pid != 7 { t.Fatalf("expected conflict from pid 7, got %+v found=%v", c, found) @@ -70,13 +70,13 @@ func TestManagerGetLk(t *testing.T) { func TestManagerReleasePosixOwnerKeepsFlockAndIndex(t *testing.T) { m := NewManager() - m.TryLock("a", Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1}) - m.TryLock("a", Range{Start: 0, End: math.MaxUint64, Type: Write, Sid: 1, Owner: 1, IsFlock: true}) + m.TryLock("a", Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1}, Lease{}) + m.TryLock("a", Range{Start: 0, End: math.MaxUint64, Type: Write, Sid: 1, Owner: 1, IsFlock: true}, Lease{}) - m.ReleasePosixOwner("a", 1, 1) + m.ReleasePosixOwner("a", Session{Sid: 1}, 1) // flock lock for the same session remains, so the index must remain too. - if !m.bySid[1]["a"] { + if !holds(m, Session{Sid: 1}, "a") { t.Fatal("session still holds the flock lock; index must remain") } if _, found := m.GetLk("a", Range{Start: 0, End: 10, Type: Write, Sid: 2, Owner: 2, IsFlock: true}); !found { @@ -89,13 +89,13 @@ func TestManagerReleasePosixOwnerKeepsFlockAndIndex(t *testing.T) { func TestManagerReleaseSessionReapsAcrossKeys(t *testing.T) { m := NewManager() - m.TryLock("a", Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1}) - m.TryLock("b", Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 2}) - m.TryLock("b", Range{Start: 200, End: 299, Type: Write, Sid: 2, Owner: 1}) + m.TryLock("a", Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1}, Lease{}) + m.TryLock("b", Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 2}, Lease{}) + m.TryLock("b", Range{Start: 200, End: 299, Type: Write, Sid: 2, Owner: 1}, Lease{}) - m.ReleaseSession(1) + m.ReleaseSession(Session{Sid: 1}) - if _, ok := m.bySid[1]; ok { + if _, ok := m.sessions[Session{Sid: 1}]; ok { t.Fatal("reaped session should be gone from the index") } if _, ok := m.byKey["a"]; ok { @@ -105,7 +105,7 @@ func TestManagerReleaseSessionReapsAcrossKeys(t *testing.T) { if _, found := m.GetLk("b", Range{Start: 200, End: 299, Type: Write, Sid: 9, Owner: 9}); !found { t.Fatal("session 2's lock on b should remain after reaping session 1") } - if !m.bySid[2]["b"] { + if !holds(m, Session{Sid: 2}, "b") { t.Fatal("session 2 index entry should remain") } } @@ -113,14 +113,14 @@ func TestManagerReleaseSessionReapsAcrossKeys(t *testing.T) { func TestManagerReapsOnlyStaleLeasedSessions(t *testing.T) { m := NewManager() // Session 1: holds a lock, leased but stale (renewed long ago). - m.TryLock("a", Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1}) - m.Renew(1) - m.lastSeen[1] = time.Now().Add(-time.Hour) + m.TryLock("a", Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1}, Lease{}) + m.Renew("", Session{Sid: 1}, Lease{}) + m.sessions[Session{Sid: 1}].lastSeen = time.Now().Add(-time.Hour) // Session 2: holds a lock, leased and fresh. - m.TryLock("b", Range{Start: 0, End: 99, Type: Write, Sid: 2, Owner: 1}) - m.Renew(2) + m.TryLock("b", Range{Start: 0, End: 99, Type: Write, Sid: 2, Owner: 1}, Lease{}) + m.Renew("", Session{Sid: 2}, Lease{}) // Session 3: holds a lock but never renewed (no lease) — must not be reaped. - m.TryLock("c", Range{Start: 0, End: 99, Type: Write, Sid: 3, Owner: 1}) + m.TryLock("c", Range{Start: 0, End: 99, Type: Write, Sid: 3, Owner: 1}, Lease{}) reaped := m.ReapExpired(30 * time.Second) @@ -136,7 +136,7 @@ func TestManagerReapsOnlyStaleLeasedSessions(t *testing.T) { if _, ok := m.byKey["c"]; !ok { t.Fatal("never-renewed session must not be reaped") } - if _, ok := m.lastSeen[1]; ok { + if _, ok := m.sessions[Session{Sid: 1}]; ok { t.Fatal("reaped session's lease entry should be cleared") } } @@ -165,7 +165,7 @@ func TestManagerConcurrentFlockMutualExclusion(t *testing.T) { token := int64(id + 1) for i := 0; i < iters; i++ { for { - if _, granted := m.TryLock(key, lk); granted { + if _, granted, _ := m.TryLock(key, lk, Lease{}); granted { break } runtime.Gosched() @@ -188,7 +188,16 @@ func TestManagerConcurrentFlockMutualExclusion(t *testing.T) { if len(m.byKey) != 0 { t.Fatalf("all locks released; byKey should be empty, got %d", len(m.byKey)) } - if len(m.bySid) != 0 { - t.Fatalf("all locks released; bySid should be empty, got %d", len(m.bySid)) + if len(m.sessions) != 0 { + t.Fatalf("all locks released; sessions should be empty, got %d", len(m.sessions)) } } + +func holds(m *Manager, ss Session, key string) bool { + st := m.sessions[ss] + if st == nil { + return false + } + _, ok := st.keys[key] + return ok +} diff --git a/weed/filer/posixlock/posixlock.go b/weed/filer/posixlock/posixlock.go index 0fdac08a7e..426888c35f 100644 --- a/weed/filer/posixlock/posixlock.go +++ b/weed/filer/posixlock/posixlock.go @@ -24,22 +24,31 @@ const ( Unlock uint32 = 3 ) -// Range is one held advisory byte-range lock. Owner identity is the (Sid, Owner) -// pair: Sid is the mount session, Owner the FUSE lock owner within it, so owners -// from different mounts never alias. End is inclusive; math.MaxUint64 means EOF. -// IsFlock separates the flock and fcntl namespaces, which never conflict. +// Range is one held advisory byte-range lock. Owner identity is the +// (Principal, Sid, Owner) triple: Sid is the mount session, Owner the FUSE lock +// owner within it, so owners from different mounts never alias. Principal is the +// verified authority the server holds the lock under, empty for unscoped +// callers; it is server-side state and never leaves the filer. End is +// inclusive; math.MaxUint64 means EOF. IsFlock separates the flock and fcntl +// namespaces, which never conflict. type Range struct { - Start uint64 - End uint64 - Type uint32 - Sid uint64 - Owner uint64 - Pid uint32 - IsFlock bool + Start uint64 + End uint64 + Type uint32 + Sid uint64 + Owner uint64 + Pid uint32 + IsFlock bool + Principal string +} + +// Session returns the session that holds r. +func (r Range) Session() Session { + return Session{Principal: r.Principal, Sid: r.Sid} } func (r Range) sameOwner(o Range) bool { - return r.Sid == o.Sid && r.Owner == o.Owner + return r.Principal == o.Principal && r.Sid == o.Sid && r.Owner == o.Owner } // Set is the authoritative set of advisory locks held on one inode. The zero @@ -172,41 +181,41 @@ func (s *Set) Release(lk Range) { }, lk.Start, lk.End) } -// ReleaseOwner removes every lock held by (sid, owner) in both namespaces. -func (s *Set) ReleaseOwner(sid, owner uint64) { +// ReleaseOwner removes every lock held by (ss, owner) in both namespaces. +func (s *Set) ReleaseOwner(ss Session, owner uint64) { s.remove(func(h Range) bool { - return h.Sid == sid && h.Owner == owner + return h.Session() == ss && h.Owner == owner }, 0, math.MaxUint64) } -// ReleaseFlockOwner removes only the flock locks of (sid, owner) — the close-time +// ReleaseFlockOwner removes only the flock locks of (ss, owner) — the close-time // path for a released file description (FUSE_RELEASE_FLOCK_UNLOCK). -func (s *Set) ReleaseFlockOwner(sid, owner uint64) { +func (s *Set) ReleaseFlockOwner(ss Session, owner uint64) { s.remove(func(h Range) bool { - return h.IsFlock && h.Sid == sid && h.Owner == owner + return h.IsFlock && h.Session() == ss && h.Owner == owner }, 0, math.MaxUint64) } -// ReleasePosixOwner removes only the fcntl locks of (sid, owner) — the close-time +// ReleasePosixOwner removes only the fcntl locks of (ss, owner) — the close-time // path for a flushing POSIX lock owner. -func (s *Set) ReleasePosixOwner(sid, owner uint64) { +func (s *Set) ReleasePosixOwner(ss Session, owner uint64) { s.remove(func(h Range) bool { - return !h.IsFlock && h.Sid == sid && h.Owner == owner + return !h.IsFlock && h.Session() == ss && h.Owner == owner }, 0, math.MaxUint64) } // ReleaseSession removes every lock held by a session, reaping a mount that has // died or disconnected (its lease expired). -func (s *Set) ReleaseSession(sid uint64) { - s.remove(func(h Range) bool { return h.Sid == sid }, 0, math.MaxUint64) +func (s *Set) ReleaseSession(ss Session) { + s.remove(func(h Range) bool { return h.Session() == ss }, 0, math.MaxUint64) } -// HasPosix reports whether (sid, owner) holds any fcntl lock, mirroring the +// HasPosix reports whether (ss, owner) holds any fcntl lock, mirroring the // mount's flush-time check that avoids treating a lock-free flush as // lock-sensitive. -func (s *Set) HasPosix(sid, owner uint64) bool { +func (s *Set) HasPosix(ss Session, owner uint64) bool { for _, h := range s.locks { - if !h.IsFlock && h.Sid == sid && h.Owner == owner { + if !h.IsFlock && h.Session() == ss && h.Owner == owner { return true } } diff --git a/weed/filer/posixlock/posixlock_test.go b/weed/filer/posixlock/posixlock_test.go index 3cbb998435..33093afc59 100644 --- a/weed/filer/posixlock/posixlock_test.go +++ b/weed/filer/posixlock/posixlock_test.go @@ -124,7 +124,7 @@ func TestReleaseOwner(t *testing.T) { mustAcquire(t, s, Range{Start: 50, End: 99, Type: Write, Owner: 1, Pid: 10}) mustAcquire(t, s, Range{Start: 200, End: 299, Type: Read, Owner: 2, Pid: 20}) - s.ReleaseOwner(0, 1) + s.ReleaseOwner(Session{}, 1) if _, found := s.Conflict(Range{Start: 0, End: 99, Type: Write, Owner: 3, Pid: 30}); found { t.Fatal("owner 1's locks should be gone") @@ -144,7 +144,7 @@ func TestFlockAndFcntlDoNotConflict(t *testing.T) { func TestReleasePosixOwnerKeepsFlock(t *testing.T) { s := &Set{} mustAcquire(t, s, Range{Start: 0, End: math.MaxUint64, Type: Write, Owner: 1, Pid: 10, IsFlock: true}) - s.ReleasePosixOwner(0, 1) + s.ReleasePosixOwner(Session{}, 1) if _, found := s.Conflict(Range{Start: 0, End: math.MaxUint64, Type: Write, Owner: 2, Pid: 20, IsFlock: true}); !found { t.Fatal("flock lock should remain after ReleasePosixOwner") } @@ -155,7 +155,7 @@ func TestReleaseFlockOwnerKeepsPosix(t *testing.T) { mustAcquire(t, s, Range{Start: 0, End: 99, Type: Write, Owner: 1, Pid: 10}) mustAcquire(t, s, Range{Start: 0, End: math.MaxUint64, Type: Write, Owner: 2, Pid: 10, IsFlock: true}) - s.ReleaseFlockOwner(0, 2) + s.ReleaseFlockOwner(Session{}, 2) if _, found := s.Conflict(Range{Start: 0, End: 99, Type: Write, Owner: 3, Pid: 30}); !found { t.Fatal("fcntl lock should remain after ReleaseFlockOwner") @@ -167,15 +167,15 @@ func TestReleaseFlockOwnerKeepsPosix(t *testing.T) { func TestHasPosixIgnoresMissingOwnerAndFlock(t *testing.T) { s := &Set{} - if s.HasPosix(0, 1) { + if s.HasPosix(Session{}, 1) { t.Fatal("empty set should report no posix owner") } mustAcquire(t, s, Range{Start: 0, End: math.MaxUint64, Type: Write, Owner: 1, Pid: 10, IsFlock: true}) - if s.HasPosix(0, 1) { + if s.HasPosix(Session{}, 1) { t.Fatal("a flock owner is not a posix owner") } mustAcquire(t, s, Range{Start: 0, End: 99, Type: Write, Owner: 2, Pid: 20}) - if !s.HasPosix(0, 2) { + if !s.HasPosix(Session{}, 2) { t.Fatal("posix owner should be reported") } } @@ -266,7 +266,7 @@ func TestReleaseSessionReapsOnlyThatSession(t *testing.T) { mustAcquire(t, s, Range{Start: 0, End: math.MaxUint64, Type: Write, Sid: 1, Owner: 2, Pid: 11, IsFlock: true}) mustAcquire(t, s, Range{Start: 50, End: 99, Type: Write, Sid: 2, Owner: 1, Pid: 20}) - s.ReleaseSession(1) + s.ReleaseSession(Session{Sid: 1}) for _, h := range s.locks { if h.Sid == 1 { diff --git a/weed/filer/posixlock/principal_test.go b/weed/filer/posixlock/principal_test.go new file mode 100644 index 0000000000..7f33114b01 --- /dev/null +++ b/weed/filer/posixlock/principal_test.go @@ -0,0 +1,508 @@ +package posixlock + +import ( + "errors" + "fmt" + "reflect" + "sync" + "testing" + "time" +) + +type testClock struct { + mu sync.Mutex + now time.Time +} + +func (c *testClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.now +} + +func (c *testClock) Set(t time.Time) { + c.mu.Lock() + defer c.mu.Unlock() + c.now = t +} + +func newScopedTestManager() (*Manager, *testClock, time.Time) { + start := time.Unix(1_000_000, 0) + clock := &testClock{now: start} + return NewManagerWithClock(clock.Now), clock, start +} + +func TestManagerOwnersWithEqualSidAndOwnerDifferUnderAnotherPrincipal(t *testing.T) { + m, _, start := newScopedTestManager() + lease := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour)} + holder := Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1, Pid: 7, Principal: "a"} + if _, granted, _ := m.TryLock("k", holder, lease); !granted { + t.Fatal("holder should be granted") + } + for _, other := range []string{"b", ""} { + same := holder + same.Principal = other + if c, granted, _ := m.TryLock("k", same, lease); granted || c.Pid != 7 { + t.Fatalf("principal %q with the holder's sid/owner must conflict, got granted=%v conflict=%+v", other, granted, c) + } + if _, found := m.GetLk("k", same); !found { + t.Fatalf("GET_LK under principal %q must report the holder", other) + } + unlock := same + unlock.Type, unlock.Start, unlock.End = Unlock, 10, 20 + m.Unlock("k", unlock) + m.ReleasePosixOwner("k", same.Session(), same.Owner) + m.ReleaseSession(same.Session()) + m.Reassert("k", same.Session(), []Range{same}, lease) + m.Renew("k", same.Session(), lease) + } + if got := m.Snapshot()["k"]; !reflect.DeepEqual(got, []Range{holder}) { + t.Fatalf("holder's lock changed by other principals: %+v", got) + } + if _, found := m.GetLk("k", holder); found { + t.Fatal("the holder must not conflict with itself") + } +} + +func TestManagerAdjacentRangesOfDifferentPrincipalsNeverCoalesce(t *testing.T) { + m, _, start := newScopedTestManager() + lease := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour)} + m.TryLock("k", Range{Start: 0, End: 9, Type: Read, Sid: 1, Owner: 1, Principal: "a"}, lease) + m.TryLock("k", Range{Start: 10, End: 19, Type: Read, Sid: 1, Owner: 1, Principal: "b"}, lease) + m.TryLock("k", Range{Start: 20, End: 29, Type: Read, Sid: 1, Owner: 1}, lease) + if got := m.Snapshot()["k"]; len(got) != 3 { + t.Fatalf("ranges of different principals must stay separate, got %+v", got) + } + // A partial unlock by one principal splits only its own range. + m.Unlock("k", Range{Start: 3, End: 5, Type: Unlock, Sid: 1, Owner: 1, Principal: "a"}) + if got := m.Snapshot()["k"]; len(got) != 4 || got[0].End != 2 || got[1].Start != 6 || got[2].Principal != "b" { + t.Fatalf("partial unlock should split only principal a's range, got %+v", got) + } +} + +func TestManagerScopedLeaseEndsAtEarlierOfTTLAndNotAfter(t *testing.T) { + cases := []struct { + name string + notAfter time.Duration + ends time.Duration + }{ + {name: "ttl first", notAfter: time.Hour, ends: 15 * time.Second}, + {name: "token expiry first", notAfter: 5 * time.Second, ends: 5 * time.Second}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + m, clock, start := newScopedTestManager() + lk := Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1, Principal: "a"} + m.TryLock("k", lk, Lease{TTL: 15 * time.Second, NotAfter: start.Add(tc.notAfter)}) + other := Range{Start: 0, End: 99, Type: Write, Sid: 2, Owner: 1, Principal: "b"} + + clock.Set(start.Add(tc.ends - time.Nanosecond)) + if _, found := m.GetLk("k", other); !found { + t.Fatal("lease must hold until its deadline") + } + clock.Set(start.Add(tc.ends)) + if _, granted, _ := m.TryLock("k", other, Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour)}); !granted { + t.Fatal("an expired lease must not block a new holder") + } + if _, ok := m.sessions[lk.Session()]; ok { + t.Fatal("expired session and its lease should be forgotten") + } + }) + } +} + +func TestManagerScopedRenewalExtendsOnlyTheRenewedKey(t *testing.T) { + m, clock, start := newScopedTestManager() + lease := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour)} + ss := Session{Principal: "a", Sid: 1} + m.TryLock("a", Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"}, lease) + m.TryLock("b", Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"}, lease) + + clock.Set(start.Add(10 * time.Second)) + m.Renew("a", ss, lease) + clock.Set(start.Add(15 * time.Second)) + other := Range{Start: 0, End: 9, Type: Write, Sid: 2, Owner: 1, Principal: "b"} + if _, found := m.GetLk("a", other); !found { + t.Fatal("renewed key a must still be held") + } + if _, found := m.GetLk("b", other); found { + t.Fatal("key b was not renewed and must have expired") + } + if holds(m, ss, "b") { + t.Fatal("key b's lease and index entry should be gone") + } + clock.Set(start.Add(25 * time.Second)) + if _, found := m.GetLk("a", other); found { + t.Fatal("key a's renewed lease ends 15s after the renewal") + } +} + +func TestManagerScopedRenewWithoutLocksLeasesNothing(t *testing.T) { + m, _, start := newScopedTestManager() + m.Renew("k", Session{Principal: "a", Sid: 1}, Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour)}) + if len(m.sessions) != 0 { + t.Fatalf("a renewal of nothing must record nothing: %v", m.sessions) + } +} + +func TestManagerReapExpiredDropsScopedLeasesAndKeepsUnleasedUnscopedLocks(t *testing.T) { + m, clock, start := newScopedTestManager() + lease := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour)} + m.TryLock("scoped", Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"}, lease) + m.TryLock("unscoped", Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1}, lease) + + clock.Set(start.Add(time.Hour)) + if reaped := m.ReapExpired(15 * time.Second); len(reaped) != 1 || reaped[0] != 1 { + t.Fatalf("only the scoped lease should be reaped, got %v", reaped) + } + held := m.Snapshot() + if len(held["scoped"]) != 0 || len(held["unscoped"]) != 1 { + t.Fatalf("sweep should drop the scoped lock and keep the never-renewed unscoped one: %+v", held) + } + if _, ok := m.sessions[Session{Principal: "a", Sid: 1}]; ok { + t.Fatal("reaped leases should be forgotten") + } + if !holds(m, Session{Sid: 1}, "unscoped") { + t.Fatal("the unscoped session's index must survive") + } +} + +func TestManagerExpiredScopedSessionWithManyRangesIsDroppedWhole(t *testing.T) { + m, clock, start := newScopedTestManager() + lease := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour)} + keep := Range{Start: 0, End: 9, Type: Read, Sid: 2, Owner: 2, Principal: "b"} + if _, granted, _ := m.TryLock("k", keep, lease); !granted { + t.Fatal("unexpired holder should be granted") + } + // Disjoint ranges that never coalesce, interleaved with another session's. + for i := uint64(1); i <= 50; i++ { + lk := Range{Start: i * 100, End: i*100 + 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"} + if _, granted, _ := m.TryLock("k", lk, lease); !granted { + t.Fatalf("range %d should be granted", i) + } + } + clock.Set(start.Add(10 * time.Second)) + m.Renew("k", keep.Session(), lease) + clock.Set(start.Add(16 * time.Second)) + + other := Range{Start: 100, End: 5009, Type: Write, Sid: 3, Owner: 3, Principal: "c"} + if c, granted, _ := m.TryLock("k", other, lease); !granted { + t.Fatalf("expired session's ranges should be gone, conflict %+v", c) + } + expired := Session{Principal: "a", Sid: 1} + if _, indexed := m.sessions[expired]; indexed { + t.Fatal("expired session is still indexed") + } + if got := m.Snapshot()["k"]; len(got) != 2 || got[0] != keep { + t.Fatalf("unexpired holder or new grant missing: %+v", got) + } +} + +func TestManagerSeveralExpiredScopedSessionsAreDroppedTogether(t *testing.T) { + m, clock, start := newScopedTestManager() + lease := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour)} + keep := Range{Start: 0, End: 9, Type: Read, Sid: 9, Owner: 9, Principal: "keep"} + m.TryLock("k", keep, lease) + for i := uint64(1); i <= 20; i++ { + principal := []string{"a", "b", "c"}[i%3] + lk := Range{Start: i * 100, End: i*100 + 9, Type: Read, Sid: i % 3, Owner: 1, Principal: principal} + if _, granted, _ := m.TryLock("k", lk, lease); !granted { + t.Fatalf("range %d should be granted", i) + } + } + clock.Set(start.Add(10 * time.Second)) + m.Renew("k", keep.Session(), lease) + clock.Set(start.Add(16 * time.Second)) + + if got := m.Snapshot()["k"]; len(got) != 21 { + t.Fatalf("snapshot should not reap, got %d ranges", len(got)) + } + if _, found := m.GetLk("k", Range{Start: 100, End: 2009, Type: Write, Sid: 5, Owner: 5, Principal: "w"}); found { + t.Fatal("ranges of the expired sessions are still held") + } + for _, p := range []string{"a", "b", "c"} { + for sid := uint64(0); sid < 3; sid++ { + if _, indexed := m.sessions[Session{Principal: p, Sid: sid}]; indexed { + t.Fatalf("expired session %s/%d is still indexed", p, sid) + } + } + } + if got := m.Snapshot()["k"]; len(got) != 1 || got[0] != keep { + t.Fatalf("only the renewed holder should remain: %+v", got) + } +} + +func TestManagerScopedRenewalExtendsTheSessionsKeysUnderTheSameGrant(t *testing.T) { + // A bare keepalive keeps the grant a key was taken under; a re-assertion + // takes the key again, under the request's grant. + renewals := []struct { + name string + renew func(m *Manager, key string, ss Session, lease Lease) + keptGrant string + }{ + {name: "bare keepalive", keptGrant: "narrow", renew: func(m *Manager, key string, ss Session, lease Lease) { m.Renew(key, ss, lease) }}, + {name: "reassertion", keptGrant: "g", renew: func(m *Manager, key string, ss Session, lease Lease) { + m.Reassert(key, ss, []Range{{Start: 0, End: 9, Type: Write, Owner: 1}}, lease) + }}, + } + for _, r := range renewals { + t.Run(r.name, func(t *testing.T) { + m, clock, start := newScopedTestManager() + lease := func(grant string) Lease { + return Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour), Grant: grant} + } + lock := func(key, principal string, sid uint64, grant string) { + lk := Range{Start: 0, End: 9, Type: Write, Sid: sid, Owner: 1, Principal: principal} + if _, granted, _ := m.TryLock(key, lk, lease(grant)); !granted { + t.Fatalf("%s should be granted", key) + } + } + ss := Session{Principal: "a", Sid: 1} + for _, key := range []string{"k1", "k2", "k3"} { + lock(key, "a", 1, "g") + } + lock("narrow1", "a", 1, "narrow") + lock("narrow2", "a", 1, "narrow") + lock("other-sid", "a", 2, "g") + lock("other-principal", "b", 1, "g") + + clock.Set(start.Add(10 * time.Second)) + r.renew(m, "k1", ss, lease("g")) + r.renew(m, "narrow1", ss, lease("g")) + + clock.Set(start.Add(25*time.Second - time.Nanosecond)) + probe := Range{Start: 0, End: 9, Type: Write, Sid: 9, Owner: 9, Principal: "probe"} + for key, want := range map[string]bool{ + "k1": true, "k2": true, "k3": true, // same session, same grant + "narrow1": true, // renewed by name + "narrow2": false, // another grant, not named + "other-sid": false, + "other-principal": false, + } { + if _, held := m.GetLk(key, probe); held != want { + t.Errorf("%s held=%v, want %v", key, held, want) + } + } + if got := m.sessions[ss].keys["narrow1"].grant; got != r.keptGrant { + t.Fatalf("narrow1 is held under grant %q, want %q", got, r.keptGrant) + } + clock.Set(start.Add(25 * time.Second)) + for _, key := range []string{"k1", "k2", "k3", "narrow1"} { + if _, held := m.GetLk(key, probe); held { + t.Errorf("%s should end 15s after the renewal", key) + } + } + }) + } +} + +func TestManagerSameGrantRenewalIsBoundedAndDoesNotReviveEndedLeases(t *testing.T) { + m, clock, start := newScopedTestManager() + ss := Session{Principal: "a", Sid: 1} + lease := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour), Grant: "g"} + lk := Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"} + probe := Range{Start: 0, End: 9, Type: Write, Sid: 9, Owner: 9, Principal: "probe"} + m.TryLock("ended", lk, lease) + clock.Set(start.Add(10 * time.Second)) + m.TryLock("live", lk, lease) + m.TryLock("bounded", lk, lease) + + // "ended" lapsed at 15s and has not been swept; a renewal must not revive it. + clock.Set(start.Add(15 * time.Second)) + expiring := lease + expiring.NotAfter = start.Add(28 * time.Second) + m.Renew("live", ss, expiring) + if _, held := m.GetLk("ended", probe); held { + t.Fatal("a same-grant renewal revived an ended lease") + } + clock.Set(start.Add(28*time.Second - time.Nanosecond)) + if _, held := m.GetLk("bounded", probe); !held { + t.Fatal("bounded should be held until the renewal's NotAfter") + } + clock.Set(start.Add(28 * time.Second)) + for _, key := range []string{"live", "bounded"} { + if _, held := m.GetLk(key, probe); held { + t.Fatalf("%s outlived the renewal's NotAfter", key) + } + } +} + +func TestManagerScopedTryLockRefusesALeaseThatHasAlreadyEnded(t *testing.T) { + m, _, start := newScopedTestManager() + lk := Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"} + probe := Range{Start: 0, End: 9, Type: Write, Sid: 9, Owner: 9, Principal: "probe"} + + // The token expired while the request waited for the manager. + ended := Lease{TTL: 15 * time.Second, NotAfter: start, Grant: "g"} + if _, granted, err := m.TryLock("k", lk, ended); granted || !errors.Is(err, ErrLeaseEnded) { + t.Fatalf("granted=%v err=%v, want a refusal with ErrLeaseEnded", granted, err) + } + if _, held := m.GetLk("k", probe); held { + t.Fatal("a refused grant must leave no lock behind") + } + if len(m.sessions) != 0 || len(m.byKey) != 0 { + t.Fatalf("a refused grant must leave no state: %v %v", m.sessions, m.byKey) + } + + live := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Nanosecond), Grant: "g"} + if _, granted, err := m.TryLock("k", lk, live); !granted || err != nil { + t.Fatalf("granted=%v err=%v, want a grant while the lease is still running", granted, err) + } + // Unscoped locks carry no lease. + unscoped := Range{Start: 0, End: 9, Type: Write, Sid: 2, Owner: 1} + if _, granted, err := m.TryLock("u", unscoped, Lease{}); !granted || err != nil { + t.Fatalf("granted=%v err=%v, want an unscoped grant", granted, err) + } +} + +func TestManagerSameGrantRenewalSkipsTheScanWhileKeysLastLongEnough(t *testing.T) { + m, clock, start := newScopedTestManager() + ss := Session{Principal: "a", Sid: 1} + lease := Lease{TTL: 16 * time.Second, NotAfter: start.Add(time.Hour), Grant: "g"} + lk := Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"} + for _, key := range []string{"k1", "k2", "k3"} { + m.TryLock(key, lk, lease) + } + deadlines := func() []time.Duration { + var out []time.Duration + for _, key := range []string{"k1", "k2", "k3"} { + out = append(out, m.sessions[ss].keys[key].deadline.Sub(start)) + } + return out + } + steps := []struct { + at time.Duration + key string + want []time.Duration + }{ + // Scans: every key ends at 26s. + {10 * time.Second, "k1", []time.Duration{26 * time.Second, 26 * time.Second, 26 * time.Second}}, + // Every key still lasts 12s (three quarters of the TTL): only k2 moves. + {13 * time.Second, "k2", []time.Duration{26 * time.Second, 29 * time.Second, 26 * time.Second}}, + {14 * time.Second, "k1", []time.Duration{30 * time.Second, 29 * time.Second, 26 * time.Second}}, + // k3 would last less than 12s: scans again. + {14*time.Second + time.Millisecond, "k2", []time.Duration{30001 * time.Millisecond, 30001 * time.Millisecond, 30001 * time.Millisecond}}, + } + for _, step := range steps { + clock.Set(start.Add(step.at)) + m.Renew(step.key, ss, lease) + if got := deadlines(); !reflect.DeepEqual(got, step.want) { + t.Fatalf("after renewing %s at %v: deadlines %v, want %v", step.key, step.at, got, step.want) + } + } +} + +func TestManagerSameGrantRenewalUnderALaterExpiringTokenScansAtOnce(t *testing.T) { + // A replacement token with the same id and grants but a later expiry must + // not leave the other keys on the old token's expiry. + m, clock, start := newScopedTestManager() + ss := Session{Principal: "a", Sid: 1} + expiring := Lease{TTL: 15 * time.Second, NotAfter: start.Add(2 * time.Second), Grant: "g"} + replaced := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour), Grant: "g"} + lk := Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"} + probe := Range{Start: 0, End: 9, Type: Write, Sid: 9, Owner: 9, Principal: "probe"} + m.TryLock("k1", lk, expiring) + m.TryLock("k2", lk, expiring) + m.Renew("k1", ss, expiring) // every key ends at the token's expiry, 2s + clock.Set(start.Add(time.Second)) + m.Renew("k1", ss, replaced) + clock.Set(start.Add(3 * time.Second)) + if _, held := m.GetLk("k2", probe); !held { + t.Fatal("k2 expired with the old token although the replacement renewed its grant") + } +} + +func TestManagerSameGrantRenewalScansAgainAfterAKeyIsLeasedForLess(t *testing.T) { + m, clock, start := newScopedTestManager() + ss := Session{Principal: "a", Sid: 1} + lease := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour), Grant: "g"} + short := Lease{TTL: 15 * time.Second, NotAfter: start.Add(4 * time.Second), Grant: "g"} + lk := Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"} + probe := Range{Start: 0, End: 9, Type: Write, Sid: 9, Owner: 9, Principal: "probe"} + m.TryLock("k1", lk, lease) + m.Renew("k1", ss, lease) // floor at 15s + m.TryLock("k2", lk, short) + clock.Set(start.Add(time.Second)) + m.Renew("k1", ss, lease) // k2 ends at 4s, below the floor: must scan + clock.Set(start.Add(5 * time.Second)) + if _, held := m.GetLk("k2", probe); !held { + t.Fatal("k2 kept its shorter lease although its grant was renewed") + } +} + +func TestManagerScopedKeepalivesWithoutLocksLeaveNoState(t *testing.T) { + m, _, start := newScopedTestManager() + lease := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour), Grant: "g"} + for sid := uint64(1); sid <= 100; sid++ { + m.Renew("k", Session{Principal: "a", Sid: sid}, lease) + } + if len(m.sessions) != 0 { + t.Fatalf("keepalives of sessions without locks left state for %d sessions", len(m.sessions)) + } + // A session's floors go with its last lease. + ss := Session{Principal: "a", Sid: 1} + lk := Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"} + m.TryLock("k", lk, lease) + m.Renew("k", ss, lease) + if len(m.sessions[ss].floors) != 1 { + t.Fatalf("a renewing session should have one floor, got %v", m.sessions[ss].floors) + } + m.Unlock("k", lk) + if len(m.sessions) != 0 { + t.Fatalf("unlocking the last lock left state: %v", m.sessions) + } +} + +func TestManagerManyKeysRenewedOneByOneStayHeldThroughLongRounds(t *testing.T) { + // A mount renews its keys one keepalive at a time; a round over 128 keys at + // 200ms each takes 25.6s, longer than the 15s lease. + m, clock, start := newScopedTestManager() + ss := Session{Principal: "a", Sid: 1} + lease := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour), Grant: "g"} + lk := Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"} + probe := Range{Start: 0, End: 9, Type: Write, Sid: 9, Owner: 9, Principal: "probe"} + keys := make([]string, 128) + for i := range keys { + keys[i] = fmt.Sprintf("k%03d", i) + m.TryLock(keys[i], lk, lease) + } + now := start + for step := 0; step < 3*len(keys); step++ { + now = now.Add(200 * time.Millisecond) + clock.Set(now) + m.Renew(keys[step%len(keys)], ss, lease) + for _, key := range keys { + if _, held := m.GetLk(key, probe); !held { + t.Fatalf("%s was lost at %v while its session kept renewing", key, now.Sub(start)) + } + } + } +} + +func TestManagerScopedRenewalUnderAnEarlierExpiringTokenKeepsTheLaterLease(t *testing.T) { + // A request under the old token can land after the replacement renewed the + // key; it must not cut the lease back to the old token's expiry. + m, clock, start := newScopedTestManager() + ss := Session{Principal: "a", Sid: 1} + expiring := Lease{TTL: 15 * time.Second, NotAfter: start.Add(2 * time.Second), Grant: "g"} + replaced := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour), Grant: "g"} + lk := Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"} + probe := Range{Start: 0, End: 9, Type: Write, Sid: 9, Owner: 9, Principal: "probe"} + for name, late := range map[string]func(){ + "renew": func() { m.Renew("k", ss, expiring) }, + "reassert": func() { m.Reassert("k", ss, []Range{lk}, expiring) }, + "trylock": func() { m.TryLock("k", lk, expiring) }, + } { + t.Run(name, func(t *testing.T) { + clock.Set(start) + m.ReleaseSession(ss) + m.TryLock("k", lk, replaced) + clock.Set(start.Add(time.Second)) + late() + clock.Set(start.Add(3 * time.Second)) + if _, held := m.GetLk("k", probe); !held { + t.Fatal("the old token's request cut the replacement's lease back to its own expiry") + } + }) + } +} diff --git a/weed/filer/posixlock/reassert_test.go b/weed/filer/posixlock/reassert_test.go index 948c47b0d5..6f767e4395 100644 --- a/weed/filer/posixlock/reassert_test.go +++ b/weed/filer/posixlock/reassert_test.go @@ -20,16 +20,16 @@ func TestReassertRebuildsOnFreshOwner(t *testing.T) { // Fresh owner (post-restart / new ring owner) knows nothing. owner := NewManager() for key, locks := range client.Snapshot() { - if c := owner.Reassert(key, sid, locks); c != nil { + if c := owner.Reassert(key, Session{Sid: sid}, locks, Lease{}); c != nil { t.Fatalf("unexpected conflict reasserting %s: %+v", key, c) } } // The owner now reports the same conflicts a foreign session would hit. - if _, granted := owner.TryLock("a", Range{Start: 50, End: 60, Type: Write, Sid: 99, Owner: 1}); granted { + if _, granted, _ := owner.TryLock("a", Range{Start: 50, End: 60, Type: Write, Sid: 99, Owner: 1}, Lease{}); granted { t.Fatal("owner should block a foreign write after rebuild") } - if _, granted := owner.TryLock("b", Range{Start: 0, End: 0, Type: Read, Sid: 99, Owner: 1, IsFlock: true}); granted { + if _, granted, _ := owner.TryLock("b", Range{Start: 0, End: 0, Type: Read, Sid: 99, Owner: 1, IsFlock: true}, Lease{}); granted { t.Fatal("owner should block a foreign flock read after rebuild") } } @@ -38,11 +38,11 @@ func TestReassertRebuildsOnFreshOwner(t *testing.T) { func TestReassertIdempotent(t *testing.T) { const sid = uint64(1) m := NewManager() - m.TryLock("k", Range{Start: 0, End: 99, Type: Write, Sid: sid, Owner: 1}) + m.TryLock("k", Range{Start: 0, End: 99, Type: Write, Sid: sid, Owner: 1}, Lease{}) before := append([]Range(nil), m.byKey["k"].locks...) - m.Reassert("k", sid, before) - m.Reassert("k", sid, before) + m.Reassert("k", Session{Sid: sid}, before, Lease{}) + m.Reassert("k", Session{Sid: sid}, before, Lease{}) if !reflect.DeepEqual(m.byKey["k"].locks, before) { t.Fatalf("reassert not idempotent:\n got %+v\nwant %+v", m.byKey["k"].locks, before) @@ -55,9 +55,9 @@ func TestReassertReportsConflict(t *testing.T) { const mine, other = uint64(1), uint64(2) m := NewManager() // Another mount took the lock on this (new) owner during the gap. - m.TryLock("k", Range{Start: 0, End: 99, Type: Write, Sid: other, Owner: 1}) + m.TryLock("k", Range{Start: 0, End: 99, Type: Write, Sid: other, Owner: 1}, Lease{}) - conflicts := m.Reassert("k", mine, []Range{{Start: 0, End: 99, Type: Write, Sid: mine, Owner: 1}}) + conflicts := m.Reassert("k", Session{Sid: mine}, []Range{{Start: 0, End: 99, Type: Write, Sid: mine, Owner: 1}}, Lease{}) if len(conflicts) != 1 { t.Fatalf("expected 1 conflict, got %d: %+v", len(conflicts), conflicts) } @@ -71,8 +71,8 @@ func TestReassertReportsConflict(t *testing.T) { func TestReassertRenewsLease(t *testing.T) { const sid = uint64(1) m := NewManager() - m.Renew(sid) - m.Reassert("k", sid, []Range{{Start: 0, End: 9, Type: Write, Sid: sid, Owner: 1}}) + m.Renew("", Session{Sid: sid}, Lease{}) + m.Reassert("k", Session{Sid: sid}, []Range{{Start: 0, End: 9, Type: Write, Sid: sid, Owner: 1}}, Lease{}) if reaped := m.ReapExpired(time.Hour); len(reaped) != 0 { t.Fatalf("freshly re-asserted session should not be reaped: %v", reaped) diff --git a/weed/mount/weedfs.go b/weed/mount/weedfs.go index 9d43023e21..a1c6f3b143 100644 --- a/weed/mount/weedfs.go +++ b/weed/mount/weedfs.go @@ -189,6 +189,7 @@ type WFS struct { posixSid uint64 // this mount's session id, for routed-lock owner identity posixHint *posixLockHint // local fcntl-lock hint for routed mode posixOwn *posixlock.Manager // mirror of locks this mount holds, re-asserted via keepalive + posixLostKeys sync.Map // keys whose lock loss was already reported, see notePosixLockLoss fhLocks fhLockOwners // non-flock lock owners per open fh, drained at release peerRegistrar *PeerRegistrar peerDirectory *PeerDirectory diff --git a/weed/mount/weedfs_posix_lock_routed.go b/weed/mount/weedfs_posix_lock_routed.go index d2f32fa3d7..f63d63060c 100644 --- a/weed/mount/weedfs_posix_lock_routed.go +++ b/weed/mount/weedfs_posix_lock_routed.go @@ -305,7 +305,7 @@ func (wfs *WFS) routedReleasePosixOwner(inode, owner uint64) bool { if !ok { return false } - wfs.posixOwn.ReleasePosixOwner(key, wfs.posixSid, owner) + wfs.posixOwn.ReleasePosixOwner(key, posixlock.Session{Sid: wfs.posixSid}, owner) ctx, cancel := context.WithTimeout(context.Background(), posixLockReleaseTimeout) defer cancel() if _, err := wfs.callPosixLock(ctx, key, filer_pb.PosixLockOp_RELEASE_POSIX_OWNER, posixlock.Range{Sid: wfs.posixSid, Owner: owner}); err != nil { @@ -324,7 +324,7 @@ func (wfs *WFS) routedReleaseFlockOwner(inode, owner uint64) { if !ok { return } - wfs.posixOwn.ReleaseFlockOwner(key, wfs.posixSid, owner) + wfs.posixOwn.ReleaseFlockOwner(key, posixlock.Session{Sid: wfs.posixSid}, owner) ctx, cancel := context.WithTimeout(context.Background(), posixLockReleaseTimeout) defer cancel() if _, err := wfs.callPosixLock(ctx, key, filer_pb.PosixLockOp_RELEASE_FLOCK_OWNER, posixlock.Range{Sid: wfs.posixSid, Owner: owner}); err != nil { @@ -373,8 +373,10 @@ func (wfs *WFS) hasPosixOwner(inode, owner uint64) bool { // callPosixReassert sends the mount's held locks on key to the key's current // owner filer as a KEEP_ALIVE, which renews the lease and lets the owner rebuild -// its in-memory state after a takeover or restart. -func (wfs *WFS) callPosixReassert(ctx context.Context, key string, locks []posixlock.Range) error { +// its in-memory state after a takeover or restart. It returns a lock another +// session now holds in place of one of this mount's, or nil; filers that do not +// report losses always return nil. +func (wfs *WFS) callPosixReassert(ctx context.Context, key string, locks []posixlock.Range) (lost *filer_pb.PosixLockRange, err error) { pbLocks := make([]*filer_pb.PosixLockRange, 0, len(locks)) for _, l := range locks { pbLocks = append(pbLocks, &filer_pb.PosixLockRange{ @@ -382,15 +384,36 @@ func (wfs *WFS) callPosixReassert(ctx context.Context, key string, locks []posix Sid: l.Sid, Owner: l.Owner, Pid: l.Pid, IsFlock: l.IsFlock, }) } - return wfs.withFilerClient(ctx, false, wfs.filerRPCWait(), func(ctx context.Context, client filer_pb.SeaweedFilerClient) error { - _, e := client.PosixLock(ctx, &filer_pb.PosixLockRequest{ + err = wfs.withFilerClient(ctx, false, wfs.filerRPCWait(), func(ctx context.Context, client filer_pb.SeaweedFilerClient) error { + resp, e := client.PosixLock(ctx, &filer_pb.PosixLockRequest{ Key: key, Op: filer_pb.PosixLockOp_KEEP_ALIVE, Lock: &filer_pb.PosixLockRange{Sid: wfs.posixSid}, Locks: pbLocks, }) + if e == nil && resp.GetHasConflict() { + lost = resp.GetConflict() + } return e }) + return lost, err +} + +// notePosixLockLoss warns once when a re-assertion finds that another session +// holds a lock this mount still believes it holds on key, typically after the +// mount's lease lapsed, and forgets the loss once a re-assertion succeeds. The +// application is not told: POSIX has no signal for a lost lock. It reports +// whether it warned. +func (wfs *WFS) notePosixLockLoss(key string, lost *filer_pb.PosixLockRange) bool { + if lost == nil { + wfs.posixLostKeys.Delete(key) + return false + } + if _, warned := wfs.posixLostKeys.LoadOrStore(key, struct{}{}); warned { + return false + } + glog.Warningf("posix lock on %s lost: another session holds [%d, %d]; this mount's application may still believe it holds the lock", key, lost.GetStart(), lost.GetEnd()) + return true } // posixKeepaliveConcurrency bounds the parallel keepalive RPCs per tick. A mount @@ -420,11 +443,21 @@ func (wfs *WFS) loopRenewPosixLeases() { // and get reaped. ctx, cancel := context.WithTimeout(context.Background(), posixLockReleaseTimeout) defer cancel() - if err := wfs.callPosixReassert(ctx, key, locks); err != nil { + lost, err := wfs.callPosixReassert(ctx, key, locks) + if err != nil { glog.V(2).Infof("posix reassert %s: %v", key, err) + return } + wfs.notePosixLockLoss(key, lost) }() } wg.Wait() + // Forget losses on keys this mount no longer holds locks on. + wfs.posixLostKeys.Range(func(key, _ any) bool { + if _, stillHeld := held[key.(string)]; !stillHeld { + wfs.posixLostKeys.Delete(key) + } + return true + }) } } diff --git a/weed/mount/weedfs_posix_lock_routed_test.go b/weed/mount/weedfs_posix_lock_routed_test.go index 064ea49eeb..dab1ffb895 100644 --- a/weed/mount/weedfs_posix_lock_routed_test.go +++ b/weed/mount/weedfs_posix_lock_routed_test.go @@ -9,6 +9,7 @@ import ( "github.com/seaweedfs/go-fuse/v2/fuse" "github.com/seaweedfs/seaweedfs/weed/filer/posixlock" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" ) func TestPosixLockTypeMapping(t *testing.T) { @@ -94,3 +95,23 @@ func TestPosixLockHint(t *testing.T) { t.Fatal("inode entry should be removed when its last owner drops") } } + +func TestNotePosixLockLossWarnsOncePerLoss(t *testing.T) { + wfs := &WFS{} + lost := &filer_pb.PosixLockRange{Start: 0, End: 99, Pid: 7} + if !wfs.notePosixLockLoss("k", lost) { + t.Fatal("first loss on a key should warn") + } + if wfs.notePosixLockLoss("k", lost) { + t.Fatal("a loss already reported should not warn again on every keepalive") + } + if !wfs.notePosixLockLoss("other", lost) { + t.Fatal("a loss on another key should warn") + } + if wfs.notePosixLockLoss("k", nil) { + t.Fatal("a successful re-assertion should not warn") + } + if !wfs.notePosixLockLoss("k", lost) { + t.Fatal("a new loss after a successful re-assertion should warn again") + } +} diff --git a/weed/server/filer_grpc_scope_posix_ownership_test.go b/weed/server/filer_grpc_scope_posix_ownership_test.go new file mode 100644 index 0000000000..9006213cb1 --- /dev/null +++ b/weed/server/filer_grpc_scope_posix_ownership_test.go @@ -0,0 +1,566 @@ +package weed_server + +import ( + "context" + "fmt" + "net" + "reflect" + "sync" + "sync/atomic" + "testing" + "time" + + jwt "github.com/golang-jwt/jwt/v5" + "github.com/seaweedfs/seaweedfs/weed/filer/posixlock" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" +) + +const posixOwnershipKey = scopePosixLockKeyPrefix + "/locks/file" + +type posixTestClock struct { + mu sync.Mutex + now time.Time +} + +func (c *posixTestClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.now +} + +// posixOwnershipHarness serves a real FilerServer PosixLock handler behind the +// scope interceptor, with the lock manager on a controllable clock. +type posixOwnershipHarness struct { + t *testing.T + fs *FilerServer + clock *posixTestClock + start time.Time + addr string + keys atomic.Value // [2]string: current and previous verification key +} + +func newPosixOwnershipHarness(t *testing.T, leeway time.Duration) *posixOwnershipHarness { + t.Helper() + h := &posixOwnershipHarness{t: t, clock: &posixTestClock{now: time.Now()}} + h.start = h.clock.Now() + h.fs = newPosixTestServer(t) + h.fs.posixLocks = posixlock.NewManagerWithClock(h.clock.Now) + h.keys.Store([2]string{scopeTestKey, ""}) + sc := newFilerGrpcScope(scopeConfig{ + verificationKeys: func() (security.SigningKey, security.SigningKey) { + keys := h.keys.Load().([2]string) + return security.SigningKey(keys[0]), security.SigningKey(keys[1]) + }, + leeway: func() time.Duration { return leeway }, + }, h.fs) + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + srv := grpc.NewServer(sc.ServerOptions()...) + filer_pb.RegisterSeaweedFilerServer(srv, h.fs) + go func() { _ = srv.Serve(lis) }() + t.Cleanup(func() { srv.Stop(); _ = lis.Close() }) + h.addr = lis.Addr().String() + return h +} + +// at moves the lock manager's clock to d after the harness start. +func (h *posixOwnershipHarness) at(d time.Duration) { + h.clock.mu.Lock() + defer h.clock.mu.Unlock() + h.clock.now = h.start.Add(d) +} + +func (h *posixOwnershipHarness) client(token string) filer_pb.SeaweedFilerClient { + h.t.Helper() + conn, err := grpc.NewClient("passthrough:///"+h.addr, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithPerRPCCredentials(scopeToken(token))) + if err != nil { + h.t.Fatal(err) + } + h.t.Cleanup(func() { _ = conn.Close() }) + return filer_pb.NewSeaweedFilerClient(conn) +} + +func (h *posixOwnershipHarness) call(c filer_pb.SeaweedFilerClient, key string, op filer_pb.PosixLockOp, lk *filer_pb.PosixLockRange, held ...*filer_pb.PosixLockRange) (*filer_pb.PosixLockResponse, error) { + return c.PosixLock(scopeCtx(h.t), &filer_pb.PosixLockRequest{Key: key, Op: op, Lock: lk, Locks: held}) +} + +func (h *posixOwnershipHarness) must(c filer_pb.SeaweedFilerClient, key string, op filer_pb.PosixLockOp, lk *filer_pb.PosixLockRange, held ...*filer_pb.PosixLockRange) *filer_pb.PosixLockResponse { + h.t.Helper() + resp, err := h.call(c, key, op, lk, held...) + if err != nil { + h.t.Fatalf("PosixLock %v: %v", op, err) + } + return resp +} + +func (h *posixOwnershipHarness) held(key string) []posixlock.Range { + return h.fs.posixLocks.Snapshot()[key] +} + +// grantable reports whether a fresh scoped holder could take lk's range now. +func (h *posixOwnershipHarness) grantable(key string, flock bool) bool { + h.t.Helper() + probe := h.client(scopedToken("newcomer", time.Hour, []string{"/locks"}, nil)) + resp := h.must(probe, key, filer_pb.PosixLockOp_GET_LK, pbLock(0, 99, posixlock.Write, 50, 51, 9, flock)) + return !resp.GetHasConflict() +} + +func expectPosixCode(t *testing.T, what string, err error, code codes.Code) { + t.Helper() + if status.Code(err) != code { + t.Fatalf("%s: got %v, want %v", what, err, code) + } +} + +func TestScopedPosixLockSurvivesReplayOfItsDisclosedIdentity(t *testing.T) { + intruders := []struct { + name string + token func() string + }{ + {name: "another scoped token", token: func() string { return scopedToken("intruder", time.Hour, []string{"/locks"}, nil) }}, + {name: "tokenless", token: func() string { return "" }}, + {name: "unscoped token", token: unscopedToken}, + } + attacks := []struct { + name string + op filer_pb.PosixLockOp + lock func(known *filer_pb.PosixLockRange) *filer_pb.PosixLockRange + held bool + }{ + {name: "partial unlock", op: filer_pb.PosixLockOp_UNLOCK, lock: func(k *filer_pb.PosixLockRange) *filer_pb.PosixLockRange { + return pbLock(10, 20, posixlock.Unlock, k.Sid, k.Owner, 8, k.IsFlock) + }}, + {name: "release posix owner", op: filer_pb.PosixLockOp_RELEASE_POSIX_OWNER, lock: func(k *filer_pb.PosixLockRange) *filer_pb.PosixLockRange { return k }}, + {name: "release flock owner", op: filer_pb.PosixLockOp_RELEASE_FLOCK_OWNER, lock: func(k *filer_pb.PosixLockRange) *filer_pb.PosixLockRange { return k }}, + {name: "bare keepalive", op: filer_pb.PosixLockOp_KEEP_ALIVE, lock: func(k *filer_pb.PosixLockRange) *filer_pb.PosixLockRange { + return &filer_pb.PosixLockRange{Sid: k.Sid} + }}, + {name: "reassertion", op: filer_pb.PosixLockOp_KEEP_ALIVE, held: true, lock: func(k *filer_pb.PosixLockRange) *filer_pb.PosixLockRange { + return &filer_pb.PosixLockRange{Sid: k.Sid} + }}, + {name: "try lock", op: filer_pb.PosixLockOp_TRY_LOCK, lock: func(k *filer_pb.PosixLockRange) *filer_pb.PosixLockRange { + return pbLock(0, 99, posixlock.Write, k.Sid, k.Owner, 8, k.IsFlock) + }}, + } + for _, flock := range []bool{false, true} { + for _, intruder := range intruders { + for _, attack := range attacks { + name := map[bool]string{false: "fcntl", true: "flock"}[flock] + "/" + intruder.name + "/" + attack.name + t.Run(name, func(t *testing.T) { + h := newPosixOwnershipHarness(t, 0) + holder := h.client(scopedToken("holder", time.Hour, []string{"/locks"}, nil)) + if !h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, flock)).Granted { + t.Fatal("holder's acquisition refused") + } + before := h.held(posixOwnershipKey) + + c := h.client(intruder.token()) + query := pbLock(0, 99, posixlock.Write, 3, 4, 8, flock) + known := h.must(c, posixOwnershipKey, filer_pb.PosixLockOp_GET_LK, query).GetConflict() + if known.GetSid() != 1 || known.GetOwner() != 2 || known.GetPid() != 7 { + t.Fatalf("GET_LK should disclose the holder, got %+v", known) + } + + h.at(10 * time.Second) + var held []*filer_pb.PosixLockRange + if attack.held { + held = []*filer_pb.PosixLockRange{pbLock(0, 99, posixlock.Write, known.Sid, known.Owner, 8, flock)} + } + resp := h.must(c, posixOwnershipKey, attack.op, attack.lock(known), held...) + if resp.GetGranted() { + t.Fatal("the holder's identity must not grant another caller its lock") + } + if got := h.held(posixOwnershipKey); !reflect.DeepEqual(got, before) { + t.Fatalf("holder's locks changed:\n got %+v\nwant %+v", got, before) + } + if !h.must(c, posixOwnershipKey, filer_pb.PosixLockOp_GET_LK, pbLock(0, 99, posixlock.Write, known.Sid, known.Owner, 8, flock)).GetHasConflict() { + t.Fatal("the disclosed identity must still conflict for another caller") + } + + // The intruder renewed nothing: the holder's lease still ends 15s + // after its acquisition. + h.at(15*time.Second - time.Nanosecond) + if h.grantable(posixOwnershipKey, flock) { + t.Fatal("holder's lease must last until its deadline") + } + h.at(15 * time.Second) + if !h.grantable(posixOwnershipKey, flock) { + t.Fatal("holder's lease was extended by another caller") + } + }) + } + } + } +} + +func TestScopedPosixLockHolderUnlocksReleasesAndRenewsItsOwnLocks(t *testing.T) { + for _, flock := range []bool{false, true} { + t.Run(map[bool]string{false: "fcntl", true: "flock"}[flock], func(t *testing.T) { + h := newPosixOwnershipHarness(t, 0) + holder := h.client(scopedToken("holder", time.Hour, []string{"/locks"}, nil)) + h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, flock)) + + h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_UNLOCK, pbLock(10, 20, posixlock.Unlock, 1, 2, 7, flock)) + if got := h.held(posixOwnershipKey); len(got) != 2 || got[0].End != 9 || got[1].Start != 21 { + t.Fatalf("partial unlock should split the holder's range, got %+v", got) + } + release := filer_pb.PosixLockOp_RELEASE_POSIX_OWNER + if flock { + release = filer_pb.PosixLockOp_RELEASE_FLOCK_OWNER + } + h.must(holder, posixOwnershipKey, release, pbLock(0, 0, posixlock.Unlock, 1, 2, 7, flock)) + if got := h.held(posixOwnershipKey); len(got) != 0 { + t.Fatalf("owner release should drop the holder's locks, got %+v", got) + } + + h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, flock)) + h.at(10 * time.Second) + h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}) + h.at(20 * time.Second) + if h.grantable(posixOwnershipKey, flock) { + t.Fatal("a bare keepalive should renew the holder's lease") + } + h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}, pbLock(0, 99, posixlock.Write, 1, 2, 7, flock)) + h.at(35*time.Second - time.Nanosecond) + if h.grantable(posixOwnershipKey, flock) { + t.Fatal("a reassertion should renew the holder's lease") + } + h.at(35 * time.Second) + if !h.grantable(posixOwnershipKey, flock) { + t.Fatal("the lease should end 15s after the last renewal") + } + }) + } +} + +func TestScopedPosixLockLeaseEndsAtTokenExpiryPlusLeeway(t *testing.T) { + const leeway = 2 * time.Second + h := newPosixOwnershipHarness(t, leeway) + exp := time.Now().Add(time.Hour).Truncate(time.Second) + h.start = exp.Add(-5 * time.Second) + h.at(0) + holder := h.client(signedScopeClaims(t, scopeTestKey, security.SeaweedFilerClaims{ + AllowedPrefixes: []string{"/locks"}, + RegisteredClaims: jwt.RegisteredClaims{ID: "holder", ExpiresAt: jwt.NewNumericDate(exp)}, + })) + h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)) + h.at(time.Second) + h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}) + + h.at(5*time.Second + leeway - time.Nanosecond) + if h.grantable(posixOwnershipKey, false) { + t.Fatal("the lease should last until the token's expiry plus leeway") + } + h.at(5*time.Second + leeway) + if !h.grantable(posixOwnershipKey, false) { + t.Fatal("a renewal must not extend the lease past the token's expiry plus leeway") + } +} + +func TestScopedPosixLockRenewalWithNarrowerGrantLeavesOtherKeysToExpire(t *testing.T) { + keyA := scopePosixLockKeyPrefix + "/locks/a" + keyB := scopePosixLockKeyPrefix + "/locks/b" + for _, reassert := range []bool{false, true} { + t.Run(map[bool]string{false: "bare keepalive", true: "reassertion"}[reassert], func(t *testing.T) { + h := newPosixOwnershipHarness(t, 0) + wide := h.client(scopedToken("holder", time.Hour, []string{"/locks"}, nil)) + h.must(wide, keyA, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)) + h.must(wide, keyB, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)) + + h.at(10 * time.Second) + narrow := h.client(scopedToken("holder", time.Hour, []string{"/locks/a"}, nil)) + var held []*filer_pb.PosixLockRange + if reassert { + held = []*filer_pb.PosixLockRange{pbLock(0, 99, posixlock.Write, 1, 2, 7, false)} + } + h.must(narrow, keyA, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}, held...) + _, err := h.call(narrow, keyB, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}) + expectPosixCode(t, "bare keepalive outside the renewed grant", err, codes.PermissionDenied) + _, err = h.call(narrow, keyB, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)) + expectPosixCode(t, "reassertion outside the renewed grant", err, codes.PermissionDenied) + + h.at(15 * time.Second) + if !h.grantable(keyB, false) { + t.Fatal("key b keeps only its previous deadline") + } + if h.grantable(keyA, false) { + t.Fatal("key a was renewed under the narrower grant") + } + h.at(25 * time.Second) + if !h.grantable(keyA, false) { + t.Fatal("key a's lease ends 15s after its renewal") + } + }) + } +} + +func TestScopeGrantFingerprintIgnoresOrderAndRepetitionOnly(t *testing.T) { + base := []scopeGrant{{path: "/a", readWrite: true}, {path: "/b"}} + same := [][]scopeGrant{ + {{path: "/b"}, {path: "/a", readWrite: true}}, + {{path: "/a", readWrite: true}, {path: "/b"}, {path: "/a", readWrite: true}}, + } + different := [][]scopeGrant{ + {{path: "/a", readWrite: true}}, + {{path: "/a"}, {path: "/b"}}, + {{path: "/a", readWrite: true}, {path: "/b", readWrite: true}}, + {{path: "/a", readWrite: true}, {path: "/b/c"}}, + {{path: "/a", readWrite: true}, {path: "/b"}, {path: "/b", readWrite: true}}, + nil, + } + want := scopeGrantFingerprint(base) + for _, g := range same { + if got := scopeGrantFingerprint(g); got != want { + t.Errorf("%+v should match %+v", g, base) + } + } + for _, g := range different { + if got := scopeGrantFingerprint(g); got == want { + t.Errorf("%+v should not match %+v", g, base) + } + } +} + +// A mount renews its keys one keepalive at a time; with many keys a round can +// outlast the lease, so a keepalive renews all of the session's keys taken +// under the same grants, not only the key it names. +func TestScopedPosixLockKeepaliveRenewsTheSessionsKeysUnderTheSameGrants(t *testing.T) { + const keys = 128 + key := func(i int) string { return fmt.Sprintf("%s/locks/f%d", scopePosixLockKeyPrefix, i) } + for _, reassert := range []bool{false, true} { + t.Run(map[bool]string{false: "bare keepalive", true: "reassertion"}[reassert], func(t *testing.T) { + h := newPosixOwnershipHarness(t, 0) + holder := h.client(scopedToken("holder", time.Hour, []string{"/locks", "/other"}, nil)) + for i := 0; i < keys; i++ { + if !h.must(holder, key(i), filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)).Granted { + t.Fatalf("key %d refused", i) + } + } + otherSid := scopePosixLockKeyPrefix + "/locks/other-sid" + h.must(holder, otherSid, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 3, 2, 7, false)) + + // Same grants in another order and a reused id, as a remount sends them. + h.at(10 * time.Second) + remount := h.client(scopedToken("holder", time.Hour, []string{"/other", "/locks", "/locks"}, nil)) + var held []*filer_pb.PosixLockRange + if reassert { + held = []*filer_pb.PosixLockRange{pbLock(0, 99, posixlock.Write, 1, 2, 7, false)} + } + h.must(remount, key(0), filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}, held...) + + probe := h.client(scopedToken("newcomer", time.Hour, []string{"/locks"}, nil)) + grantable := func(k string) bool { + return !h.must(probe, k, filer_pb.PosixLockOp_GET_LK, pbLock(0, 99, posixlock.Write, 50, 51, 9, false)).GetHasConflict() + } + h.at(25*time.Second - time.Nanosecond) + for i := 0; i < keys; i++ { + if grantable(key(i)) { + t.Fatalf("key %d lapsed although its session renewed under the same grants", i) + } + } + if !grantable(otherSid) { + t.Fatal("another session's lock was renewed") + } + h.at(25 * time.Second) + for i := 0; i < keys; i++ { + if !grantable(key(i)) { + t.Fatalf("key %d outlived the renewed lease", i) + } + } + }) + } +} + +func TestScopedPosixLockTokenWithNewIdCannotAdoptPreviousLocks(t *testing.T) { + h := newPosixOwnershipHarness(t, 0) + old := h.client(scopedToken("holder", time.Hour, []string{"/locks"}, nil)) + h.must(old, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)) + before := h.held(posixOwnershipKey) + + h.at(10 * time.Second) + renewed := h.client(scopedToken("holder-renewed", time.Hour, []string{"/locks"}, nil)) + h.must(renewed, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)) + h.must(renewed, posixOwnershipKey, filer_pb.PosixLockOp_UNLOCK, pbLock(0, 99, posixlock.Unlock, 1, 2, 7, false)) + if got := h.held(posixOwnershipKey); !reflect.DeepEqual(got, before) { + t.Fatalf("a new token id adopted or released the previous locks: %+v", got) + } + + h.at(15 * time.Second) + if !h.must(renewed, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)).Granted { + t.Fatal("after expiry the renewed token should reacquire cleanly") + } +} + +func TestScopedPosixLockReassertionReportsALostLock(t *testing.T) { + h := newPosixOwnershipHarness(t, 0) + holder := h.client(scopedToken("holder", time.Hour, []string{"/locks"}, nil)) + h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)) + if resp := h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)); resp.HasConflict { + t.Fatalf("the holder's own re-assertion reported a loss: %+v", resp.Conflict) + } + + // The holder's lease lapses and another token takes the range. + h.at(16 * time.Second) + other := h.client(scopedToken("other", time.Hour, []string{"/locks"}, nil)) + if !h.must(other, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 49, posixlock.Write, 3, 4, 9, false)).Granted { + t.Fatal("the lapsed range should be grantable") + } + resp := h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)) + if !resp.HasConflict || resp.Conflict.GetPid() != 9 || resp.Conflict.GetEnd() != 49 { + t.Fatalf("re-assertion of a lock another session holds should report it, got %+v", resp) + } +} + +// Ownership is per token id: tokens sharing an id, such as a remount reusing +// its credential, act for the same holder, even under a fresh sid. +func TestScopedPosixLockTokensSharingAnIdShareItsLocks(t *testing.T) { + h := newPosixOwnershipHarness(t, 0) + first := h.client(scopedToken("holder", time.Hour, []string{"/locks"}, nil)) + h.must(first, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)) + + remount := h.client(scopedToken("holder", time.Hour, []string{"/locks"}, nil)) + if h.must(remount, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 5, 2, 8, false)).Granted { + t.Fatal("a fresh sid is a different owner and must conflict") + } + h.must(remount, posixOwnershipKey, filer_pb.PosixLockOp_RELEASE_POSIX_OWNER, pbLock(0, 0, posixlock.Unlock, 1, 2, 8, false)) + if got := h.held(posixOwnershipKey); len(got) != 0 { + t.Fatalf("a token with the same id controls the holder's locks, got %+v", got) + } +} + +func TestScopedPosixLockGetLkReportsConflictWithoutTransferringOwnership(t *testing.T) { + h := newPosixOwnershipHarness(t, 0) + holder := h.client(scopedToken("holder", time.Hour, []string{"/locks"}, nil)) + h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(10, 50, posixlock.Write, 1, 2, 7, false)) + + if h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_GET_LK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)).GetHasConflict() { + t.Fatal("the holder must not conflict with itself") + } + reader := h.client(scopedToken("reader", time.Hour, nil, []string{"/locks"})) + got := h.must(reader, posixOwnershipKey, filer_pb.PosixLockOp_GET_LK, pbLock(0, 99, posixlock.Read, 1, 2, 9, false)).GetConflict() + want := pbLock(10, 50, posixlock.Write, 1, 2, 7, false) + if got.GetStart() != want.Start || got.GetEnd() != want.End || got.GetType() != want.Type || got.GetSid() != want.Sid || got.GetOwner() != want.Owner || got.GetPid() != want.Pid { + t.Fatalf("GET_LK with the holder's identity should report the holder, got %+v", got) + } + // A peer's cooling probe carries no principal, so it also sees the conflict. + probe, err := h.fs.PosixLock(context.Background(), &filer_pb.PosixLockRequest{ + Key: posixOwnershipKey, IsMoved: true, CoolingProbe: true, Op: filer_pb.PosixLockOp_GET_LK, + Lock: pbLock(0, 99, posixlock.Write, 1, 2, 7, false), + }) + if err != nil || !probe.GetHasConflict() { + t.Fatalf("a cooling probe must report the scoped lock: %+v, %v", probe, err) + } + h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_UNLOCK, pbLock(0, 99, posixlock.Unlock, 1, 2, 7, false)) + if got := h.held(posixOwnershipKey); len(got) != 0 { + t.Fatalf("queries must not transfer ownership away from the holder: %+v", got) + } +} + +func TestScopedPosixLockRefusedRequestsLeaveStateUnchanged(t *testing.T) { + h := newPosixOwnershipHarness(t, 0) + holder := h.client(scopedToken("holder", time.Hour, []string{"/locks"}, nil)) + h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)) + before := h.held(posixOwnershipKey) + + h.at(10 * time.Second) + valid := pbLock(0, 99, posixlock.Write, 1, 2, 7, false) + _, err := h.call(holder, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}, valid, pbLock(200, 299, posixlock.Unlock, 1, 2, 7, false)) + expectPosixCode(t, "reassertion with an unlock range", err, codes.InvalidArgument) + _, err = h.call(holder, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}, valid, pbLock(300, 200, posixlock.Write, 1, 2, 7, false)) + expectPosixCode(t, "reassertion with an inverted range", err, codes.InvalidArgument) + _, err = h.call(holder, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(200, 299, posixlock.Unlock, 1, 2, 7, false)) + expectPosixCode(t, "try lock with an unlock range", err, codes.InvalidArgument) + + expired := h.client(signedScopeClaims(t, scopeTestKey, security.SeaweedFilerClaims{ + AllowedPrefixes: []string{"/locks"}, + RegisteredClaims: jwt.RegisteredClaims{ID: "holder", ExpiresAt: jwt.NewNumericDate(time.Now().Add(-time.Minute))}, + })) + _, err = h.call(expired, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}, valid) + expectPosixCode(t, "keepalive with an expired token", err, codes.Unauthenticated) + readOnly := h.client(scopedToken("holder", time.Hour, nil, []string{"/locks"})) + _, err = h.call(readOnly, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}) + expectPosixCode(t, "keepalive with a read-only grant", err, codes.PermissionDenied) + + if got := h.held(posixOwnershipKey); !reflect.DeepEqual(got, before) { + t.Fatalf("a refused request changed the holder's locks: %+v", got) + } + h.at(15 * time.Second) + if !h.grantable(posixOwnershipKey, false) { + t.Fatal("a refused request must not renew the lease") + } +} + +func TestUnscopedPosixLocksKeepTheirBehaviour(t *testing.T) { + h := newPosixOwnershipHarness(t, 0) + tokenless := h.client("") + unscoped := h.client(unscopedToken()) + scoped := h.client(scopedToken("scoped", time.Hour, []string{"/locks"}, nil)) + h.must(tokenless, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)) + + // Unscoped callers share one namespace in which sid and owner identify the + // lock, as before. + if h.must(unscoped, posixOwnershipKey, filer_pb.PosixLockOp_GET_LK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)).GetHasConflict() { + t.Fatal("an unscoped caller naming the owner should not conflict with it") + } + h.must(unscoped, posixOwnershipKey, filer_pb.PosixLockOp_UNLOCK, pbLock(10, 20, posixlock.Unlock, 1, 2, 7, false)) + if got := h.held(posixOwnershipKey); len(got) != 2 { + t.Fatalf("an unscoped caller should still split an unscoped lock, got %+v", got) + } + before := h.held(posixOwnershipKey) + + // A scoped token's verified id never matches an unscoped lock. + h.must(scoped, posixOwnershipKey, filer_pb.PosixLockOp_RELEASE_POSIX_OWNER, pbLock(0, 0, posixlock.Unlock, 1, 2, 7, false)) + if h.must(scoped, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)).Granted { + t.Fatal("a scoped token must not take over an unscoped lock") + } + if got := h.held(posixOwnershipKey); !reflect.DeepEqual(got, before) { + t.Fatalf("a scoped token changed an unscoped lock: %+v", got) + } + + // Unscoped sessions are leased only once they renew, as a whole. + h.at(time.Hour) + if reaped := h.fs.posixLocks.ReapExpired(posixLockSessionTTL); len(reaped) != 0 { + t.Fatalf("a never-renewed unscoped session must not be reaped, got %v", reaped) + } + h.must(scoped, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}) + h.at(time.Hour + posixLockSessionTTL) + if reaped := h.fs.posixLocks.ReapExpired(posixLockSessionTTL); len(reaped) != 0 { + t.Fatalf("a scoped keepalive must not lease an unscoped session, got %v", reaped) + } + h.must(tokenless, scopePosixLockKeyPrefix+"/elsewhere", filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}) + h.at(2*time.Hour + posixLockSessionTTL) + if reaped := h.fs.posixLocks.ReapExpired(posixLockSessionTTL); len(reaped) != 1 || reaped[0] != 1 { + t.Fatalf("a renewed unscoped session should be reaped after the ttl, got %v", reaped) + } + if got := h.held(posixOwnershipKey); len(got) != 0 { + t.Fatalf("the reaped unscoped session's locks should be gone, got %+v", got) + } +} + +func TestScopedPosixLockOwnerSurvivesSigningKeyRotation(t *testing.T) { + h := newPosixOwnershipHarness(t, 0) + claims := func() security.SeaweedFilerClaims { + return security.SeaweedFilerClaims{ + AllowedPrefixes: []string{"/locks"}, + RegisteredClaims: jwt.RegisteredClaims{ID: "holder", ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour))}, + } + } + before := h.client(signedScopeClaims(t, scopeTestKey, claims())) + h.must(before, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)) + + const rotated = "rotated-scope-test-key" + h.keys.Store([2]string{rotated, scopeTestKey}) + h.must(before, posixOwnershipKey, filer_pb.PosixLockOp_UNLOCK, pbLock(10, 20, posixlock.Unlock, 1, 2, 7, false)) + after := h.client(signedScopeClaims(t, rotated, claims())) + h.must(after, posixOwnershipKey, filer_pb.PosixLockOp_RELEASE_POSIX_OWNER, pbLock(0, 0, posixlock.Unlock, 1, 2, 7, false)) + if got := h.held(posixOwnershipKey); len(got) != 0 { + t.Fatalf("the token id, not the signing key, owns the lock; got %+v", got) + } +} diff --git a/weed/server/filer_grpc_server_posix_lock.go b/weed/server/filer_grpc_server_posix_lock.go index 7f690ae382..73a31eb42e 100644 --- a/weed/server/filer_grpc_server_posix_lock.go +++ b/weed/server/filer_grpc_server_posix_lock.go @@ -2,7 +2,12 @@ package weed_server import ( "context" + "crypto/sha256" + "encoding/hex" "fmt" + "slices" + "strconv" + "strings" "time" "github.com/seaweedfs/seaweedfs/weed/filer/posixlock" @@ -96,15 +101,15 @@ func (fs *FilerServer) PosixLock(ctx context.Context, req *filer_pb.PosixLockReq } } - lk := posixlock.Range{ - Start: req.Lock.GetStart(), - End: req.Lock.GetEnd(), - Type: req.Lock.GetType(), - Sid: req.Lock.GetSid(), - Owner: req.Lock.GetOwner(), - Pid: req.Lock.GetPid(), - IsFlock: req.Lock.GetIsFlock(), + principal, lease := posixLockAuthority(ctx) + if principal != "" { + if err := checkScopedPosixLockRanges(req); err != nil { + return &filer_pb.PosixLockResponse{}, err + } } + lk := posixRangeFromPb(req.Lock) + lk.Principal = principal + session := lk.Session() resp := &filer_pb.PosixLockResponse{} switch req.Op { @@ -123,7 +128,10 @@ func (fs *FilerServer) PosixLock(ctx context.Context, req *filer_pb.PosixLockReq break } } - if c, granted := fs.posixLocks.TryLock(req.Key, lk); granted { + if c, granted, err := fs.posixLocks.TryLock(req.Key, lk, lease); err != nil { + // The token expired while the request waited: a grant would end at once. + return &filer_pb.PosixLockResponse{}, status.Error(codes.Unauthenticated, err.Error()) + } else if granted { resp.Granted = true } else { resp.HasConflict = true @@ -145,23 +153,26 @@ func (fs *FilerServer) PosixLock(ctx context.Context, req *filer_pb.PosixLockReq resp.Conflict = posixRangeToPb(c) } case filer_pb.PosixLockOp_RELEASE_POSIX_OWNER: - fs.posixLocks.ReleasePosixOwner(req.Key, lk.Sid, lk.Owner) + fs.posixLocks.ReleasePosixOwner(req.Key, session, lk.Owner) case filer_pb.PosixLockOp_RELEASE_FLOCK_OWNER: - fs.posixLocks.ReleaseFlockOwner(req.Key, lk.Sid, lk.Owner) + fs.posixLocks.ReleaseFlockOwner(req.Key, session, lk.Owner) case filer_pb.PosixLockOp_KEEP_ALIVE: // A re-assertion carries the mount's held locks on this key so the owner // can rebuild its in-memory state after an ownership change or restart; a - // bare keepalive just renews the lease. + // bare keepalive just renews the lease. A lock another session now holds + // is reported back as a conflict, so the mount learns it lost it. if len(req.Locks) > 0 { held := make([]posixlock.Range, 0, len(req.Locks)) for _, l := range req.Locks { held = append(held, posixRangeFromPb(l)) } - if conflicts := fs.posixLocks.Reassert(req.Key, lk.Sid, held); len(conflicts) > 0 { - glog.Warningf("posix reassert %s sid %d: %d lock(s) lost to another session: %+v", req.Key, lk.Sid, len(conflicts), conflicts) + if conflicts := fs.posixLocks.Reassert(req.Key, session, held, lease); len(conflicts) > 0 { + glog.Warningf("posix reassert %s sid %d: %d lock(s) lost to another session", req.Key, lk.Sid, len(conflicts)) + resp.HasConflict = true + resp.Conflict = posixRangeToPb(conflicts[0]) } } else { - fs.posixLocks.Renew(lk.Sid) + fs.posixLocks.Renew(req.Key, session, lease) } default: return &filer_pb.PosixLockResponse{}, fmt.Errorf("unknown posix lock op %v", req.Op) @@ -169,6 +180,59 @@ func (fs *FilerServer) PosixLock(ctx context.Context, req *filer_pb.PosixLockReq return resp, nil } +// posixLockAuthority derives who a PosixLock request acts for. A request the +// scope interceptor admitted for a scoped token acts for that token's verified +// id (jti): it controls only the locks it took, whatever sid or owner it names, +// and each of its leases ends no later than the token's expiry plus the +// verifier's clock leeway. Its leases are held under a fingerprint of its +// grants, so one keepalive renews every lock the session took under the same +// grants, but not those a token reusing the id took under other grants. Any other +// request, tokenless or carrying an unscoped token, acts in the unscoped +// namespace, which never matches a scoped lock. +func posixLockAuthority(ctx context.Context) (principal string, lease posixlock.Lease) { + authority, _ := ctx.Value(scopeWriteAuthorityKey{}).(*scopeWriteAuthority) + if authority == nil || authority.sc == nil { + return "", posixlock.Lease{} + } + sc := authority.sc + return sc.id, posixlock.Lease{TTL: posixLockSessionTTL, NotAfter: sc.exp.Add(sc.leeway), Grant: scopeGrantFingerprint(sc.grants)} +} + +// scopeGrantFingerprint digests a token's verified grants, independent of +// their order or repetition. Tokens with equal fingerprints may lock exactly +// the same keys, which is what lets a keepalive under one renew the locks +// taken under the other. +func scopeGrantFingerprint(grants []scopeGrant) string { + entries := make([]string, 0, len(grants)) + for _, g := range grants { + // Quoting keeps every entry on one line, so the joined list is unambiguous. + entries = append(entries, strconv.FormatBool(g.readWrite)+" "+strconv.Quote(g.path)) + } + slices.Sort(entries) + sum := sha256.Sum256([]byte(strings.Join(slices.Compact(entries), "\n"))) + return hex.EncodeToString(sum[:]) +} + +// checkScopedPosixLockRanges refuses a scoped request whose lock, or any +// re-asserted lock, is not a well-formed read or write range, before any state +// changes. +func checkScopedPosixLockRanges(req *filer_pb.PosixLockRequest) error { + valid := func(l *filer_pb.PosixLockRange) bool { + return (l.GetType() == posixlock.Read || l.GetType() == posixlock.Write) && l.GetStart() <= l.GetEnd() + } + if req.Op == filer_pb.PosixLockOp_TRY_LOCK && !valid(req.Lock) { + return status.Error(codes.InvalidArgument, "malformed lock range") + } + if req.Op == filer_pb.PosixLockOp_KEEP_ALIVE { + for _, l := range req.Locks { + if !valid(l) { + return status.Error(codes.InvalidArgument, "malformed re-asserted lock range") + } + } + } + return nil +} + // posixWarmingUp reports whether this filer is still within posixLockWarmup of // when it began serving POSIX locks. The zero readyAt (e.g. in tests) is never // warming up. diff --git a/weed/server/filer_grpc_server_posix_lock_test.go b/weed/server/filer_grpc_server_posix_lock_test.go index 2539994024..d2703ddb0c 100644 --- a/weed/server/filer_grpc_server_posix_lock_test.go +++ b/weed/server/filer_grpc_server_posix_lock_test.go @@ -98,7 +98,7 @@ func TestPosixLockKeepAlive(t *testing.T) { t.Fatalf("keep_alive should succeed: err=%v", err) } // A renewed session that goes stale is reaped; a never-renewed one is not. - fs.posixLocks.TryLock("s3.fuse.lock:/x", posixlock.Range{Start: 0, End: 9, Type: posixlock.Write, Sid: 7, Owner: 1}) + fs.posixLocks.TryLock("s3.fuse.lock:/x", posixlock.Range{Start: 0, End: 9, Type: posixlock.Write, Sid: 7, Owner: 1}, posixlock.Lease{}) if reaped := fs.posixLocks.ReapExpired(0); len(reaped) != 1 || reaped[0] != 7 { t.Fatalf("renewed session 7 should be reapable at ttl=0, got %v", reaped) } @@ -141,11 +141,11 @@ func TestPosixLockForwardsToOwner(t *testing.T) { } // The lock landed on the owner: a conflicting acquire there is rejected. - if _, granted := owner.posixLocks.TryLock(key, posixlock.Range{Start: 50, End: 149, Type: posixlock.Write, Sid: 2, Owner: 1}); granted { + if _, granted, _ := owner.posixLocks.TryLock(key, posixlock.Range{Start: 50, End: 149, Type: posixlock.Write, Sid: 2, Owner: 1}, posixlock.Lease{}); granted { t.Fatal("owner should hold the forwarded lock") } // The sender did not apply locally. - if _, granted := self.posixLocks.TryLock(key, posixlock.Range{Start: 0, End: 99, Type: posixlock.Write, Sid: 9, Owner: 9}); !granted { + if _, granted, _ := self.posixLocks.TryLock(key, posixlock.Range{Start: 0, End: 99, Type: posixlock.Write, Sid: 9, Owner: 9}, posixlock.Lease{}); !granted { t.Fatal("sender must forward, not apply locally") } } @@ -164,7 +164,7 @@ func TestPosixLockWarmupDefersGrants(t *testing.T) { } // A lock the owner already knows about is still reported as a conflict. - fs.posixLocks.TryLock("s3.fuse.lock:/x", posixlock.Range{Start: 0, End: 99, Type: posixlock.Write, Sid: 9, Owner: 1, Pid: 5}) + fs.posixLocks.TryLock("s3.fuse.lock:/x", posixlock.Range{Start: 0, End: 99, Type: posixlock.Write, Sid: 9, Owner: 1, Pid: 5}, posixlock.Lease{}) if r := posixOp(t, fs, filer_pb.PosixLockOp_TRY_LOCK, pbLock(50, 60, posixlock.Write, 1, 1, 7, false)); r.Granted || !r.HasConflict { t.Fatalf("known conflict should be reported during warm-up: %+v", r) }