-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgo-lock.go
276 lines (244 loc) · 6.46 KB
/
go-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
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
package golangUtils
import (
"context"
"crypto/sha1"
"fmt"
"log"
"net"
"strconv"
"sync"
"time"
"github.com/redis/go-redis/v9"
)
func init() {
singleConfig = new(config)
singleConfig.cancelTime = defaultCancelTime
singleConfig.expiresTime = defaultExpiresTime
singleConfig.maxOffsetTime = defaultMaxOffsetTime
singleConfig.reties = defaultReties
nodeID, err := getMachineID()
if err != nil {
panic(fmt.Sprintf("init the mutex unique nodeId false:%s", err.Error()))
}
singleConfig.nodeID = nodeID
}
const defaultCancelTime = 1 * time.Second
const defaultExpiresTime = 3 * time.Second
const defaultMaxOffsetTime = 10 * time.Millisecond
const defaultReties = 2
type Mutex struct {
// auto delay
delayDone chan struct{}
name string
config *config
ending chan error
}
type config struct {
cancelTime time.Duration
maxOffsetTime time.Duration
expiresTime time.Duration
reties int
delegate *redis.Client
nodeID string
}
type ConfigOption func(*config)
// WithCancelTime a time for redis conn need spend the max time
func WithCancelTime(cancelTime time.Duration) ConfigOption {
return func(c *config) {
c.cancelTime = cancelTime
}
}
// WithExpiresTime Duration of lock
func WithExpiresTime(expireTime time.Duration) ConfigOption {
return func(c *config) {
c.expiresTime = expireTime
}
}
// WithMaxOffsetTime be set to priority about the max gradient times for the interval of requesting lock
func WithMaxOffsetTime(maxOffsetTime time.Duration) ConfigOption {
return func(c *config) {
c.maxOffsetTime = maxOffsetTime
}
}
// WithReties be set to priority about the gradient decreases for the interval of requesting lock,After how many repetitions
func WithReties(reties int) ConfigOption {
return func(c *config) {
c.reties = reties
}
}
// WithStorageClient the must be init
func WithStorageClient(client *redis.Client) ConfigOption {
return func(c *config) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
err := client.Ping(ctx).Err()
if err != nil {
panic(fmt.Sprintf("connect the redis error:%s", err.Error()))
}
c.delegate = client
}
}
// AssemblyMutex the mutex config init
func AssemblyMutex(options ...ConfigOption) {
once.Do(func() {
for _, value := range options {
value(singleConfig)
}
})
}
// must init before use
var (
singleConfig *config
once sync.Once
)
func NewMutex(name string) *Mutex {
if singleConfig.delegate == nil {
panic("Execute the AssemblyMutex Method Must include claim WithStorageClient before initing the lock")
}
mutex := new(Mutex)
mutex.config = singleConfig
mutex.name = name
mutex.delayDone = make(chan struct{})
mutex.ending = make(chan error)
return mutex
}
func (mutex *Mutex) Lock() {
timeOffset := mutex.config.maxOffsetTime
retryTimes := 0
for {
ok := mutex.TryLock()
if ok {
//delay
go func() {
for {
select {
case <-mutex.delayDone:
return
default:
//TODO resolve the relay error should do
mutex.delay()
// if err != nil {
// log.Println(err)
// mutex.ending <- err
// return
// }
time.Sleep(mutex.config.expiresTime / 5)
}
}
}()
return
}
time.Sleep(timeOffset)
retryTimes++
if mutex.config.reties <= retryTimes {
timeOffset /= 2
retryTimes = 0
}
}
}
func (mutex *Mutex) TryLock() bool {
ok, err := mutex.acquire()
if err != nil || !ok {
return false
}
return true
}
func (mutex *Mutex) acquire() (bool, error) {
ctx, cancel := context.WithTimeout(context.Background(), mutex.config.cancelTime)
defer cancel()
cmd := mutex.config.delegate.SetNX(ctx, mutex.name, mutex.config.nodeID, mutex.config.expiresTime)
return cmd.Val(), cmd.Err()
}
// -1 resprent the delay error
const delayScript = `
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('PEXPIRE',KEYS[1],ARGV[2])
else
return -2
end
`
const delayCacheKey = "delay"
func (mutex *Mutex) delay() error {
ctx, cancel := context.WithTimeout(context.TODO(), mutex.config.cancelTime)
defer cancel()
if _, ok := cacheHash[delayCacheKey]; !ok {
cmd := mutex.config.delegate.Eval(ctx, delayScript, []string{mutex.name}, mutex.config.nodeID, strconv.FormatInt(int64(mutex.config.expiresTime.Milliseconds()), 10))
err := cmd.Err()
if err != nil {
return err
}
status, err := cmd.Int()
if err != nil {
return err
}
if status < 0 {
return fmt.Errorf("%s key delay error:%d", mutex.name, status)
}
hash := sha1.Sum([]byte(delayScript))
cacheHash[delayCacheKey] = fmt.Sprintf("%x", hash[:])
}
cmd := mutex.config.delegate.EvalSha(ctx, cacheHash[delayCacheKey], []string{mutex.name}, mutex.config.nodeID, strconv.FormatInt(int64(mutex.config.expiresTime.Milliseconds()), 10))
err := cmd.Err()
if err != nil {
return err
}
status, err := cmd.Int()
if err != nil {
return err
}
if status < 0 {
return fmt.Errorf("%s key delay error:%d", mutex.name, status)
}
return err
}
func (mutex *Mutex) UnLock() {
if len(mutex.delayDone) > 0 {
log.Println("delay error for mutex")
return
}
mutex.delayDone <- struct{}{}
mutex.release()
}
const releaseScript = `
if redis.call('GET',KEYS[1])==ARGV[1] then
return redis.call('DEL',KEYS[1])
end
`
var cacheHash = make(map[string]string)
const releaseCacheKey = "release"
// const deleteCacheKey = "delete"
// if the release failed , the system cant loss any resource
func (mutex *Mutex) release() {
ctx, cancel := context.WithTimeout(context.TODO(), mutex.config.cancelTime)
defer cancel()
if _, ok := cacheHash[releaseCacheKey]; !ok {
mutex.config.delegate.Eval(ctx, releaseScript, []string{mutex.name}, mutex.config.nodeID)
hash := sha1.Sum([]byte(releaseScript))
cacheHash[releaseCacheKey] = fmt.Sprintf("%x", hash[:])
}
mutex.config.delegate.EvalSha(ctx, cacheHash[releaseCacheKey], []string{mutex.name}, mutex.config.nodeID)
}
func getMachineID() (string, error) {
interfaces, err := net.Interfaces()
if err != nil {
return "", err
}
for _, iface := range interfaces {
if iface.Flags&net.FlagUp != 0 && iface.Flags&net.FlagLoopback == 0 {
addrs, err := iface.Addrs()
if err != nil {
return "", err
}
// 查找第一个有效的MAC地址
for _, addr := range addrs {
if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
mac := iface.HardwareAddr.String()
if mac != "" {
return mac, nil
}
}
}
}
}
return "", fmt.Errorf("无法获取机器的唯一标识")
}