-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrdl.go
More file actions
251 lines (227 loc) Β· 4.48 KB
/
Copy pathrdl.go
File metadata and controls
251 lines (227 loc) Β· 4.48 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
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package rdl
import (
"context"
"fmt"
"math/rand"
"net"
"strconv"
"sync"
"time"
)
var ErrNotGetLock = e("failed to get lock")
var ErrTimeout = e("timeout")
var ErrConfNotValid = e("conf is not valid")
// RedisClient is the interface of redis client
type RedisClient interface {
// set k, v with expire time if origin value is old or not exists(nil).
// NOTE: make sure this is an atomic operation.
SetIfValIs(key, new string, ex time.Duration, old string) (ok bool)
}
// Rdl is a locker
type Rdl struct {
mu *sync.Mutex
c *Conf
cli RedisClient
set time.Time
hasLock bool
name string
val string
}
// New returns a new lock with redisclient and key name
func New(cli RedisClient, name string, confs ...*Conf) *Rdl {
conf := DefaultConf()
if len(confs) != 0 {
conf = confs[0]
}
if !conf.isValid() {
panic(ErrConfNotValid)
}
return &Rdl{
mu: new(sync.Mutex),
c: conf,
cli: cli,
name: name,
}
}
// Lock returns whether get lock
func (r *Rdl) Lock() bool {
r.mu.Lock()
defer r.mu.Unlock()
for i := 0; i <= r.c.retry; i++ {
var (
start = time.Now()
ticker = time.NewTicker(r.c.timeout)
loop = true
d = time.Duration(0)
)
for loop {
select {
case <-ticker.C:
loop = false
break
case <-time.After(d):
if r.getLock() {
r.set = time.Now()
r.hasLock = true
time.AfterFunc(r.remain(), func() {
r.hasLock = false
})
if r.c.autoRenewal {
go r.autoRenewal()
}
return true
}
d = r.c.wait
remain := r.c.timeout -
time.Now().Sub(start)
if d > remain {
d = remain
}
}
}
}
return false
}
// LockWithCancel likes `Lock` but with a context.
func (r *Rdl) LockWithContext(ctx context.Context) bool {
r.mu.Lock()
defer r.mu.Unlock()
for i := 0; i <= r.c.retry; i++ {
var (
start = time.Now()
ticker = time.NewTicker(r.c.timeout)
loop = true
d = time.Duration(0)
)
for loop {
select {
case <-ticker.C:
loop = false
break
case <-ctx.Done():
return false
case <-time.After(d):
if r.getLock() {
r.set = time.Now()
r.hasLock = true
time.AfterFunc(r.remain(), func() {
r.hasLock = false
})
if r.c.autoRenewal {
go r.autoRenewal()
}
return true
}
d = r.c.wait
remain := r.c.timeout -
time.Now().Sub(start)
if d > remain {
d = remain
}
}
}
}
return false
}
// Unlock release the lock. If can not put lock back, Unlock retry until the
// lock expired.
func (r *Rdl) Unlock() {
r.mu.Lock()
defer func() {
r.mu.Unlock()
r.hasLock = false
}()
if !r.hasLock {
return
}
if r.putLock() {
return
}
done := make(chan struct{})
for {
select {
case <-time.After(r.remain()):
return
case <-time.After(1 * time.Nanosecond):
go func() {
if r.putLock() {
done <- struct{}{}
}
}()
case <-done:
return
}
}
}
// remain returns the rest time of holding lock
func (r *Rdl) remain() time.Duration {
if !r.hasLock {
return 0
}
return r.c.timeout - time.Now().Sub(r.set)
}
// renewal renewal the time of holding lock
func (r *Rdl) renewal() {
// TODO: if the lock can not get, it means something wrong with redis or
// the network or the method SetIfValIs. How to fix?
r.cli.SetIfValIs(r.name, r.val, r.c.timeout, r.val)
}
// autoRenewal execute r.renewal() every renewalTime
func (r *Rdl) autoRenewal() {
for r.hasLock {
time.AfterFunc(r.c.renewalTime, func() { r.renewal() })
}
}
// getLock get the lock
func (r *Rdl) getLock() bool {
v := random()
ok := r.cli.SetIfValIs(r.name, v, r.c.timeout, "")
if ok {
r.val = v
}
return ok
}
// put lock put the lock back
func (r *Rdl) putLock() bool {
return r.cli.SetIfValIs(r.name, "", 1*time.Second, r.val)
}
// randome returns a random string value based on time.Now().UnixNano()
func random() string {
return getLocalIp() + strconv.Itoa(
rand.New(
rand.NewSource(
time.Now().UnixNano(),
),
).Int(),
)
}
// getLocalIp returns local ip
func getLocalIp() string {
ifaces, err := net.Interfaces()
if err != nil {
return ""
}
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
continue
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if ip.To4() != nil && !ip.IsLoopback() {
return ip.To4().String()
}
}
}
return ""
}
// e wrap the msg into an error
func e(msg string) error {
return fmt.Errorf("[%s] %s.", "RDL", msg)
}