mutex.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. // Copyright 2016 CoreOS, Inc.
  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. "sync"
  17. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  18. v3 "github.com/coreos/etcd/clientv3"
  19. )
  20. // Mutex implements the sync Locker interface with etcd
  21. type Mutex struct {
  22. client *v3.Client
  23. kv v3.KV
  24. ctx context.Context
  25. pfx string
  26. myKey string
  27. myRev int64
  28. }
  29. func NewMutex(ctx context.Context, client *v3.Client, pfx string) *Mutex {
  30. return &Mutex{client, v3.NewKV(client), ctx, pfx, "", -1}
  31. }
  32. // Lock locks the mutex with a cancellable context. If the context is cancelled
  33. // while trying to acquire the lock, the mutex tries to clean its stale lock entry.
  34. func (m *Mutex) Lock(ctx context.Context) error {
  35. s, err := NewSession(m.client)
  36. if err != nil {
  37. return err
  38. }
  39. // put self in lock waiters via myKey; oldest waiter holds lock
  40. m.myKey, m.myRev, err = NewUniqueKey(ctx, m.kv, m.pfx, v3.WithLease(s.Lease()))
  41. // wait for lock to become available
  42. for err == nil {
  43. // find oldest element in waiters via revision of insertion
  44. var resp *v3.GetResponse
  45. resp, err = m.kv.Get(ctx, m.pfx, v3.WithFirstRev()...)
  46. if err != nil {
  47. break
  48. }
  49. if m.myRev == resp.Kvs[0].CreateRevision {
  50. // myKey is oldest in waiters; myKey holds the lock now
  51. return nil
  52. }
  53. // otherwise myKey isn't lowest, so there must be a pfx prior to myKey
  54. opts := append(v3.WithLastRev(), v3.WithRev(m.myRev-1))
  55. resp, err = m.kv.Get(ctx, m.pfx, opts...)
  56. if err != nil {
  57. break
  58. }
  59. lastKey := string(resp.Kvs[0].Key)
  60. // wait for release on prior pfx
  61. err = waitUpdate(ctx, m.client, lastKey, v3.WithRev(m.myRev))
  62. // try again in case lastKey left the wait list before acquiring the lock;
  63. // myKey can only hold the lock if it's the oldest in the list
  64. }
  65. // release lock key if cancelled
  66. select {
  67. case <-ctx.Done():
  68. m.Unlock()
  69. default:
  70. }
  71. return err
  72. }
  73. func (m *Mutex) Unlock() error {
  74. if _, err := m.kv.Delete(m.ctx, m.myKey); err != nil {
  75. return err
  76. }
  77. m.myKey = "\x00"
  78. m.myRev = -1
  79. return nil
  80. }
  81. func (m *Mutex) IsOwner() v3.Cmp {
  82. return v3.Compare(v3.CreatedRevision(m.myKey), "=", m.myRev)
  83. }
  84. type lockerMutex struct{ *Mutex }
  85. func (lm *lockerMutex) Lock() {
  86. if err := lm.Mutex.Lock(lm.ctx); err != nil {
  87. panic(err)
  88. }
  89. }
  90. func (lm *lockerMutex) Unlock() {
  91. if err := lm.Mutex.Unlock(); err != nil {
  92. panic(err)
  93. }
  94. }
  95. // NewLocker creates a sync.Locker backed by an etcd mutex.
  96. func NewLocker(ctx context.Context, client *v3.Client, pfx string) sync.Locker {
  97. return &lockerMutex{NewMutex(ctx, client, pfx)}
  98. }