-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmutex.go
198 lines (176 loc) · 4.33 KB
/
mutex.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
package godisson
import (
"context"
"github.com/pkg/errors"
"net"
"time"
)
type Mutex struct {
Key string
g *Godisson
cancelFunc context.CancelFunc
}
var _ Locker = (*Mutex)(nil)
func newMutex(key string, g *Godisson) *Mutex {
return &Mutex{Key: key, g: g}
}
func (m *Mutex) TryLock(waitTime int64, leaseTime int64) error {
wait := waitTime
current := currentTimeMillis()
ttl, err := m.tryAcquire(waitTime, leaseTime)
if err != nil {
return err
}
if ttl == 0 {
return nil
}
wait -= currentTimeMillis() - current
if wait <= 0 {
return ErrLockNotObtained
}
current = currentTimeMillis()
// PubSub
sub := m.g.c.Subscribe(context.TODO(), m.g.getChannelName(m.Key))
defer sub.Close()
timeoutCtx, timeoutCancel := context.WithTimeout(context.TODO(), time.Duration(wait)*time.Millisecond)
defer timeoutCancel()
_, err = sub.ReceiveMessage(timeoutCtx)
if err != nil {
return ErrLockNotObtained
}
wait -= currentTimeMillis() - current
if wait <= 0 {
return ErrLockNotObtained
}
for {
currentTime := currentTimeMillis()
ttl, err = m.tryAcquire(waitTime, leaseTime)
if ttl == 0 {
return nil
}
wait -= currentTimeMillis() - currentTime
if wait <= 0 {
return ErrLockNotObtained
}
currentTime = currentTimeMillis()
var target *net.OpError
if ttl >= 0 && ttl < wait {
tCtx, _ := context.WithTimeout(context.TODO(), time.Duration(ttl)*time.Millisecond)
_, err := sub.ReceiveMessage(tCtx)
if err != nil {
if errors.As(err, &target) {
continue
}
}
} else {
tCtx, _ := context.WithTimeout(context.TODO(), time.Duration(wait)*time.Millisecond)
_, err := sub.ReceiveMessage(tCtx)
if err != nil {
if errors.As(err, &target) {
continue
}
}
}
wait -= currentTimeMillis() - currentTime
if wait <= 0 {
return ErrLockNotObtained
}
}
}
func (m *Mutex) tryAcquire(waitTime int64, leaseTime int64) (int64, error) {
if leaseTime != -1 {
return m.tryAcquireInner(waitTime, leaseTime)
}
ttl, err := m.tryAcquire(waitTime, m.g.watchDogTimeout.Milliseconds())
if err != nil {
return 0, err
}
if ttl == 0 {
m.renewExpirationScheduler()
}
return ttl, nil
}
func (m *Mutex) tryAcquireInner(waitTime int64, leaseTime int64) (int64, error) {
result, err := m.g.c.Eval(context.Background(), `
if (redis.call('exists', KEYS[1]) == 0) then
redis.call('set', KEYS[1], 1);
redis.call('pexpire', KEYS[1], ARGV[1]);
return 0;
end;
return redis.call('pttl', KEYS[1]);
`, []string{m.Key}, leaseTime).Result()
if err != nil {
return 0, err
}
if ttl, ok := result.(int64); ok {
return ttl, nil
} else {
return 0, errors.Errorf("tryAcquireInner result converter to int64 error, value is %v", result)
}
}
func (m *Mutex) Unlock() (int64, error) {
defer m.cancelExpirationRenewal()
result, err := m.g.c.Eval(context.TODO(), `
if (redis.call('exists', KEYS[1]) == 0) then
return 0;
end;
redis.call('del', KEYS[1]);
redis.call('publish', KEYS[2], ARGV[1]);
return 1;
`, []string{m.Key, m.g.getChannelName(m.Key)}, UNLOCK_MESSAGE).Result()
if err != nil {
return 0, err
}
if b, ok := result.(int64); ok {
return b, nil
} else {
return 0, errors.Errorf("unlock result converter to bool error, value is %v", result)
}
}
func (m *Mutex) renewExpirationScheduler() {
cancel, cancelFunc := context.WithCancel(context.TODO())
m.cancelFunc = cancelFunc
go m.renewExpirationSchedulerGoroutine(cancel)
}
func (m *Mutex) renewExpirationSchedulerGoroutine(cancel context.Context) {
ticker := time.NewTicker(m.g.watchDogTimeout / 3)
defer ticker.Stop()
for {
select {
case <-ticker.C:
renew, err := m.renewExpiration()
if err != nil {
return
}
// key not exists, so return goroutine
if renew == 0 {
m.cancelExpirationRenewal()
return
}
case <-cancel.Done():
return
}
}
}
func (m *Mutex) renewExpiration() (int64, error) {
result, err := m.g.c.Eval(context.TODO(), `
if (redis.call('exists', KEYS[1]) == 1) then
redis.call('pexpire', KEYS[1], ARGV[1]);
return 1;
end;
return 0;
`, []string{m.Key}, m.g.watchDogTimeout.Milliseconds()).Result()
if err != nil {
return 0, err
}
if b, ok := result.(int64); ok {
return b, nil
} else {
return 0, errors.Errorf("try lock result converter to int64 error, value is %v", result)
}
}
func (m *Mutex) cancelExpirationRenewal() {
if m.cancelFunc != nil {
m.cancelFunc()
}
}