mutex.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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. "fmt"
  18. "sync"
  19. v3 "go.etcd.io/etcd/clientv3"
  20. pb "go.etcd.io/etcd/etcdserver/etcdserverpb"
  21. )
  22. // Mutex implements the sync Locker interface with etcd
  23. type Mutex struct {
  24. s *Session
  25. pfx string
  26. myKey string
  27. myRev int64
  28. hdr *pb.ResponseHeader
  29. }
  30. func NewMutex(s *Session, pfx string) *Mutex {
  31. return &Mutex{s, pfx + "/", "", -1, nil}
  32. }
  33. // Lock locks the mutex with a cancelable context. If the context is canceled
  34. // while trying to acquire the lock, the mutex tries to clean its stale lock entry.
  35. func (m *Mutex) Lock(ctx context.Context) error {
  36. s := m.s
  37. client := m.s.Client()
  38. m.myKey = fmt.Sprintf("%s%x", m.pfx, s.Lease())
  39. cmp := v3.Compare(v3.CreateRevision(m.myKey), "=", 0)
  40. // put self in lock waiters via myKey; oldest waiter holds lock
  41. put := v3.OpPut(m.myKey, "", v3.WithLease(s.Lease()))
  42. // reuse key in case this session already holds the lock
  43. get := v3.OpGet(m.myKey)
  44. // fetch current holder to complete uncontended path with only one RPC
  45. getOwner := v3.OpGet(m.pfx, v3.WithFirstCreate()...)
  46. resp, err := client.Txn(ctx).If(cmp).Then(put, getOwner).Else(get, getOwner).Commit()
  47. if err != nil {
  48. return err
  49. }
  50. m.myRev = resp.Header.Revision
  51. if !resp.Succeeded {
  52. m.myRev = resp.Responses[0].GetResponseRange().Kvs[0].CreateRevision
  53. }
  54. // if no key on prefix / the minimum rev is key, already hold the lock
  55. ownerKey := resp.Responses[1].GetResponseRange().Kvs
  56. if len(ownerKey) == 0 || ownerKey[0].CreateRevision == m.myRev {
  57. m.hdr = resp.Header
  58. return nil
  59. }
  60. // wait for deletion revisions prior to myKey
  61. hdr, werr := waitDeletes(ctx, client, m.pfx, m.myRev-1)
  62. // release lock key if cancelled
  63. select {
  64. case <-ctx.Done():
  65. m.Unlock(client.Ctx())
  66. default:
  67. m.hdr = hdr
  68. }
  69. return werr
  70. }
  71. func (m *Mutex) Unlock(ctx context.Context) error {
  72. client := m.s.Client()
  73. if _, err := client.Delete(ctx, m.myKey); err != nil {
  74. return err
  75. }
  76. m.myKey = "\x00"
  77. m.myRev = -1
  78. return nil
  79. }
  80. func (m *Mutex) IsOwner() v3.Cmp {
  81. return v3.Compare(v3.CreateRevision(m.myKey), "=", m.myRev)
  82. }
  83. func (m *Mutex) Key() string { return m.myKey }
  84. // Header is the response header received from etcd on acquiring the lock.
  85. func (m *Mutex) Header() *pb.ResponseHeader { return m.hdr }
  86. type lockerMutex struct{ *Mutex }
  87. func (lm *lockerMutex) Lock() {
  88. client := lm.s.Client()
  89. if err := lm.Mutex.Lock(client.Ctx()); err != nil {
  90. panic(err)
  91. }
  92. }
  93. func (lm *lockerMutex) Unlock() {
  94. client := lm.s.Client()
  95. if err := lm.Mutex.Unlock(client.Ctx()); err != nil {
  96. panic(err)
  97. }
  98. }
  99. // NewLocker creates a sync.Locker backed by an etcd mutex.
  100. func NewLocker(s *Session, pfx string) sync.Locker {
  101. return &lockerMutex{NewMutex(s, pfx)}
  102. }