forked from bsm/redis-lock
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlock.go
147 lines (122 loc) · 3.12 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
package redlock
import (
"crypto/rand"
"encoding/base64"
"strconv"
"sync"
"time"
"gopkg.in/redis.v3"
)
const luaRefresh = `if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("pexpire", KEYS[1], ARGV[2]) else return 0 end`
const luaRelease = `if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end`
// RedisClient is a minimal client interface, supported by gopkg.in/redis.v3
type RedisClient interface {
SetNX(key string, value interface{}, expiration time.Duration) *redis.BoolCmd
Eval(script string, keys []string, args []string) *redis.Cmd
}
type Lock struct {
client RedisClient
key string
opts LockOptions
token string
mutex sync.Mutex
}
// ObtainLock is a shortcut for NewLock().Lock()
func ObtainLock(client RedisClient, key string, opts *LockOptions) (*Lock, error) {
lock := NewLock(client, key, opts)
if ok, err := lock.Lock(); err != nil || !ok {
return nil, err
}
return lock, nil
}
// NewLock creates a new distributed lock on key
func NewLock(client RedisClient, key string, opts *LockOptions) *Lock {
if opts == nil {
opts = new(LockOptions)
}
return &Lock{client: client, key: key, opts: *opts.normalize()}
}
// IsLocked returns true if a lock is acquired
func (l *Lock) IsLocked() bool {
l.mutex.Lock()
locked := l.token != ""
l.mutex.Unlock()
return locked
}
// Lock applies the lock, don't forget to defer the Unlock() function to release the lock after usage
func (l *Lock) Lock() (bool, error) {
l.mutex.Lock()
defer l.mutex.Unlock()
if l.token != "" {
return l.refresh()
}
return l.create()
}
// Unlock releases the lock
func (l *Lock) Unlock() error {
l.mutex.Lock()
err := l.release()
l.mutex.Unlock()
return err
}
// Helpers
func (l *Lock) create() (bool, error) {
l.reset()
// Create a random token
token, err := randomToken()
if err != nil {
return false, err
}
// Calculate the timestamp we are willing to wait for
stop := time.Now().Add(l.opts.WaitTimeout)
for {
// Try to obtain a lock
ok, err := l.obtain(token)
if err != nil {
return false, err
} else if ok {
l.token = token
return true, nil
}
if time.Now().Add(l.opts.WaitRetry).After(stop) {
break
}
time.Sleep(l.opts.WaitRetry)
}
return false, nil
}
func (l *Lock) refresh() (bool, error) {
ttl := strconv.FormatInt(int64(l.opts.LockTimeout/time.Millisecond), 10)
status, err := l.client.Eval(luaRefresh, []string{l.key}, []string{l.token, ttl}).Result()
if err != nil {
return false, err
} else if status == int64(1) {
return true, nil
}
return l.create()
}
func (l *Lock) obtain(token string) (bool, error) {
ok, err := l.client.SetNX(l.key, token, l.opts.LockTimeout).Result()
if err == redis.Nil {
err = nil
}
return ok, err
}
func (l *Lock) release() error {
defer l.reset()
err := l.client.Eval(luaRelease, []string{l.key}, []string{l.token}).Err()
if err == redis.Nil {
err = nil
}
return err
}
func (l *Lock) reset() {
l.token = ""
}
func randomToken() (string, error) {
buf := make([]byte, 16)
if _, err := rand.Read(buf); err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(buf), nil
}