-
Notifications
You must be signed in to change notification settings - Fork 1
/
locks.go
230 lines (196 loc) · 5.04 KB
/
locks.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package discordha
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"math/rand"
"time"
"github.com/coreos/etcd/clientv3"
"go.etcd.io/etcd/clientv3/concurrency"
)
// etcd states to store in value
const (
statusNone = "0"
statusHandling = "1"
statusOk = "2"
)
func init() {
rand.Seed(time.Now().UTC().UnixNano())
}
func (h *HAInstance) ElectLeader(ctx context.Context) error {
if !h.config.HA {
// Non HA, development instance probably
return nil
}
e := concurrency.NewElection(h.concurrency, "/discordha-election/")
if err := e.Campaign(ctx, h.name); err != nil {
return err
}
h.config.Log.Println("Became leader")
h.isLeader = true
return nil
}
func (h *HAInstance) ResignLeader(ctx context.Context) error {
if !h.config.HA {
// Non HA, development instance probably
return nil
}
e := concurrency.NewElection(h.concurrency, "/discordha-election/")
if err := e.Resign(ctx); err != nil {
return err
}
h.isLeader = false
return nil
}
func (h *HAInstance) AmLeader(ctx context.Context) bool {
if !h.config.HA {
// Non HA, development instance probably
return true
}
if !h.isLeader {
// saves one etcd roundtrip
return false
}
e := concurrency.NewElection(h.concurrency, "/discordha-election/")
resp, err := e.Leader(ctx)
if err != nil {
h.config.Log.Println("AmLeader error", err)
return false
}
return bytes.Equal(resp.Kvs[0].Value, []byte(h.name))
}
func (h *HAInstance) lockUpdateLoop(ctx context.Context) {
ticker := time.NewTicker(h.config.LockUpdateInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
h.locksMutex.Lock()
for _, lease := range h.locks {
err := h.keepAlive(lease)
if err != nil {
h.config.Log.Printf("Etcd keepalive error: %q\n", err)
}
}
h.locksMutex.Unlock()
}
}
}
func (h *HAInstance) logLoop(ctx context.Context, logInterval time.Duration) {
ticker := time.NewTicker(logInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
h.locksMutex.Lock()
h.config.Log.Printf("I own %d locks\n", len(h.locks))
h.locksMutex.Unlock()
}
}
}
// Lock tries to acquire a lock on an event, it will return true if
// the instance that requests it may process the request.
func (h *HAInstance) Lock(obj interface{}) (bool, string, error) {
if !h.config.HA {
// Non HA, development instance probably
return true, "", nil
}
hash, err := h.getObjectHash(obj)
if err != nil {
h.config.Log.Printf("Hash error:%q\n", err)
return false, "", err
}
key := fmt.Sprintf("/locks/%s", hash)
goAhead, err := h.lockKey(key, true)
return goAhead, hash, err
}
func (h *HAInstance) lockKey(key string, waitForFailure bool) (bool, error) {
grant, err := h.etcd.Grant(h.bgContext, int64(h.config.LockTTL.Seconds()))
if err != nil {
return false, err
}
txn, err := h.etcd.Txn(h.bgContext).
// txn value comparisons are lexical
If(clientv3.Compare(clientv3.Value(key), ">", statusNone)).
Else(clientv3.OpPut(key, statusHandling, clientv3.WithLease(grant.ID))).
Commit()
if err != nil {
return false, err
}
// if clientv3.Compare(clientv3.Value(key), ">", statusNone) is true
if txn.Succeeded {
// Lock exists!
if !waitForFailure {
return false, nil
}
ctx, cancel := context.WithCancel(h.bgContext)
defer cancel()
w := h.etcd.Watch(ctx, key)
for wresp := range w {
if wresp.Canceled {
return h.lockKey(key, waitForFailure) // attempt watch again!
}
for _, ev := range wresp.Events {
if string(ev.Kv.Value) == statusOk {
// other server succeeded!
return false, nil
}
if ev.Type == clientv3.EventTypeDelete {
return h.lockKey(key, waitForFailure) // re-lock!
}
}
}
return false, nil
}
h.locksMutex.Lock()
h.locks[key] = grant.ID
h.locksMutex.Unlock()
return true, nil
}
// Unlock will release a lock on an event
func (h *HAInstance) Unlock(lockKey string) error {
if !h.config.HA {
// Non HA, development instance probably
return nil
}
key := fmt.Sprintf("/locks/%s", lockKey)
return h.unlockKey(key, 0)
}
func (h *HAInstance) unlockKey(key string, tries int) error {
tries++
h.keepAlive(h.locks[key]) // keep lock in etcd till it expires so all servers catch up
_, err := h.etcd.Put(h.bgContext, key, statusOk, clientv3.WithLease(h.locks[key]))
if err != nil {
h.config.Log.Printf("Failed to set status OK: %q retrying", err)
time.Sleep(5 * time.Duration(tries) * time.Second)
if tries > 100 {
h.config.Log.Printf("Fatal to set status OK: %q not retrying", err)
} else {
return h.unlockKey(key, tries)
}
}
h.locksMutex.Lock()
delete(h.locks, key)
h.locksMutex.Unlock()
return nil
}
func (h *HAInstance) keepAlive(leaseID clientv3.LeaseID) error {
_, err := h.etcd.KeepAlive(h.bgContext, leaseID)
return err
}
func (h *HAInstance) getObjectHash(v interface{}) (string, error) {
jsonData, err := json.Marshal(v)
if err != nil {
return "", err
}
hasher := sha256.New()
hasher.Write(jsonData)
return base64.URLEncoding.EncodeToString(hasher.Sum(nil)), nil
}