Skip to content

Commit

Permalink
Define a DLocker interface for distributed locker
Browse files Browse the repository at this point in the history
Also updated the contrib/lock example to demo how to use the DLocker

Signed-off-by: Benjamin Wang <benjamin.ahrtr@gmail.com>
  • Loading branch information
ahrtr committed Oct 24, 2024
1 parent 7b82523 commit c5eed51
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 4 deletions.
13 changes: 12 additions & 1 deletion client/v3/concurrency/mutex.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ func (m *Mutex) IsOwner() v3.Cmp {
}

func (m *Mutex) Key() string { return m.myKey }
func (m *Mutex) Rev() int64 { return m.myRev }

// Header is the response header received from etcd on acquiring the lock.
func (m *Mutex) Header() *pb.ResponseHeader { return m.hdr }
Expand All @@ -172,6 +173,16 @@ func (lm *lockerMutex) Unlock() {
}

// NewLocker creates a sync.Locker backed by an etcd mutex.
func NewLocker(s *Session, pfx string) sync.Locker {
func NewLocker(s *Session, pfx string) DLocker {
return &lockerMutex{NewMutex(s, pfx)}
}

// A DLocker represents an object that can be locked and unlocked
// in distributed environment.
type DLocker interface {
sync.Locker
// Rev returns a revision which is monotonically incremental. It can
// be used as a fencing token to prevent expired locker from operating
// the shared resource.
Rev() int64
}
2 changes: 1 addition & 1 deletion contrib/lock/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ If things go well the second client process invoked as `./client 2` finishes soo
After checking this, please hit any key for `./client 1` and resume the process. It will show an output like below:
```
resuming client 1
expected fail to write to storage with old lease version: error: given version (694d82254d5fa305) is different from the existing version (694d82254e18770a)
expected fail to write to storage with old lease version: error: given version (4) is smaller than the existing version (6)
```

[fencing]: https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html
Expand Down
4 changes: 2 additions & 2 deletions contrib/lock/storage/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ func handler(w http.ResponseWriter, r *http.Request) {
}
} else if strings.Compare(req.Op, "write") == 0 {
if val, ok := data[req.Key]; ok {
if req.Version != val.version {
writeResponse(response{"", -1, fmt.Sprintf("given version (%x) is different from the existing version (%x)", req.Version, val.version)}, w)
if req.Version < val.version {
writeResponse(response{"", -1, fmt.Sprintf("given version (%d) is smaller than the existing version (%d)", req.Version, val.version)}, w)
} else {
data[req.Key].val = req.Val
data[req.Key].version = req.Version
Expand Down

0 comments on commit c5eed51

Please sign in to comment.