-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode_rpc.go
147 lines (111 loc) · 2.34 KB
/
node_rpc.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 dlm
import (
"errors"
"log"
"time"
"github.com/yaitoo/sqle"
)
func (n *Node) NewLock(req LockRequest, t *Lease) error {
n.mu.Lock()
defer n.mu.Unlock()
_, ok := n.frozen[req.Topic]
if ok {
return ErrFrozenTopic
}
lease, err := n.getLease(req.Topic, req.Key)
if err == nil { // exits a lease
if lease.Lessee != req.ID && lease.IsLive() { // someone else's lease is still live
return ErrLeaseExists
}
} else {
if !errors.Is(err, ErrNoLease) {
return err
}
}
// assign/reassign lease to current request
lease = Lease{
Lessee: req.ID,
Topic: req.Topic,
Key: req.Key,
TTL: sqle.Duration(req.TTL),
Since: time.Now().Unix(),
}
if errors.Is(err, ErrNoLease) {
err = n.createLease(lease)
} else {
err = n.updateLease(lease)
}
if err != nil {
return err
}
if t != nil {
*t = lease
}
log.Printf("new: topic=%s key=%s lessee=%s ttl=%s\n", lease.Topic, lease.Key, lease.Lessee, lease.TTL.Duration())
return nil
}
func (n *Node) RenewLock(req LockRequest, t *Lease) error {
n.mu.Lock()
defer n.mu.Unlock()
_, ok := n.frozen[req.Topic]
if ok {
return ErrFrozenTopic
}
lease, err := n.getLease(req.Topic, req.Key)
if err != nil {
return err
}
if lease.Lessee != req.ID {
return ErrNotYourLease
}
if !lease.IsLive() {
return ErrExpiredLease
}
lease.Since = time.Now().Unix()
lease.TTL = sqle.Duration(req.TTL)
err = n.updateLease(lease)
if err != nil {
return err
}
if t != nil {
*t = lease
}
return nil
}
func (n *Node) ReleaseLock(req LockRequest, ok *bool) error {
n.mu.Lock()
defer n.mu.Unlock()
lease, err := n.getLease(req.Topic, req.Key)
if err != nil {
if errors.Is(err, ErrNoLease) {
return nil
}
return err
}
if lease.Lessee != req.ID {
return ErrNotYourLease
}
err = n.deleteLease(req.Topic, req.Key)
if err != nil {
return err
}
*ok = true
log.Printf("release: topic=%s key=%s lessee=%s ttl=%s\n", lease.Topic, lease.Key, lease.Lessee, lease.TTL.Duration())
return nil
}
func (n *Node) Freeze(topic string, ok *bool) error {
n.mu.Lock()
defer n.mu.Unlock()
n.frozen[topic] = struct{}{}
*ok = true
log.Printf("freeze: topic=%s", topic)
return nil
}
func (n *Node) Reset(topic string, ok *bool) error {
n.mu.Lock()
defer n.mu.Unlock()
delete(n.frozen, topic)
*ok = true
log.Printf("reset: topic=%s", topic)
return nil
}