mutex.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 recipe
  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. "github.com/coreos/etcd/storage/storagepb"
  20. )
  21. // Mutex implements the sync Locker interface with etcd
  22. type Mutex struct {
  23. client *v3.Client
  24. kv v3.KV
  25. ctx context.Context
  26. key string
  27. myKey *EphemeralKV
  28. }
  29. func NewMutex(client *v3.Client, key string) *Mutex {
  30. return &Mutex{client, v3.NewKV(client), context.TODO(), key, nil}
  31. }
  32. func (m *Mutex) Lock() (err error) {
  33. // put self in lock waiters via myKey; oldest waiter holds lock
  34. m.myKey, err = NewUniqueEphemeralKey(m.client, m.key)
  35. if err != nil {
  36. return err
  37. }
  38. // find oldest element in waiters via revision of insertion
  39. resp, err := m.kv.Get(m.ctx, m.key, withFirstRev()...)
  40. if err != nil {
  41. return err
  42. }
  43. // if myKey is oldest in waiters, then myKey holds the lock
  44. if m.myKey.Revision() == resp.Kvs[0].CreateRevision {
  45. return nil
  46. }
  47. // otherwise myKey isn't lowest, so there must be a key prior to myKey
  48. opts := append(withLastRev(), v3.WithRev(m.myKey.Revision()-1))
  49. lastKey, err := m.kv.Get(m.ctx, m.key, opts...)
  50. if err != nil {
  51. return err
  52. }
  53. // wait for release on prior key
  54. _, err = WaitEvents(
  55. m.client,
  56. string(lastKey.Kvs[0].Key),
  57. m.myKey.Revision()-1,
  58. []storagepb.Event_EventType{storagepb.DELETE})
  59. // myKey now oldest
  60. return err
  61. }
  62. func (m *Mutex) Unlock() error {
  63. err := m.myKey.Delete()
  64. m.myKey = nil
  65. return err
  66. }
  67. type lockerMutex struct{ *Mutex }
  68. func (lm *lockerMutex) Lock() {
  69. if err := lm.Mutex.Lock(); err != nil {
  70. panic(err)
  71. }
  72. }
  73. func (lm *lockerMutex) Unlock() {
  74. if err := lm.Mutex.Unlock(); err != nil {
  75. panic(err)
  76. }
  77. }
  78. func NewLocker(client *v3.Client, key string) sync.Locker {
  79. return &lockerMutex{NewMutex(client, key)}
  80. }