mutex.go 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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. ctx context.Context
  24. pfx string
  25. myKey string
  26. myRev int64
  27. }
  28. func NewMutex(ctx context.Context, client *v3.Client, pfx string) *Mutex {
  29. return &Mutex{client, ctx, pfx, "", -1}
  30. }
  31. // Lock locks the mutex with a cancellable context. If the context is cancelled
  32. // while trying to acquire the lock, the mutex tries to clean its stale lock entry.
  33. func (m *Mutex) Lock(ctx context.Context) error {
  34. s, err := NewSession(m.client)
  35. if err != nil {
  36. return err
  37. }
  38. // put self in lock waiters via myKey; oldest waiter holds lock
  39. m.myKey, m.myRev, err = NewUniqueKey(ctx, m.client, m.pfx, v3.WithLease(s.Lease()))
  40. // wait for lock to become available
  41. for err == nil {
  42. // find oldest element in waiters via revision of insertion
  43. var resp *v3.GetResponse
  44. resp, err = m.client.Get(ctx, m.pfx, v3.WithFirstRev()...)
  45. if err != nil {
  46. break
  47. }
  48. if m.myRev == resp.Kvs[0].CreateRevision {
  49. // myKey is oldest in waiters; myKey holds the lock now
  50. return nil
  51. }
  52. // otherwise myKey isn't lowest, so there must be a pfx prior to myKey
  53. opts := append(v3.WithLastRev(), v3.WithRev(m.myRev-1))
  54. resp, err = m.client.Get(ctx, m.pfx, opts...)
  55. if err != nil {
  56. break
  57. }
  58. lastKey := string(resp.Kvs[0].Key)
  59. // wait for release on prior pfx
  60. err = waitUpdate(ctx, m.client, lastKey, v3.WithRev(m.myRev))
  61. // try again in case lastKey left the wait list before acquiring the lock;
  62. // myKey can only hold the lock if it's the oldest in the list
  63. }
  64. // release lock key if cancelled
  65. select {
  66. case <-ctx.Done():
  67. m.Unlock()
  68. default:
  69. }
  70. return err
  71. }
  72. func (m *Mutex) Unlock() error {
  73. if _, err := m.client.Delete(m.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.CreatedRevision(m.myKey), "=", m.myRev)
  82. }
  83. func (m *Mutex) Key() string { return m.myKey }
  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. }