-
Notifications
You must be signed in to change notification settings - Fork 7
/
service.go
268 lines (248 loc) · 7.7 KB
/
service.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
// Copyright 2019-present Open Networking Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package lock
import (
"container/list"
lockapi "github.com/atomix/atomix-api/go/atomix/primitive/lock"
metaapi "github.com/atomix/atomix-api/go/atomix/primitive/meta"
"github.com/atomix/atomix-go-framework/pkg/atomix/errors"
"github.com/atomix/atomix-go-framework/pkg/atomix/storage/protocol/rsm"
)
func init() {
registerServiceFunc(newService)
}
func newService(context ServiceContext) Service {
return &lockService{
ServiceContext: context,
queue: list.New(),
watchers: make(map[ProposalID]Watcher),
timers: make(map[ProposalID]rsm.Timer),
}
}
// lockService is a state machine for a list primitive
type lockService struct {
ServiceContext
owner *LockRequest
queue *list.List
watchers map[ProposalID]Watcher
timers map[ProposalID]rsm.Timer
}
func (l *lockService) Backup(writer SnapshotWriter) error {
state := &LockState{
Owner: l.owner,
}
request := l.queue.Front()
for request != nil {
state.Requests = append(state.Requests, request.Value.(LockRequest))
request = request.Next()
}
return writer.WriteState(state)
}
func (l *lockService) Restore(reader SnapshotReader) error {
state, err := reader.ReadState()
if err != nil {
return err
}
l.owner = state.Owner
for _, request := range state.Requests {
l.queue.PushBack(request)
}
return nil
}
func (l *lockService) Lock(lock LockProposal) {
lockRequest := LockRequest{
ProposalID: lock.ID(),
SessionID: lock.Session().ID(),
}
if lock.Request().Timeout != nil {
expire := l.Scheduler().Time().Add(*lock.Request().Timeout)
lockRequest.Expire = &expire
}
if l.owner == nil {
// If the lock is not already owned, immediately grant the lock to the requester.
// Note that we still have to publish an event to the session. The event is guaranteed to be received
// by the client-side primitive after the LOCK response.
l.owner = &lockRequest
l.watchers[lock.ID()] = lock.Session().Watch(func(state SessionState) {
if state == SessionClosed {
l.unlock(lock.Session())
delete(l.watchers, lock.ID())
}
})
lock.Reply(&lockapi.LockResponse{
Lock: lockapi.Lock{
ObjectMeta: metaapi.ObjectMeta{
Revision: &metaapi.Revision{
Num: metaapi.RevisionNum(lock.ID()),
},
},
State: lockapi.Lock_LOCKED,
},
})
} else if lock.Request().Timeout != nil && int64(*lock.Request().Timeout) == 0 {
// If the timeout is 0, that indicates this is a tryLock request. Immediately fail the request.
lock.Fail(errors.NewTimeout("lock request timed out"))
} else if lock.Request().Timeout != nil {
// If a timeout exists, add the request to the queue and set a timer. Note that the lock request expiration
// time is based on the *state machine* time - not the system time - to ensure consistency across servers.
element := l.queue.PushBack(lockRequest)
l.timers[lock.ID()] = l.Scheduler().RunAt(*lockRequest.Expire, func() {
// When the lock request timer expires, remove the request from the queue and publish a FAILED
// event to the session. Note that this timer is guaranteed to be executed in the same thread as the
// state machine commands, so there's no need to use a lock here.
delete(l.timers, lock.ID())
l.queue.Remove(element)
lock.Fail(errors.NewTimeout("lock request timed out"))
})
l.watchers[lock.ID()] = lock.Session().Watch(func(state SessionState) {
if state == SessionClosed {
l.unlock(lock.Session())
delete(l.watchers, lock.ID())
}
})
} else {
// If the lock does not have an expiration, just add the request to the queue with no expiration.
l.queue.PushBack(lockRequest)
l.watchers[lock.ID()] = lock.Session().Watch(func(state SessionState) {
if state == SessionClosed {
l.unlock(lock.Session())
delete(l.watchers, lock.ID())
}
})
}
}
func (l *lockService) Unlock(unlock UnlockProposal) (*lockapi.UnlockResponse, error) {
if l.owner != nil {
// If the commit's session does not match the current lock holder, preserve the existing lock.
// If the current lock ID does not match the requested lock ID, preserve the existing lock.
// However, ensure the associated lock request is removed from the queue.
if unlock.Session().ID() != l.owner.SessionID {
return nil, errors.NewConflict("not the lock owner")
}
// The lock has been released. Populate the lock from the queue.
element := l.queue.Front()
if element != nil {
request := element.Value.(LockRequest)
l.queue.Remove(element)
// If the waiter has a lock timer, cancel the timer.
timer, ok := l.timers[request.ProposalID]
if ok {
timer.Cancel()
delete(l.timers, request.ProposalID)
}
lock, ok := l.Proposals().Lock().Get(request.ProposalID)
if ok {
l.owner = &request
lock.Reply(&lockapi.LockResponse{
Lock: lockapi.Lock{
ObjectMeta: metaapi.ObjectMeta{
Revision: &metaapi.Revision{
Num: metaapi.RevisionNum(lock.ID()),
},
},
State: lockapi.Lock_LOCKED,
},
})
return &lockapi.UnlockResponse{
Lock: lockapi.Lock{
ObjectMeta: metaapi.ObjectMeta{
Revision: &metaapi.Revision{
Num: metaapi.RevisionNum(lock.ID()),
},
},
State: lockapi.Lock_LOCKED,
},
}, nil
}
} else {
l.owner = nil
return &lockapi.UnlockResponse{
Lock: lockapi.Lock{
State: lockapi.Lock_UNLOCKED,
},
}, nil
}
}
return &lockapi.UnlockResponse{
Lock: lockapi.Lock{
State: lockapi.Lock_UNLOCKED,
},
}, nil
}
func (l *lockService) GetLock(get GetLockQuery) (*lockapi.GetLockResponse, error) {
if l.owner != nil {
return &lockapi.GetLockResponse{
Lock: lockapi.Lock{
ObjectMeta: metaapi.ObjectMeta{
Revision: &metaapi.Revision{
Num: metaapi.RevisionNum(l.owner.ProposalID),
},
},
State: lockapi.Lock_LOCKED,
},
}, nil
}
return &lockapi.GetLockResponse{
Lock: lockapi.Lock{
State: lockapi.Lock_UNLOCKED,
},
}, nil
}
func (l *lockService) unlock(session Session) {
// Remove all instances of the session from the queue.
element := l.queue.Front()
for element != nil {
next := element.Next()
lock := element.Value.(LockRequest)
if lock.SessionID == session.ID() {
l.queue.Remove(element)
timer, ok := l.timers[lock.ProposalID]
if ok {
timer.Cancel()
delete(l.timers, lock.ProposalID)
}
}
element = next
}
// If the removed session is the current holder of the lock, nullify the lock and attempt to grant it
// to the next waiter in the queue.
if l.owner != nil && l.owner.SessionID == session.ID() {
l.owner = nil
element := l.queue.Front()
if element != nil {
lock := element.Value.(LockRequest)
l.queue.Remove(element)
// If the waiter has a lock timer, cancel the timer.
timer, ok := l.timers[lock.ProposalID]
if ok {
timer.Cancel()
delete(l.timers, lock.ProposalID)
}
l.owner = &lock
proposal, ok := l.Proposals().Lock().Get(lock.ProposalID)
if ok {
proposal.Reply(&lockapi.LockResponse{
Lock: lockapi.Lock{
ObjectMeta: metaapi.ObjectMeta{
Revision: &metaapi.Revision{
Num: metaapi.RevisionNum(l.owner.ProposalID),
},
},
State: lockapi.Lock_LOCKED,
},
})
}
}
}
}