/
mock_lock.go
84 lines (70 loc) · 1.27 KB
/
mock_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
package lock
import (
"sync"
"time"
)
type MockLocker struct {
*sync.Mutex
locks map[string]*MockLock
}
type MockLock struct {
mutex *sync.Mutex
locked bool
}
func NewMockLocker() *MockLocker {
return &MockLocker{
Mutex: &sync.Mutex{},
locks: make(map[string]*MockLock),
}
}
func (locker *MockLocker) Acquire(path string, ttl uint64) (Lock, error) {
locker.Lock()
defer locker.Unlock()
m, ok := locker.locks[path]
if !ok {
locker.locks[path] = &MockLock{mutex: &sync.Mutex{}}
m = locker.locks[path]
}
if m.locked {
return nil, &Error{hostname: "localhost"}
} else {
m.mutex.Lock()
m.locked = true
}
if ttl > 0 {
go func() {
time.Sleep(time.Duration(ttl) * time.Second)
m.Release()
}()
}
return m, nil
}
func (locker *MockLocker) WaitAcquire(path string, ttl uint64) (Lock, error) {
var lock Lock
var err error = &Error{}
for err != nil {
lock, err = locker.Acquire(path, ttl)
if err != nil {
break
}
}
return lock, nil
}
func (locker *MockLocker) Wait(path string) error {
locker.Lock()
defer locker.Unlock()
l, ok := locker.locks[path]
if !ok {
return nil
}
if l.locked {
l.mutex.Lock()
l.mutex.Unlock()
}
return nil
}
func (lock *MockLock) Release() error {
lock.locked = false
lock.mutex.Unlock()
return nil
}