Files
seaweedfs/weed/cluster/lock_manager/lock_manager.go
T
5b7e2d9e9e fix: retain released lock version watermarks (#13083)
* fix: retain released lock version watermarks

* fix(lock_manager): scope release records to lease identities

Keep a stable acquisition ID in opaque renewal tokens so release history cannot reject a valid lease from a different primary when generation counters overlap. Preserve earlier releases across new acquisitions and ownership eviction.

Carry the maximum lease expiry with releases, prevent renewals from shortening that bound, reject expired inserts, and reclaim release records after expiry. Track replication and handoff before sending copies so local-only leases need no release records.

Add regressions for fresh-primary failover, equal and lower generation counters, reordered releases and renewals, bounded retention, local-only workloads, ownership eviction, legacy release metadata, and gRPC release handling.

* lock_manager: name the release replay tests after the behavior they check

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

* fix(lock_manager): serialize lease handoff with local mutations

Hold per-key mutation admission through a fresh lease snapshot, the transfer RPC, and source demotion or removal. A release that wins first suppresses the transfer; a release arriving during handoff waits and is forwarded to the new primary afterward.

Keep incoming replication outside the gate to avoid callback cycles. Retain source authority on transfer errors and apply transfer completion only to the lease that was sent.

Add real gRPC regressions for releases during both handoff branches and replay after release, plus coverage for fresh snapshots, transfer errors, unrelated keys, and replacement leases.

* fix(lock_manager): retry handoffs without retaining renewal authority

Deliver a source-held lease to the current owner before forwarding renewal or unlock. Freeze local authority before sending a transfer, including when the receiver may have committed despite an RPC error. Retry without requiring a membership change, with backoff and shutdown cancellation.

Recheck ownership after a background handoff and preserve the copy until the latest owner receives it. Replicate the effective installed expiry instead of a shorter transfer input.

Replace timing assumptions with a same-key admission contention hook. Cover pre-handoff releases, lost acknowledgements, retry cleanup, owner changes, and effective expiry. Document why identityless legacy releases cannot safely delete slash-format leases with overlapping generation counters.

* test(filer): set up DLM handoff before the peer lock transfer check

Ring-change transfers now go through Dlm.TransferFn, which
SetupDlmReplication installs; without it the lock stays pending on the
old filer and the peer-auth transfer test cannot see it move.

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

* test(lock_manager): bound the handoff and unlock completion waits

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

* test(filer): give the handoff retry expiry subtest a one-second lease

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

* fix(lock_manager): serve lock and unlock here when a handoff ends with this node as primary

transferToOwnerLocked now returns the primary it observed after the
handoff. LockWithTimeout and Unlock redirected to the primary read before
the transfer, so a ring that moved back during the handoff sent the client
away from the node that holds the lease.

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

* test(lock_manager): bound the admission probes in the handoff tests

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

* fix(filer): keep the holder's renew token while its lock handoff is pending

A failed transfer RPC or a frozen lease answered the lock request with an
error and an empty RenewToken. The client treats that as a rejection and
drops its token, so it can no longer renew the lease once the handoff
completes. Report transfer failures as LockHandoffPending and echo the
caller's token for that error.

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

* refactor(lock_manager): return lease expiry from Lock, Unlock and InsertLock

The DLM was the only production caller of these methods and used private
twins (lockWithExpiry, unlock, insertLock) to get the effective expiry.
Return it from the public methods instead and drop the twins.

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

* refactor(lock_manager): share the copy acceptance checks between InsertLock and InsertBackupLock

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

* refactor(lock_manager): drive handoff tests through TransferLockToOwner

TransferLock and its helpers were only reachable from tests. Remove them
so the tests exercise the production handoff path.

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

* refactor(lock_manager): share the routing and handoff prologue of LockWithTimeout and Unlock

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

---------

Co-authored-by: Master <Master@node0.8m510.lpad-pg0.utah.cloudlab.us>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 15:31:06 -08:00

481 lines
15 KiB
Go

package lock_manager
import (
"fmt"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/google/uuid"
"github.com/seaweedfs/seaweedfs/weed/glog"
)
var LockErrorNonEmptyTokenOnNewLock = fmt.Errorf("lock: non-empty token on a new lock")
var LockErrorNonEmptyTokenOnExpiredLock = fmt.Errorf("lock: non-empty token on an expired lock")
var LockErrorTokenMismatch = fmt.Errorf("lock: token mismatch")
var UnlockErrorTokenMismatch = fmt.Errorf("unlock: token mismatch")
var LockNotFound = fmt.Errorf("lock not found")
var LockHandoffPending = fmt.Errorf("lock handoff pending")
// LockManager local lock manager, used by distributed lock manager
type LockManager struct {
locks map[string]*Lock
// Released lease identities are retained only until their maximum expiry.
removed map[releasedLease]int64
accessLock sync.RWMutex
nextGeneration atomic.Int64
}
type releasedLease struct{ path, id string }
// Tokens are opaque to clients. Keep a stable acquisition ID while rotating the
// secret on renewal; local generation counters can overlap across primaries.
func leaseID(token string) string {
id, _, _ := strings.Cut(token, "/")
return id
}
func newLockToken(previous string) string {
id := leaseID(previous)
if id == "" {
id = uuid.New().String()
}
return id + "/" + uuid.New().String()
}
type Lock struct {
Token string
PrevToken string // token superseded by the latest renewal; a holder whose renewal response was lost still presents it
ExpiredAtNs int64
Key string // only used for moving locks
Owner string
IsBackup bool // true if this node holds the lock as a backup
Generation int64 // monotonic fencing token, increments on fresh acquisition
Seq int64 // per-lock sequence number, increments on every mutation (acquire/renew/unlock)
replicated bool // a copy may exist elsewhere, requiring a release record
handoff bool // renewal authority has moved, but delivery may need retry
}
func NewLockManager() *LockManager {
t := &LockManager{
locks: make(map[string]*Lock),
}
go t.CleanUp()
return t
}
func (lm *LockManager) NextGeneration() int64 {
return lm.nextGeneration.Add(1)
}
func compareMutationVersion(generation, seq int64, existingGeneration, existingSeq int64) int {
switch {
case generation < existingGeneration:
return -1
case generation > existingGeneration:
return 1
case seq < existingSeq:
return -1
case seq > existingSeq:
return 1
default:
return 0
}
}
func (lm *LockManager) advanceGenerationFloor(generation int64) {
for {
current := lm.nextGeneration.Load()
if generation < current {
return
}
if lm.nextGeneration.CompareAndSwap(current, generation) {
return
}
}
}
// rememberRemoval runs under accessLock. Delayed messages for this lease are
// rejected until its maximum expiry, after which inserts reject them as expired.
func (lm *LockManager) rememberRemoval(path, token string, expiredAtNs int64) {
if token == "" || expiredAtNs <= time.Now().UnixNano() {
return
}
if lm.removed == nil {
lm.removed = make(map[releasedLease]int64)
}
key := releasedLease{path, leaseID(token)}
lm.removed[key] = max(lm.removed[key], expiredAtNs)
}
func (lm *LockManager) wasRemoved(path, token string) bool {
return lm.removed[releasedLease{path, leaseID(token)}] > time.Now().UnixNano()
}
// Lock also returns the effective expiry for replication. Renewals cannot
// shorten it, so a release carries a validity bound for every older RPC.
func (lm *LockManager) Lock(path string, expiredAtNs int64, token string, owner string) (lockOwner, renewToken string, generation int64, seq int64, leaseExpires int64, err error) {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
leaseExpires = expiredAtNs
glog.V(4).Infof("lock %s %v %v %v", path, time.Unix(0, expiredAtNs), token, owner)
if oldValue, found := lm.locks[path]; found {
if oldValue.handoff && oldValue.ExpiredAtNs > time.Now().UnixNano() {
err = LockHandoffPending
return
}
if oldValue.ExpiredAtNs > 0 && oldValue.ExpiredAtNs < time.Now().UnixNano() {
// lock is expired, set to a new lock
if token != "" {
glog.V(4).Infof("lock expired key %s non-empty token %v owner %v ts %s", path, token, owner, time.Unix(0, oldValue.ExpiredAtNs))
err = LockErrorNonEmptyTokenOnExpiredLock
return
} else {
// new lock
renewToken = newLockToken("")
generation = lm.NextGeneration()
seq = 1
glog.V(4).Infof("key %s new token %v owner %v generation %d", path, renewToken, owner, generation)
lm.locks[path] = &Lock{Token: renewToken, ExpiredAtNs: expiredAtNs, Owner: owner, Generation: generation, Seq: seq}
return
}
}
// not expired
leaseExpires = max(expiredAtNs, oldValue.ExpiredAtNs)
lockOwner = oldValue.Owner
if oldValue.Token == token {
// token matches, renew the lock
renewToken = newLockToken(oldValue.Token)
generation = oldValue.Generation // keep same generation on renewal
seq = oldValue.Seq + 1
glog.V(4).Infof("key %s old token %v owner %v => %v owner %v", path, oldValue.Token, oldValue.Owner, renewToken, owner)
lm.locks[path] = &Lock{Token: renewToken, PrevToken: oldValue.Token, ExpiredAtNs: leaseExpires, Owner: owner, Generation: generation, Seq: seq, replicated: oldValue.replicated}
return
}
if token != "" && token == oldValue.PrevToken && owner == oldValue.Owner {
// The latest renewal already rotated the token but its response
// was lost: replay the current token so the holder recovers it
// instead of conflicting with its own lease until it expires.
renewToken = oldValue.Token
generation = oldValue.Generation
seq = oldValue.Seq + 1
oldValue.ExpiredAtNs = leaseExpires
oldValue.Seq = seq
return
}
if token == "" {
// new lock
glog.V(4).Infof("key %s locked by %v", path, oldValue.Owner)
err = fmt.Errorf("lock already owned by %v", oldValue.Owner)
return
}
glog.V(4).Infof("key %s expected token %v owner %v received %v from %v", path, oldValue.Token, oldValue.Owner, token, owner)
err = fmt.Errorf("lock: token mismatch")
return
} else {
glog.V(4).Infof("key %s no lock owner %v", path, owner)
if token == "" {
// new lock
renewToken = newLockToken("")
generation = lm.NextGeneration()
seq = 1
glog.V(4).Infof("key %s new token %v owner %v generation %d", path, renewToken, owner, generation)
lm.locks[path] = &Lock{Token: renewToken, ExpiredAtNs: expiredAtNs, Owner: owner, Generation: generation, Seq: seq}
return
} else {
glog.V(4).Infof("key %s non-empty token %v owner %v", path, token, owner)
err = LockErrorNonEmptyTokenOnNewLock
return
}
}
}
// Unlock returns the released lease and its maximum expiry atomically, including
// when the caller uses a superseded token after losing a renewal response.
func (lm *LockManager) Unlock(path, token string) (*Lock, error) {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
old, found := lm.locks[path]
if !found {
return nil, LockNotFound
}
if old.handoff {
return nil, LockHandoffPending
}
expired := old.ExpiredAtNs > 0 && old.ExpiredAtNs < time.Now().UnixNano()
if !expired && old.Token != token && (token == "" || token != old.PrevToken) {
return nil, UnlockErrorTokenMismatch
}
if expired {
glog.V(4).Infof("key %s expired at %v", path, time.Unix(0, old.ExpiredAtNs))
} else {
glog.V(4).Infof("key %s unlocked with %v", path, token)
}
released := *old
released.Seq++
if released.replicated {
lm.rememberRemoval(path, released.Token, released.ExpiredAtNs)
}
delete(lm.locks, path)
return &released, nil
}
func (lm *LockManager) CleanUp() {
for {
time.Sleep(time.Minute)
lm.cleanUp(time.Now().UnixNano())
}
}
func (lm *LockManager) cleanUp(now int64) {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
for key, lock := range lm.locks {
if lock != nil && now >= lock.ExpiredAtNs {
glog.V(4).Infof("key %s expired at %v", key, time.Unix(0, lock.ExpiredAtNs))
delete(lm.locks, key)
}
}
for key, expires := range lm.removed {
if now >= expires {
delete(lm.removed, key)
}
}
if len(lm.removed) == 0 {
lm.removed = nil
}
}
// SelectLocks takes out locks by key
// if selectFn returns true, the lock will be removed and returned
func (lm *LockManager) SelectLocks(selectFn func(key string) bool) (locks []*Lock) {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
now := time.Now().UnixNano()
for key, lock := range lm.locks {
if now > lock.ExpiredAtNs {
glog.V(4).Infof("key %s expired at %v", key, time.Unix(0, lock.ExpiredAtNs))
delete(lm.locks, key)
continue
}
if selectFn(key) {
glog.V(4).Infof("key %s selected and deleted", key)
delete(lm.locks, key)
lock.Key = key
locks = append(locks, lock)
}
}
return
}
// InsertLock inserts a lock from a transfer if it is newer than the current
// state, returning the effective expiry atomically with installation.
func (lm *LockManager) InsertLock(path string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64) (leaseExpires int64, accepted bool) {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
if lock := lm.insertCopyLocked(path, expiredAtNs, token, prevToken, owner, generation, seq, false); lock != nil {
return lock.ExpiredAtNs, true
}
return 0, false
}
// InsertBackupLock inserts or updates a lock as a backup copy.
// It rejects stale mutations by comparing (generation, seq). If a current primary
// already exists on this node, newer replicated state refreshes that primary copy
// without demoting it back to a backup.
func (lm *LockManager) InsertBackupLock(path string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64) {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
lm.insertCopyLocked(path, expiredAtNs, token, prevToken, owner, generation, seq, true)
}
// insertCopyLocked runs under accessLock. It rejects a copy that is expired,
// released, or not newer than the live lock, and never shortens the same lease.
func (lm *LockManager) insertCopyLocked(path string, expiredAtNs int64, token, prevToken, owner string, generation, seq int64, asBackup bool) *Lock {
now := time.Now().UnixNano()
if expiredAtNs <= now || lm.wasRemoved(path, token) {
return nil
}
lock := &Lock{Token: token, PrevToken: prevToken, ExpiredAtNs: expiredAtNs, Owner: owner, IsBackup: asBackup, Generation: generation, Seq: seq, replicated: true}
if existing, found := lm.locks[path]; found && existing.ExpiredAtNs > now {
if compareMutationVersion(generation, seq, existing.Generation, existing.Seq) <= 0 {
glog.V(4).Infof("lock %s: rejecting stale copy gen=%d seq=%d (current gen=%d seq=%d)", path, generation, seq, existing.Generation, existing.Seq)
return nil
}
sameLease := leaseID(existing.Token) == leaseID(token)
if sameLease {
lock.ExpiredAtNs = max(expiredAtNs, existing.ExpiredAtNs)
}
if asBackup {
lock.IsBackup = existing.IsBackup
lock.handoff = existing.handoff && sameLease
}
}
lm.locks[path] = lock
lm.advanceGenerationFloor(generation)
return lock
}
// markReplicated must precede sending a copy. If release won the race, skip
// the send; otherwise unlock will retain this lease's identity until expiry.
func (lm *LockManager) markReplicated(path, token string) bool {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
lock, found := lm.locks[path]
if !found || leaseID(lock.Token) != leaseID(token) {
return false
}
lock.replicated = true
return true
}
// beginTransfer freezes local renewal authority before sending an RPC. Even a
// failed RPC may have installed the lease on its receiver.
func (lm *LockManager) beginTransfer(path string) (*Lock, bool) {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
lock, found := lm.locks[path]
if !found || lock.ExpiredAtNs <= time.Now().UnixNano() {
return nil, false
}
lock.replicated, lock.handoff, lock.IsBackup = true, true, true
cp := *lock
cp.Key = path
return &cp, true
}
// finishTransfer changes only the lease that was handed off. A different lease
// installed by incoming replication while the RPC was in flight must survive.
func (lm *LockManager) finishTransfer(path, token string, keepBackup bool) {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
if lock, found := lm.locks[path]; found && leaseID(lock.Token) == leaseID(token) {
if keepBackup {
lock.IsBackup = true
lock.handoff = false
} else {
delete(lm.locks, path)
}
}
}
// RemoveLock removes a lock by key
func (lm *LockManager) RemoveLock(path string) {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
// Ownership eviction is not a release: the same live mutation may return
// in a later transfer. Only completed releases create tombstones.
delete(lm.locks, path)
}
// RemoveBackupLockIfSeq records a release even if its acquire has not arrived.
// A release can only delete its own lease, never a different primary's lease
// whose local generation may be smaller or equal.
func (lm *LockManager) RemoveBackupLockIfSeq(path string, generation, seq int64, token string, expiredAtNs int64) bool {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
lm.advanceGenerationFloor(generation)
if existing, found := lm.locks[path]; found {
// Older primaries omitted release metadata. Preserve ordered releases
// for their legacy tokens without letting them delete a new lease.
// For slash-format tokens, equal generations can belong to different
// primaries. Without a lease ID it is safer to retain the lease until
// expiry than to delete an unrelated acquisition during an upgrade.
if token == "" && !strings.Contains(existing.Token, "/") {
token = existing.Token
}
if existing.Generation != generation || leaseID(existing.Token) != leaseID(token) {
lm.rememberRemoval(path, token, expiredAtNs)
return false
}
if seq < existing.Seq {
return false
}
expiredAtNs = max(expiredAtNs, existing.ExpiredAtNs)
delete(lm.locks, path)
}
lm.rememberRemoval(path, token, expiredAtNs)
return true
}
// GetLock returns a copy of the lock for a key, if it exists and is not expired
func (lm *LockManager) GetLock(key string) (*Lock, bool) {
lm.accessLock.RLock()
defer lm.accessLock.RUnlock()
lock, found := lm.locks[key]
if !found {
return nil, false
}
if time.Now().UnixNano() > lock.ExpiredAtNs {
return nil, false
}
// Return a copy
cp := *lock
return &cp, true
}
func (lm *LockManager) GetLockOwner(key string) (owner string, err error) {
lm.accessLock.RLock()
defer lm.accessLock.RUnlock()
if lock, found := lm.locks[key]; found {
if time.Now().UnixNano() > lock.ExpiredAtNs {
err = LockNotFound
return
}
return lock.Owner, nil
}
err = LockNotFound
return
}
// AllLocks returns a copy of all non-expired locks
func (lm *LockManager) AllLocks() []*Lock {
lm.accessLock.RLock()
defer lm.accessLock.RUnlock()
now := time.Now().UnixNano()
var result []*Lock
for key, lock := range lm.locks {
if now > lock.ExpiredAtNs {
continue
}
cp := *lock
cp.Key = key
result = append(result, &cp)
}
return result
}
// PromoteLock changes a backup lock to a primary lock
func (lm *LockManager) PromoteLock(key string) bool {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
if lock, found := lm.locks[key]; found && lock.IsBackup {
lock.IsBackup = false
lock.handoff = false
return true
}
return false
}
// DemoteLock changes a primary lock to a backup lock
func (lm *LockManager) DemoteLock(key string) bool {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
if lock, found := lm.locks[key]; found && !lock.IsBackup {
lock.IsBackup = true
lock.replicated = true
return true
}
return false
}