seaweedfs/weed/cluster/lock_manager/distributed_lock_manager.go

67 lines
1.9 KiB
Go
Raw Normal View History

2023-06-26 05:14:40 +08:00
package lock_manager
import (
2023-06-26 05:30:58 +08:00
"fmt"
2023-06-26 05:14:40 +08:00
"github.com/seaweedfs/seaweedfs/weed/pb"
2023-06-26 05:30:58 +08:00
"time"
2023-06-26 05:14:40 +08:00
)
type DistributedLockManager struct {
lockManager *LockManager
2023-06-26 05:30:58 +08:00
LockRing *LockRing
2023-06-26 05:14:40 +08:00
}
func NewDistributedLockManager() *DistributedLockManager {
return &DistributedLockManager{
lockManager: NewLockManager(),
2023-06-26 05:30:58 +08:00
LockRing: NewLockRing(time.Second * 5),
2023-06-26 05:14:40 +08:00
}
}
2023-06-26 05:30:58 +08:00
func (dlm *DistributedLockManager) Lock(host pb.ServerAddress, key string, expiredAtNs int64, token string) (renewToken string, movedTo pb.ServerAddress, err error) {
servers := dlm.LockRing.GetSnapshot()
if servers == nil {
err = fmt.Errorf("no lock server found")
return
}
2023-06-26 05:17:58 +08:00
server := hashKeyToServer(key, servers)
2023-06-26 05:14:40 +08:00
if server != host {
movedTo = server
return
}
renewToken, err = dlm.lockManager.Lock(key, expiredAtNs, token)
return
}
2023-06-26 05:30:58 +08:00
func (dlm *DistributedLockManager) Unlock(host pb.ServerAddress, key string, token string) (movedTo pb.ServerAddress, err error) {
servers := dlm.LockRing.GetSnapshot()
if servers == nil {
err = fmt.Errorf("no lock server found")
return
}
2023-06-26 05:17:58 +08:00
server := hashKeyToServer(key, servers)
2023-06-26 05:14:40 +08:00
if server != host {
movedTo = server
return
}
_, err = dlm.lockManager.Unlock(key, token)
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
func (dlm *DistributedLockManager) InsertLock(key string, expiredAtNs int64, token string) {
dlm.lockManager.InsertLock(key, expiredAtNs, token)
}
func (dlm *DistributedLockManager) SelectNotOwnedLocks(host pb.ServerAddress, servers []pb.ServerAddress) (locks []*Lock) {
return dlm.lockManager.SelectLocks(func(key string) bool {
2023-06-26 05:17:58 +08:00
server := hashKeyToServer(key, servers)
2023-06-26 05:14:40 +08:00
return server != host
})
}
func (dlm *DistributedLockManager) CalculateTargetServer(key string, servers []pb.ServerAddress) pb.ServerAddress {
2023-06-26 05:17:58 +08:00
return hashKeyToServer(key, servers)
2023-06-26 05:14:40 +08:00
}