mutex.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 deletion revisions prior to myKey
  41. err = waitDeletes(ctx, m.client, m.pfx, v3.WithPrefix(), v3.WithRev(m.myRev-1))
  42. // release lock key if cancelled
  43. select {
  44. case <-ctx.Done():
  45. m.Unlock()
  46. default:
  47. }
  48. return err
  49. }
  50. func (m *Mutex) Unlock() error {
  51. if _, err := m.client.Delete(m.ctx, m.myKey); err != nil {
  52. return err
  53. }
  54. m.myKey = "\x00"
  55. m.myRev = -1
  56. return nil
  57. }
  58. func (m *Mutex) IsOwner() v3.Cmp {
  59. return v3.Compare(v3.CreatedRevision(m.myKey), "=", m.myRev)
  60. }
  61. func (m *Mutex) Key() string { return m.myKey }
  62. type lockerMutex struct{ *Mutex }
  63. func (lm *lockerMutex) Lock() {
  64. if err := lm.Mutex.Lock(lm.ctx); err != nil {
  65. panic(err)
  66. }
  67. }
  68. func (lm *lockerMutex) Unlock() {
  69. if err := lm.Mutex.Unlock(); err != nil {
  70. panic(err)
  71. }
  72. }
  73. // NewLocker creates a sync.Locker backed by an etcd mutex.
  74. func NewLocker(ctx context.Context, client *v3.Client, pfx string) sync.Locker {
  75. return &lockerMutex{NewMutex(ctx, client, pfx)}
  76. }