forked from samuel/go-zookeeper
/
lock.go
193 lines (173 loc) · 4.48 KB
/
lock.go
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
package zk
import (
"errors"
"fmt"
"strconv"
"strings"
"time"
)
var (
ErrDeadlock = errors.New("zk: trying to acquire a lock twice")
ErrNotLocked = errors.New("zk: not locked")
ErrLockTimeout = errors.New("zk: timeout trying to acquire lock")
)
type Lock struct {
c *Conn
path string
acl []ACL
lockPath string
seq int
acquisitionTimeout time.Duration
ttl time.Duration
}
func NewLock(c *Conn, path string, acl []ACL) *Lock {
return &Lock{
c: c,
path: path,
acl: acl,
}
}
func parseSeq(path string) (int, error) {
parts := strings.Split(path, "-")
return strconv.Atoi(parts[len(parts)-1])
}
// SetTimeout sets the time we will wait to acquire the lock, bail out if time is exceeded
func (l *Lock) SetTimeout(d time.Duration) {
l.acquisitionTimeout = d
}
// SetTTL sets the max time that the lock should live for
func (l *Lock) SetTTL(d time.Duration) {
l.ttl = d
}
// Lock attempts to acquire a lock.
// Uses the recipe http://zookeeper.apache.org/doc/trunk/recipes.html#sc_recipes_Locks.
// Timeout achieved by first creating the lock node and then waiting X secs. If lock not yet acquired it will delete and then return.
// Does not account for initial request taking too long
func (l *Lock) Lock() error {
if l.lockPath != "" {
return ErrDeadlock
}
prefix := fmt.Sprintf("%s/lock-", l.path)
path := ""
var err error
data := []byte{}
if l.ttl > 0 {
data, _ = time.Now().Add(l.ttl).GobEncode()
}
maxEnd := time.Now().Add(l.acquisitionTimeout)
path, err = l.c.CreateProtectedEphemeralSequential(prefix, data, l.acl)
if err == ErrNoNode {
// Create parent nodes and try again
parts := strings.Split(l.path, "/")
pth := ""
for _, p := range parts[1:] {
pth += "/" + p
_, err := l.c.Create(pth, []byte{}, 0, l.acl)
if err != nil && err != ErrNodeExists {
// Timeout error could be here too
return err
}
}
path, err = l.c.CreateProtectedEphemeralSequential(prefix, data, l.acl)
if err != nil {
return err
}
} else if err != nil {
return err
}
seq, err := parseSeq(path)
if err != nil {
return err
}
// wait for lock to be acquired
for {
lowestSeq, prevSeqPath, err := l.findLowestSequenceNode(seq)
if seq == lowestSeq {
// Acquired the lock
break
}
// Wait on the node next in line for the lock by setting watcher
_, _, ch, err := l.c.GetW(l.path + "/" + prevSeqPath)
if err != nil && err != ErrNoNode {
return err
} else if err != nil && err == ErrNoNode {
// try again
continue
}
// Wait for a timeout period before giving up trying to achieve the lock
var ev Event
if l.acquisitionTimeout == 0 {
ev = <-ch // watch event fired
} else {
select {
case ev = <-ch: // watch event fired
case <-time.After(maxEnd.Sub(time.Now())): // handles -ve
// clean up after ourself
return l.cleanUpTimeoutLock(path)
}
}
if ev.Err != nil {
return ev.Err
}
}
l.seq = seq
l.lockPath = path
return nil
}
func (l *Lock) findLowestSequenceNode(seq int) (lowestSeq int, prevSeqPath string, err error) {
children, _, err := l.c.Children(l.path)
if err != nil {
return -1, "", err
}
var ttl time.Time
lowestSeq = seq
prevSeq := 0
prevSeqPath = ""
for _, p := range children {
// check if this lock has timed out TODO keep this?
data, _, _ := l.c.Get(l.path + "/" + p)
if len(data) > 0 {
err := ttl.GobDecode(data)
if err == nil { // data might not be a time
if ttl.Before(time.Now()) {
l.c.Delete(l.path+"/"+p, -1)
continue
}
}
}
s, err := parseSeq(p)
if err != nil {
return -1, "", err
}
if s < lowestSeq {
lowestSeq = s
}
if s < seq && s > prevSeq {
prevSeq = s
prevSeqPath = p
}
}
return lowestSeq, prevSeqPath, err
}
func (l *Lock) cleanUpTimeoutLock(path string) error {
if err := l.c.Delete(path, -1); err != nil {
// Delete failed, so disconnect to trigger ephemeral nodes to clear
if closeErr := l.c.conn.Close(); closeErr != nil {
return fmt.Errorf("Failed to get lock after %v, then failed to delete ourself (%v), then failed to close connection (%v)", l.acquisitionTimeout, err, closeErr)
} else {
return fmt.Errorf("Failed to get lock after %v, then failed to delete ourself (%v)", l.acquisitionTimeout, err)
}
}
return ErrLockTimeout
}
func (l *Lock) Unlock() error {
if l.lockPath == "" {
return ErrNotLocked
}
if err := l.c.Delete(l.lockPath, -1); err != nil {
return err
}
l.lockPath = ""
l.seq = 0
return nil
}