mutex.go 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. "fmt"
  17. "sync"
  18. v3 "github.com/coreos/etcd/clientv3"
  19. "golang.org/x/net/context"
  20. )
  21. // Mutex implements the sync Locker interface with etcd
  22. type Mutex struct {
  23. client *v3.Client
  24. pfx string
  25. myKey string
  26. myRev int64
  27. }
  28. func NewMutex(client *v3.Client, pfx string) *Mutex {
  29. return &Mutex{client, 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, serr := NewSession(m.client)
  35. if serr != nil {
  36. return serr
  37. }
  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. resp, err := m.client.Txn(ctx).If(cmp).Then(put).Else(get).Commit()
  45. if err != nil {
  46. return err
  47. }
  48. m.myRev = resp.Header.Revision
  49. if !resp.Succeeded {
  50. m.myRev = resp.Responses[0].GetResponseRange().Kvs[0].CreateRevision
  51. }
  52. // wait for deletion revisions prior to myKey
  53. err = waitDeletes(ctx, m.client, m.pfx, v3.WithPrefix(), v3.WithRev(m.myRev-1))
  54. // release lock key if cancelled
  55. select {
  56. case <-ctx.Done():
  57. m.Unlock()
  58. default:
  59. }
  60. return err
  61. }
  62. func (m *Mutex) Unlock() error {
  63. if _, err := m.client.Delete(m.client.Ctx(), m.myKey); err != nil {
  64. return err
  65. }
  66. m.myKey = "\x00"
  67. m.myRev = -1
  68. return nil
  69. }
  70. func (m *Mutex) IsOwner() v3.Cmp {
  71. return v3.Compare(v3.CreateRevision(m.myKey), "=", m.myRev)
  72. }
  73. func (m *Mutex) Key() string { return m.myKey }
  74. type lockerMutex struct{ *Mutex }
  75. func (lm *lockerMutex) Lock() {
  76. if err := lm.Mutex.Lock(lm.client.Ctx()); err != nil {
  77. panic(err)
  78. }
  79. }
  80. func (lm *lockerMutex) Unlock() {
  81. if err := lm.Mutex.Unlock(); err != nil {
  82. panic(err)
  83. }
  84. }
  85. // NewLocker creates a sync.Locker backed by an etcd mutex.
  86. func NewLocker(client *v3.Client, pfx string) sync.Locker {
  87. return &lockerMutex{NewMutex(client, pfx)}
  88. }