mutex.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package concurrency
  15. import (
  16. "context"
  17. "errors"
  18. "fmt"
  19. "sync"
  20. v3 "go.etcd.io/etcd/clientv3"
  21. pb "go.etcd.io/etcd/etcdserver/etcdserverpb"
  22. )
  23. // ErrLocked is returned by TryLock when Mutex is already locked by another session.
  24. var ErrLocked = errors.New("mutex: Locked by another session")
  25. // Mutex implements the sync Locker interface with etcd
  26. type Mutex struct {
  27. s *Session
  28. pfx string
  29. myKey string
  30. myRev int64
  31. hdr *pb.ResponseHeader
  32. }
  33. func NewMutex(s *Session, pfx string) *Mutex {
  34. return &Mutex{s, pfx + "/", "", -1, nil}
  35. }
  36. // TryLock locks the mutex if not already locked by another session.
  37. // If lock is held by another session, return immediately after attempting necessary cleanup
  38. // The ctx argument is used for the sending/receiving Txn RPC.
  39. func (m *Mutex) TryLock(ctx context.Context) error {
  40. resp, err := m.tryAcquire(ctx)
  41. if err != nil {
  42. return err
  43. }
  44. // if no key on prefix / the minimum rev is key, already hold the lock
  45. ownerKey := resp.Responses[1].GetResponseRange().Kvs
  46. if len(ownerKey) == 0 || ownerKey[0].CreateRevision == m.myRev {
  47. m.hdr = resp.Header
  48. return nil
  49. }
  50. client := m.s.Client()
  51. // Cannot lock, so delete the key
  52. if _, err := client.Delete(ctx, m.myKey); err != nil {
  53. return err
  54. }
  55. m.myKey = "\x00"
  56. m.myRev = -1
  57. return ErrLocked
  58. }
  59. // Lock locks the mutex with a cancelable context. If the context is canceled
  60. // while trying to acquire the lock, the mutex tries to clean its stale lock entry.
  61. func (m *Mutex) Lock(ctx context.Context) error {
  62. resp, err := m.tryAcquire(ctx)
  63. if err != nil {
  64. return err
  65. }
  66. // if no key on prefix / the minimum rev is key, already hold the lock
  67. ownerKey := resp.Responses[1].GetResponseRange().Kvs
  68. if len(ownerKey) == 0 || ownerKey[0].CreateRevision == m.myRev {
  69. m.hdr = resp.Header
  70. return nil
  71. }
  72. client := m.s.Client()
  73. // wait for deletion revisions prior to myKey
  74. hdr, werr := waitDeletes(ctx, client, m.pfx, m.myRev-1)
  75. // release lock key if wait failed
  76. if werr != nil {
  77. m.Unlock(client.Ctx())
  78. } else {
  79. m.hdr = hdr
  80. }
  81. return werr
  82. }
  83. func (m *Mutex) tryAcquire(ctx context.Context) (*v3.TxnResponse, error) {
  84. s := m.s
  85. client := m.s.Client()
  86. m.myKey = fmt.Sprintf("%s%x", m.pfx, s.Lease())
  87. cmp := v3.Compare(v3.CreateRevision(m.myKey), "=", 0)
  88. // put self in lock waiters via myKey; oldest waiter holds lock
  89. put := v3.OpPut(m.myKey, "", v3.WithLease(s.Lease()))
  90. // reuse key in case this session already holds the lock
  91. get := v3.OpGet(m.myKey)
  92. // fetch current holder to complete uncontended path with only one RPC
  93. getOwner := v3.OpGet(m.pfx, v3.WithFirstCreate()...)
  94. resp, err := client.Txn(ctx).If(cmp).Then(put, getOwner).Else(get, getOwner).Commit()
  95. if err != nil {
  96. return nil, err
  97. }
  98. m.myRev = resp.Header.Revision
  99. if !resp.Succeeded {
  100. m.myRev = resp.Responses[0].GetResponseRange().Kvs[0].CreateRevision
  101. }
  102. return resp, nil
  103. }
  104. func (m *Mutex) Unlock(ctx context.Context) error {
  105. client := m.s.Client()
  106. if _, err := client.Delete(ctx, m.myKey); err != nil {
  107. return err
  108. }
  109. m.myKey = "\x00"
  110. m.myRev = -1
  111. return nil
  112. }
  113. func (m *Mutex) IsOwner() v3.Cmp {
  114. return v3.Compare(v3.CreateRevision(m.myKey), "=", m.myRev)
  115. }
  116. func (m *Mutex) Key() string { return m.myKey }
  117. // Header is the response header received from etcd on acquiring the lock.
  118. func (m *Mutex) Header() *pb.ResponseHeader { return m.hdr }
  119. type lockerMutex struct{ *Mutex }
  120. func (lm *lockerMutex) Lock() {
  121. client := lm.s.Client()
  122. if err := lm.Mutex.Lock(client.Ctx()); err != nil {
  123. panic(err)
  124. }
  125. }
  126. func (lm *lockerMutex) Unlock() {
  127. client := lm.s.Client()
  128. if err := lm.Mutex.Unlock(client.Ctx()); err != nil {
  129. panic(err)
  130. }
  131. }
  132. // NewLocker creates a sync.Locker backed by an etcd mutex.
  133. func NewLocker(s *Session, pfx string) sync.Locker {
  134. return &lockerMutex{NewMutex(s, pfx)}
  135. }