Files
seaweedfs/weed/cluster/lock_manager/distributed_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

263 lines
9.7 KiB
Go

package lock_manager
import (
"fmt"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
const RenewInterval = time.Second * 3
const LiveLockTTL = time.Second * 7
var NoLockServerError = fmt.Errorf("no lock server found")
// ReplicateFunc is called to replicate a lock operation to a backup server.
// The caller (filer server) provides this to avoid a circular dependency.
// seq is a per-lock monotonic sequence number for causal ordering — the backup
// rejects mutations with seq <= its current seq for that key.
type ReplicateFunc func(server pb.ServerAddress, key string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64, isUnlock bool)
type DistributedLockManager struct {
lockManager *LockManager
mutations *util.LockTable[string]
LockRing *LockRing
Host pb.ServerAddress
ReplicateFn ReplicateFunc // set by filer server after creation
// TransferFn waits for the receiver; an error may still mean it committed.
TransferFn func(pb.ServerAddress, *Lock) error
// RetryTransferFn enqueues work without waiting for this key gate.
RetryTransferFn func(string)
// Tests set this before concurrent use, to observe admission contention.
onMutationWait func(string)
}
func NewDistributedLockManager(host pb.ServerAddress) *DistributedLockManager {
return &DistributedLockManager{
lockManager: NewLockManager(),
mutations: util.NewLockTable[string](),
LockRing: NewLockRing(time.Second * 5),
Host: host,
}
}
func (dlm *DistributedLockManager) acquireMutation(key string) *util.ActiveLock {
if mutation, ok := dlm.mutations.TryAcquireLock("lock mutation", key, util.ExclusiveLock); ok {
return mutation
}
if dlm.onMutationWait != nil {
dlm.onMutationWait(key)
}
return dlm.mutations.AcquireLock("lock mutation", key, util.ExclusiveLock)
}
func (dlm *DistributedLockManager) LockWithTimeout(key string, expiredAtNs int64, token string, owner string) (lockOwner string, renewToken string, generation int64, movedTo pb.ServerAddress, err error) {
mutation := dlm.acquireMutation(key)
defer dlm.mutations.ReleaseLock(key, mutation)
if movedTo, err = dlm.serverLocked(key); err != nil || movedTo != "" {
return
}
var seq, leaseExpires int64
lockOwner, renewToken, generation, seq, leaseExpires, err = dlm.lockManager.Lock(key, expiredAtNs, token, owner)
if err == nil && renewToken != "" {
dlm.replicateToBackup(key, leaseExpires, renewToken, token, owner, generation, seq, false)
}
return
}
// serverLocked runs under key's mutation gate. It returns the primary to
// forward to, or "" when this node serves key. The new owner must receive any
// local lease first, since only it can rotate the renewal token; this holds
// even when a request wins admission before the topology callback.
func (dlm *DistributedLockManager) serverLocked(key string) (movedTo pb.ServerAddress, err error) {
primary, _ := dlm.LockRing.GetPrimaryAndBackup(key)
if primary != "" && primary != dlm.Host {
if primary, err = dlm.transferToOwnerLocked(key); err != nil {
return "", err
}
}
if primary == "" {
return "", NoLockServerError
}
if primary == dlm.Host {
return "", nil
}
return primary, nil
}
func (dlm *DistributedLockManager) FindLockOwner(key string) (owner string, movedTo pb.ServerAddress, err error) {
primary, _ := dlm.LockRing.GetPrimaryAndBackup(key)
if primary == "" {
err = NoLockServerError
return
}
if primary != dlm.Host {
// If we still hold this lock locally, serve it here
if lock, found := dlm.lockManager.GetLock(key); found && !lock.IsBackup {
owner = lock.Owner
return
}
movedTo = primary
servers := dlm.LockRing.GetSnapshot()
glog.V(0).Infof("lock %s not on current %s but on %s from %v", key, dlm.Host, movedTo, servers)
return
}
owner, err = dlm.lockManager.GetLockOwner(key)
return
}
func (dlm *DistributedLockManager) Unlock(key string, token string) (movedTo pb.ServerAddress, err error) {
mutation := dlm.acquireMutation(key)
defer dlm.mutations.ReleaseLock(key, mutation)
if movedTo, err = dlm.serverLocked(key); err != nil || movedTo != "" {
return
}
released, err := dlm.lockManager.Unlock(key, token)
if released != nil {
dlm.replicateToBackup(key, released.ExpiredAtNs, released.Token, "", released.Owner, released.Generation, released.Seq, true)
}
return
}
// InsertLock is used to insert a lock to a server unconditionally.
// It is used when a server is down and the lock is moved to another server.
// After inserting, it replicates to the backup for this key.
func (dlm *DistributedLockManager) InsertLock(key string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64) {
if effectiveExpiry, accepted := dlm.lockManager.InsertLock(key, expiredAtNs, token, prevToken, owner, generation, seq); accepted {
dlm.replicateToBackup(key, effectiveExpiry, token, prevToken, owner, generation, seq, false)
}
}
// InsertBackupLock inserts a lock as a backup copy, rejecting stale seq
func (dlm *DistributedLockManager) InsertBackupLock(key string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64) {
dlm.lockManager.InsertBackupLock(key, expiredAtNs, token, prevToken, owner, generation, seq)
}
// RemoveBackupLock removes a backup lock unconditionally
func (dlm *DistributedLockManager) RemoveBackupLock(key string) {
dlm.lockManager.RemoveLock(key)
}
// RemoveBackupLockIfSeq records a release and removes only the matching lease.
func (dlm *DistributedLockManager) RemoveBackupLockIfSeq(key string, generation int64, seq int64, token string, expiredAtNs int64) {
dlm.lockManager.RemoveBackupLockIfSeq(key, generation, seq, token, expiredAtNs)
}
func (dlm *DistributedLockManager) SelectNotOwnedLocks(servers []pb.ServerAddress) (locks []*Lock) {
return dlm.lockManager.SelectLocks(func(key string) bool {
server := hashKeyToServer(key, servers)
return server != dlm.Host
})
}
func (dlm *DistributedLockManager) CalculateTargetServer(key string, servers []pb.ServerAddress) pb.ServerAddress {
return hashKeyToServer(key, servers)
}
func (dlm *DistributedLockManager) IsLocal(key string) bool {
primary := dlm.LockRing.GetPrimary(key)
if primary == "" {
return true
}
return primary == dlm.Host
}
// AllLocks returns all non-expired locks on this node
func (dlm *DistributedLockManager) AllLocks() []*Lock {
return dlm.lockManager.AllLocks()
}
// PromoteLock promotes a backup lock to primary
func (dlm *DistributedLockManager) PromoteLock(key string) bool {
return dlm.lockManager.PromoteLock(key)
}
// DemoteLock demotes a primary lock to backup
func (dlm *DistributedLockManager) DemoteLock(key string) bool {
return dlm.lockManager.DemoteLock(key)
}
// GetLock returns a copy of a lock if it exists
func (dlm *DistributedLockManager) GetLock(key string) (*Lock, bool) {
return dlm.lockManager.GetLock(key)
}
// TransferLockToOwner serializes a fresh snapshot and handoff with local
// mutations. Incoming replication bypasses admission so the receiver can
// replicate back. The retry worker also calls it without a ring change.
func (dlm *DistributedLockManager) TransferLockToOwner(key string) error {
mutation := dlm.acquireMutation(key)
defer dlm.mutations.ReleaseLock(key, mutation)
_, err := dlm.transferToOwnerLocked(key)
return err
}
// transferToOwnerLocked returns the primary that owns the lease afterwards.
func (dlm *DistributedLockManager) transferToOwnerLocked(key string) (owner pb.ServerAddress, err error) {
defer func() {
if err != nil && dlm.RetryTransferFn != nil {
dlm.RetryTransferFn(key)
}
}()
primary, backup := dlm.LockRing.GetPrimaryAndBackup(key)
current, found := dlm.lockManager.GetLock(key)
if !found {
return primary, nil
}
if primary == "" {
return "", NoLockServerError
}
if primary == dlm.Host {
if current.handoff {
dlm.lockManager.PromoteLock(key)
}
return primary, nil
}
if current.IsBackup && !current.handoff && backup == dlm.Host {
return primary, nil
}
if dlm.TransferFn == nil {
return "", LockHandoffPending
}
transferred, found := dlm.lockManager.beginTransfer(key)
if !found {
return primary, nil
}
// On error keep the frozen copy: the receiver may have committed.
if err = dlm.TransferFn(primary, transferred); err != nil {
return primary, fmt.Errorf("%w: %w", LockHandoffPending, err)
}
// Background retries can overlap a newer topology callback. Never evict
// a lease now owned here or discard it before its newest owner receives it.
currentPrimary, currentBackup := dlm.LockRing.GetPrimaryAndBackup(key)
if currentPrimary == dlm.Host {
dlm.lockManager.PromoteLock(key)
} else if currentPrimary == primary {
dlm.lockManager.finishTransfer(key, transferred.Token, currentBackup == dlm.Host)
} else {
return "", LockHandoffPending
}
return currentPrimary, nil
}
// ReplicateLock sends an existing lease to its current backup after a topology
// change, recording that the local lease may now have a remote copy.
func (dlm *DistributedLockManager) ReplicateLock(lock *Lock) {
dlm.replicateToBackup(lock.Key, lock.ExpiredAtNs, lock.Token, lock.PrevToken, lock.Owner, lock.Generation, lock.Seq, false)
}
// replicateToBackup asynchronously replicates a lock operation to the backup server
func (dlm *DistributedLockManager) replicateToBackup(key string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64, isUnlock bool) {
_, backup := dlm.LockRing.GetPrimaryAndBackup(key)
if backup == "" {
return // single-server deployment, no backup
}
if dlm.ReplicateFn != nil {
if !isUnlock && !dlm.lockManager.markReplicated(key, token) {
return
}
go dlm.ReplicateFn(backup, key, expiredAtNs, token, prevToken, owner, generation, seq, isUnlock)
}
}