-
Notifications
You must be signed in to change notification settings - Fork 0
/
gorlock.go
574 lines (479 loc) Β· 15.2 KB
/
gorlock.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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
package gorlock // import "github.com/hunterhug/gorlock"
import (
"context"
"errors"
"github.com/gomodule/redigo/redis"
"github.com/hunterhug/gosession"
"github.com/hunterhug/gosession/kv"
"io"
"strings"
"sync"
"time"
)
const (
defaultRetryCount = 3
defaultUnlockRetryCount = 3
defaultRetryMillSecondDelay = 200
defaultUnlockRetryMillSecondDelay = 200
)
var (
LockEmptyError = errors.New("lock empty")
luaDelScript = redis.NewScript(1, `if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end`)
luaExpireScript = redis.NewScript(2, `if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('PEXPIRE', KEYS[2], ARGV[2]) else return 0 end`)
)
// LockFactory is main interface
type LockFactory interface {
SetRetryCount(c int64) LockFactory
GetRetryCount() int64
SetUnLockRetryCount(c int64) LockFactory
GetUnLockRetryCount() int64
SetKeepAlive(isKeepAlive bool) LockFactory
IsKeepAlive() bool
SetRetryMillSecondDelay(c int64) LockFactory
GetRetryMillSecondDelay() int64
SetUnLockRetryMillSecondDelay(c int64) LockFactory
GetUnLockRetryMillSecondDelay() int64
LockFactoryCore
}
// LockFactoryCore is core interface
type LockFactoryCore interface {
// Lock ,lock resource default keepAlive depend on LockFactory
Lock(ctx context.Context, resourceName string, lockMillSecond int) (lock *Lock, err error)
// LockForceKeepAlive lock resource force keepAlive
LockForceKeepAlive(ctx context.Context, resourceName string, lockMillSecond int) (lock *Lock, err error)
// LockForceNotKeepAlive lock resource force not keepAlive
LockForceNotKeepAlive(ctx context.Context, resourceName string, lockMillSecond int) (lock *Lock, err error)
// UnLock ,unlock resource
UnLock(ctx context.Context, lock *Lock) (isUnLock bool, err error)
// Done asynchronous see lock whether is release
Done(lock *Lock) chan struct{}
}
// redisLockFactory Redis lock factory
type redisLockFactory struct {
// redis pool can single mode or other mode
pool *redis.Pool
// as the name say
retryLockTryCount int64
retryLockMillSecondDelay int64
retryUnLockTryCount int64
retryUnLockMillSecondDelay int64
// auto keep alive the lock util call unlock
isKeepAlive bool
}
// Lock Redis lock
type Lock struct {
// lock time
CreateMillSecondTime int64
// lock live time, TTL
LiveMillSecondTime int
// if isKeepAlive, the last time refresh lock live time
LastKeepAliveMillSecondTime int64
// unlock time
UnlockMillSecondTime int64
// resource you lock
ResourceName string
// unique key of resource lock
RandomKey string
// when lock is unlock, will make chan signal, keepAlive find it unlock or call UnLock()
IsUnlock bool
isUnlockChan chan struct{}
// call UnLock() will set to true
IsClose bool
// the lock is open keep alive
OpenKeepAlive bool
// which Unlock() send to keepAlive()
closeChan chan struct{}
// which keepAlive() response to Unlock()
keepAliveDealCloseChan chan bool
// lock something
mutex sync.Mutex
}
// Done judge lock is whether release
// one example is:
//
// lockFactory.SetKeepAlive(true).SetRetryCount(-1)
// lock, _ := lockFactory.Lock(context.Background(), resourceName, expireMillSecond)
// if lock != nil {
// crontab = true
// }
// select {
// case <- lock.Done():
// crontab = false
// }
//
// very useful for crontab work
func (lock *Lock) Done() chan struct{} {
return lock.isUnlockChan
}
// New make a redis lock factory
// call NewRedisSingleModeConfig and NewRedisSentinelModeConfig then call NewRedisPool
// you can also call kv.NewRedis for diy redis pool
func New(pool *redis.Pool) LockFactory {
if pool.TestOnBorrow == nil {
pool.TestOnBorrow = func(c redis.Conn, t time.Time) error {
if time.Since(t) < time.Minute {
return nil
}
_, err := c.Do("PING")
if err != nil {
Logger.Debugf("redis ping err: %s", err.Error())
}
return err
}
}
factory := &redisLockFactory{
pool: pool,
retryLockTryCount: defaultRetryCount,
retryLockMillSecondDelay: defaultRetryMillSecondDelay,
retryUnLockTryCount: defaultUnlockRetryCount,
retryUnLockMillSecondDelay: defaultUnlockRetryMillSecondDelay,
}
return factory
}
// NewByRedisConfig One step do everyThing
func NewByRedisConfig(redisConf *kv.MyRedisConf) (LockFactory, error) {
pool, err := NewRedisPool(redisConf)
if err != nil {
return nil, err
}
factory := New(pool)
return factory, nil
}
// NewRedisPool make a redis pool
var NewRedisPool = kv.NewRedis
// NewRedisSingleModeConfig redis single mode config
func NewRedisSingleModeConfig(redisHost string, redisDB int, redisPass string) *kv.MyRedisConf {
return &kv.MyRedisConf{
RedisHost: redisHost,
RedisPass: redisPass,
RedisDB: redisDB,
RedisIdleTimeout: 360,
RedisMaxActive: 0,
RedisMaxIdle: 0,
DialConnectTimeout: 20,
DialReadTimeout: 20,
DialWriteTimeout: 20,
}
}
// NewRedisSentinelModeConfig redis sentinel mode config
// redisHost is sentinel address, not redis address
// redisPass is redis password
func NewRedisSentinelModeConfig(redisHost string, redisDB int, redisPass string, masterName string) *kv.MyRedisConf {
return &kv.MyRedisConf{
RedisHost: redisHost,
RedisDB: redisDB,
RedisIdleTimeout: 15,
RedisMaxActive: 0,
RedisMaxIdle: 0,
IsCluster: true,
MasterName: masterName,
RedisPass: redisPass,
}
}
// Done judge lock is whether release
func (s *redisLockFactory) Done(lock *Lock) chan struct{} {
return lock.Done()
}
// SetRetryCount if lock fail, can try again
// if c=0 point not retry, c=1 try ones, and so on.
// if c<0 there will try loop to world die.
func (s *redisLockFactory) SetRetryCount(c int64) LockFactory {
s.retryLockTryCount = c
return s
}
func (s *redisLockFactory) GetRetryCount() int64 {
return s.retryLockTryCount
}
// SetUnLockRetryCount as the SetRetryCount, but is reverse.
func (s *redisLockFactory) SetUnLockRetryCount(c int64) LockFactory {
if c < 0 {
c = defaultUnlockRetryCount
}
s.retryUnLockTryCount = c
return s
}
func (s *redisLockFactory) GetUnLockRetryCount() int64 {
return s.retryUnLockTryCount
}
// SetKeepAlive keep alive the lock
// useful when your work waste a lot of time, you can keep lock alive prevent others grab your lock
func (s *redisLockFactory) SetKeepAlive(isKeepAlive bool) LockFactory {
s.isKeepAlive = isKeepAlive
return s
}
func (s *redisLockFactory) IsKeepAlive() bool {
return s.isKeepAlive
}
// SetRetryMillSecondDelay retry must delay some times
func (s *redisLockFactory) SetRetryMillSecondDelay(c int64) LockFactory {
if c < 0 {
c = defaultRetryMillSecondDelay
}
s.retryLockMillSecondDelay = c
return s
}
func (s *redisLockFactory) GetRetryMillSecondDelay() int64 {
return s.retryLockMillSecondDelay
}
// SetUnLockRetryMillSecondDelay retry must delay sometimes
func (s *redisLockFactory) SetUnLockRetryMillSecondDelay(c int64) LockFactory {
if c < 0 {
c = defaultRetryMillSecondDelay
}
s.retryUnLockMillSecondDelay = c
return s
}
func (s *redisLockFactory) GetUnLockRetryMillSecondDelay() int64 {
return s.retryUnLockMillSecondDelay
}
// Lock ,lock the resource with lockMillSecond TTL(Time to Live) time
// take context.Context to control time out lock when try many times
func (s *redisLockFactory) Lock(ctx context.Context, resourceName string, lockMillSecond int) (lock *Lock, err error) {
return s.lock(ctx, resourceName, lockMillSecond, true, false)
}
// LockForceKeepAlive lock force keepAlive, must call defer Unlock()
func (s *redisLockFactory) LockForceKeepAlive(ctx context.Context, resourceName string, lockMillSecond int) (lock *Lock, err error) {
return s.lock(ctx, resourceName, lockMillSecond, false, true)
}
// LockForceNotKeepAlive lock force not keepalive
func (s *redisLockFactory) LockForceNotKeepAlive(ctx context.Context, resourceName string, lockMillSecond int) (lock *Lock, err error) {
return s.lock(ctx, resourceName, lockMillSecond, false, false)
}
func IsConnError(err error) bool {
var needNewConn bool
if err == nil {
return false
}
if err == io.EOF {
needNewConn = true
}
if strings.Contains(err.Error(), "use of closed network connection") {
needNewConn = true
}
if strings.Contains(err.Error(), "connect: connection refused") {
needNewConn = true
}
return needNewConn
}
func (s *redisLockFactory) lock(ctx context.Context, resourceName string, lockMillSecond int, useFactoryKeepAlive bool, keepAlive bool) (lock *Lock, err error) {
// get redis con
conn := s.pool.Get()
defer func(conn redis.Conn) {
err := conn.Close()
if err != nil {
// ignore
}
}(conn)
// ttl add one second for magic
lockTime := lockMillSecond + 1
randomKey := gosession.GetGUID()
retry := s.retryLockTryCount + 1
for retry > 0 || retry <= 0 {
select {
// if time out, return
case <-ctx.Done():
return nil, ctx.Err()
default:
beginTime := time.Now().String()
retry -= 1
rep, err := redis.String(conn.Do("set", resourceName, randomKey, "nx", "px", lockTime))
success := false
if err != nil {
if IsConnError(err) {
Logger.Debugf("lock start in %v lock %s with random key:%s, expire: %d ms err:%s", beginTime, resourceName, randomKey, lockMillSecond, err.Error())
return nil, err
}
// after Redis 2.6.12, set nx will return nil reply if condition not match
if err == redis.ErrNil {
} else {
// redis inner err
// debug you can SetLogLevel("DEBUG")
Logger.Debugf("lock start in %v lock %s with random key:%s, expire: %d ms err:%s", beginTime, resourceName, randomKey, lockMillSecond, err.Error())
// retry again
if retry != 0 {
time.Sleep(time.Duration(s.retryLockMillSecondDelay) * time.Millisecond)
continue
}
return nil, err
}
}
if rep == "OK" {
// success we go
success = true
}
if !success {
// lock is hold by others
Logger.Debugf("lock start in %v lock %s with random key:%s, expire: %d ms not lock", beginTime, resourceName, randomKey, lockMillSecond)
if retry != 0 {
// try again
time.Sleep(time.Duration(s.retryLockMillSecondDelay) * time.Millisecond)
continue
}
return nil, nil
}
// lock is success gen, make a Lock return
lock = new(Lock)
lock.LiveMillSecondTime = lockTime
lock.RandomKey = randomKey
lock.ResourceName = resourceName
lock.CreateMillSecondTime = time.Now().UnixNano() / 1e6
// when lock unlock, send a chan to caller
lock.isUnlockChan = make(chan struct{}, 1)
if useFactoryKeepAlive {
// if is keepAlive, we make a new goroutine to do the work
if s.isKeepAlive {
lock.OpenKeepAlive = true
lock.closeChan = make(chan struct{})
lock.keepAliveDealCloseChan = make(chan bool)
go s.keepAlive(lock)
}
} else {
if keepAlive {
lock.OpenKeepAlive = true
lock.closeChan = make(chan struct{})
lock.keepAliveDealCloseChan = make(chan bool)
go s.keepAlive(lock)
}
}
return lock, nil
}
}
return nil, LockEmptyError
}
// UnLock ,unlock the resource, but now we should pass variable "lock Lock" into func but not resource name
// suggest call defer UnLock() after Lock()
func (s *redisLockFactory) UnLock(ctx context.Context, lock *Lock) (isUnLock bool, err error) {
if lock == nil {
return false, LockEmptyError
}
// avoid unlock the same, mutex it
lock.mutex.Lock()
defer lock.mutex.Unlock()
// only can call unlock once
if lock.IsClose {
return true, nil
}
lock.IsClose = true
if lock.OpenKeepAlive {
Logger.Debug("UnLock send signal to keepAlive ask game over")
// will block util keepAlive deal
lock.closeChan <- struct{}{}
keepAliveHasBeenClose := <-lock.keepAliveDealCloseChan
if keepAliveHasBeenClose {
Logger.Debugf("UnLock receive signal to keepAlive response keepAliveHasBeenClose=%v UnLock direct return", keepAliveHasBeenClose)
return true, nil
}
Logger.Debugf("UnLock receive signal to keepAlive response keepAliveHasBeenClose=%v", keepAliveHasBeenClose)
} else {
lock.IsUnlock = true
lock.UnlockMillSecondTime = time.Now().UnixNano() / 1e6
// close a close chan
if lock.closeChan != nil {
close(lock.closeChan)
}
// unlock chan send
lock.isUnlockChan <- struct{}{}
}
conn := s.pool.Get()
defer func(conn redis.Conn) {
err := conn.Close()
if err != nil {
// ignore
}
}(conn)
retry := s.retryUnLockTryCount + 1
for retry > 0 {
select {
case <-ctx.Done():
return false, ctx.Err()
default:
beginTime := time.Now().String()
retry -= 1
rep, err := redis.Int64(luaDelScript.Do(conn, lock.ResourceName, lock.RandomKey))
if err != nil {
Logger.Debugf("UnLock start in %v unlock %s with random key:%s, err:%s", beginTime, lock.ResourceName, lock.RandomKey, err.Error())
if IsConnError(err) {
return false, err
}
if retry != 0 {
time.Sleep(time.Duration(s.retryUnLockMillSecondDelay) * time.Millisecond)
continue
}
return false, err
}
if rep != 1 {
// no err but the lock is not exist, may be expired or grab by others
Logger.Debugf("UnLock start in %v unlock %s with random key:%s not unlock", beginTime, lock.ResourceName, lock.RandomKey)
return false, nil
}
// unlock success
return true, nil
}
}
return false, LockEmptyError
}
func (s *redisLockFactory) keepAliveSendToRedis(lock *Lock) (int64, error) {
conn := s.pool.Get()
defer func(conn redis.Conn) {
err := conn.Close()
if err != nil {
// ignore
}
}(conn)
rep, err := redis.Int64(luaExpireScript.Do(conn, lock.ResourceName, lock.ResourceName, lock.RandomKey, lock.LiveMillSecondTime))
return rep, err
}
func (s *redisLockFactory) keepAlive(lock *Lock) {
isKeepAliveFail := false
for {
if isKeepAliveFail && !lock.IsClose {
go func() {
_, err := s.UnLock(context.Background(), lock)
if err != nil {
// ignore
}
}()
}
select {
case <-lock.closeChan:
// receive a close chan
beginTime := time.Now().String()
Logger.Debugf("start in %v keepAlive %s with random key:%s close", beginTime, lock.ResourceName, lock.RandomKey)
if !isKeepAliveFail {
lock.IsUnlock = true
lock.UnlockMillSecondTime = time.Now().UnixNano() / 1e6
lock.isUnlockChan <- struct{}{}
}
close(lock.closeChan)
lock.keepAliveDealCloseChan <- isKeepAliveFail
return
case <-time.After(500 * time.Millisecond):
if isKeepAliveFail {
continue
}
beginTime := time.Now().String()
rep, err := s.keepAliveSendToRedis(lock)
if err != nil {
// if redis inner err, retry forever
Logger.Debugf("start in %v keepAlive %s with random key:%s, err:%s", beginTime, lock.ResourceName, lock.RandomKey, err.Error())
continue
}
if rep != 1 {
// lock not exist or others grab it
Logger.Debugf("start in %v keepAlive %s with random key:%s not keepAlive=%v", beginTime, lock.ResourceName, lock.RandomKey, rep)
lock.IsUnlock = true
lock.UnlockMillSecondTime = time.Now().UnixNano() / 1e6
lock.isUnlockChan <- struct{}{}
isKeepAliveFail = true
// will loop util call Unlock()
continue
}
lock.LastKeepAliveMillSecondTime = time.Now().UnixNano() / 1e6
Logger.Debugf("start in %v keepAlive %s with random key:%s doing", beginTime, lock.ResourceName, lock.RandomKey)
}
}
}
// SetDebug for debug
func SetDebug() {
SetLogLevel(DEBUG)
}