-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmutex.go
More file actions
118 lines (97 loc) · 2.34 KB
/
mutex.go
File metadata and controls
118 lines (97 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package supervisor
import (
"errors"
"fmt"
"time"
"github.com/samuel/go-zookeeper/zk"
)
// Mutex holds mutex information
type Mutex struct {
client *Client
key string
path string
lockPath string
guid string
locked bool
}
// Acquire blocks until it's available
func (m *Mutex) Acquire(waitTime int64, unit time.Duration) error {
if !m.client.isConnected {
return errors.New("Client not connected")
}
_, err := m.client.createParentNodeIfNotExists(m.path, []byte{})
if err != nil {
return err
}
abspath, guid, err := m.client.createProtectedEphemeralSequential(m.path, []byte{})
if err != nil {
return fmt.Errorf("%s - %s", err.Error(), m.path)
}
m.lockPath = abspath
m.guid = guid
for !m.locked {
children, _, channel, err := m.client.childrenWatch(m.path)
if err != nil {
return fmt.Errorf("%s - %s", err.Error(), m.path)
}
if len(children) == 1 {
m.locked = true
break
}
timeout := make(chan bool, 0)
go func() {
time.Sleep(time.Duration(waitTime) * unit)
timeout <- true
}()
select {
case <-timeout:
if err := m.client.deleteNodeLastVersion(m.lockPath); err != nil {
return fmt.Errorf("Could not remove node %s - %s", m.path, err.Error())
}
return errors.New("Timeout")
case event := <-channel:
if event.Type == zk.EventNodeChildrenChanged {
nodeGUIDList, err := m.client.getSortedNodeGUIDList(m.path)
if err != nil {
return err
}
if nodeGUIDList[0] == m.guid {
m.locked = true
break
}
}
}
}
return nil
}
// Release performs one release of the mutex
func (m *Mutex) Release() error {
if !m.locked {
return errors.New("Key [" + m.key + "] not locked")
}
if err := m.cleanup(); err != nil {
return err
}
return nil
}
func (m *Mutex) cleanup() error {
if err := m.client.deleteNodeLastVersion(m.lockPath); err != nil {
return fmt.Errorf("Could not remove node %s - %s", m.path, err.Error())
}
m.locked = false
if err := m.client.deleteNodeLastVersion(m.path); err != nil {
return err
}
m.guid = ""
m.lockPath = ""
return nil
}
// NewMutex returns new mutex for distributed lock
func NewMutex(c *Client, path string) *Mutex {
m := Mutex{
client: c,
path: path,
locked: false,
}
return &m
}