-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
semaphore.go
320 lines (279 loc) · 9.38 KB
/
semaphore.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
/*
Copyright 2020 Gravitational, Inc.
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 types
import (
"context"
"fmt"
"time"
"github.com/gravitational/teleport/api/v7/constants"
"github.com/gravitational/trace"
)
// SemaphoreKindConnection is the semaphore kind used by
// the Concurrent Session Control feature to limit concurrent
// connections (corresponds to the `max_connections`
// role option).
const SemaphoreKindConnection = "connection"
// Semaphore represents distributed semaphore concept
type Semaphore interface {
// Resource contains common resource values
Resource
// Contains checks if lease is member of this semaphore.
Contains(lease SemaphoreLease) bool
// Acquire attempts to acquire a lease with this semaphore.
Acquire(leaseID string, params AcquireSemaphoreRequest) (*SemaphoreLease, error)
// KeepAlive attempts to update the expiry of an existent lease.
KeepAlive(lease SemaphoreLease) error
// Cancel attempts to cancel an existent lease.
Cancel(lease SemaphoreLease) error
// LeaseRefs grants access to the underlying list
// of lease references.
LeaseRefs() []SemaphoreLeaseRef
// RemoveExpiredLeases removes expired leases
RemoveExpiredLeases(now time.Time)
}
// ConfigureSemaphore configures an empty semaphore resource matching
// these acquire parameters.
func (s *AcquireSemaphoreRequest) ConfigureSemaphore() (Semaphore, error) {
sem := SemaphoreV3{
SubKind: s.SemaphoreKind,
Metadata: Metadata{
Name: s.SemaphoreName,
},
}
sem.SetExpiry(s.Expires)
if err := sem.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
return &sem, nil
}
// Check verifies that all required parameters have been supplied.
func (s *AcquireSemaphoreRequest) Check() error {
if s.SemaphoreKind == "" {
return trace.BadParameter("missing parameter SemaphoreKind")
}
if s.SemaphoreName == "" {
return trace.BadParameter("missing parameter SemaphoreName")
}
if s.MaxLeases == 0 {
return trace.BadParameter("missing parameter MaxLeases")
}
if s.Expires.IsZero() {
return trace.BadParameter("missing parameter Expires")
}
return nil
}
// CheckAndSetDefaults checks and sets default values
func (l *SemaphoreLease) CheckAndSetDefaults() error {
if l.SemaphoreKind == "" {
return trace.BadParameter("missing parameter SemaphoreKind")
}
if l.SemaphoreName == "" {
return trace.BadParameter("missing parameter SemaphoreName")
}
if l.LeaseID == "" {
return trace.BadParameter("missing parameter LeaseID")
}
if l.Expires.IsZero() {
return trace.BadParameter("missing lease expiry time")
}
return nil
}
// Contains checks if lease is member of this semaphore.
func (c *SemaphoreV3) Contains(lease SemaphoreLease) bool {
if lease.SemaphoreKind != c.GetSubKind() || lease.SemaphoreName != c.GetName() {
return false
}
for _, ref := range c.Spec.Leases {
if ref.LeaseID == lease.LeaseID {
return true
}
}
return false
}
// Acquire attempts to acquire a lease with this semaphore.
func (c *SemaphoreV3) Acquire(leaseID string, params AcquireSemaphoreRequest) (*SemaphoreLease, error) {
if params.SemaphoreKind != c.GetSubKind() || params.SemaphoreName != c.GetName() {
return nil, trace.BadParameter("cannot acquire, params do not match")
}
if c.leaseCount() >= params.MaxLeases {
return nil, trace.LimitExceeded("cannot acquire semaphore %s/%s (%s)",
c.GetSubKind(),
c.GetName(),
constants.MaxLeases,
)
}
for _, ref := range c.Spec.Leases {
if ref.LeaseID == leaseID {
return nil, trace.AlreadyExists("semaphore lease already exists: %q", leaseID)
}
}
if params.Expires.After(c.Expiry()) {
c.SetExpiry(params.Expires)
}
c.Spec.Leases = append(c.Spec.Leases, SemaphoreLeaseRef{
LeaseID: leaseID,
Expires: params.Expires,
Holder: params.Holder,
})
return &SemaphoreLease{
SemaphoreKind: params.SemaphoreKind,
SemaphoreName: params.SemaphoreName,
LeaseID: leaseID,
Expires: params.Expires,
}, nil
}
// KeepAlive attempts to update the expiry of an existent lease.
func (c *SemaphoreV3) KeepAlive(lease SemaphoreLease) error {
if lease.SemaphoreKind != c.GetSubKind() || lease.SemaphoreName != c.GetName() {
return trace.BadParameter("cannot keepalive, lease does not match")
}
for i := range c.Spec.Leases {
if c.Spec.Leases[i].LeaseID == lease.LeaseID {
c.Spec.Leases[i].Expires = lease.Expires
if lease.Expires.After(c.Expiry()) {
c.SetExpiry(lease.Expires)
}
return nil
}
}
return trace.NotFound("cannot keepalive, lease not found: %q", lease.LeaseID)
}
// Cancel attempts to cancel an existent lease.
func (c *SemaphoreV3) Cancel(lease SemaphoreLease) error {
if lease.SemaphoreKind != c.GetSubKind() || lease.SemaphoreName != c.GetName() {
return trace.BadParameter("cannot cancel, lease does not match")
}
for i, ref := range c.Spec.Leases {
if ref.LeaseID == lease.LeaseID {
c.Spec.Leases = append(c.Spec.Leases[:i], c.Spec.Leases[i+1:]...)
return nil
}
}
return trace.NotFound("cannot cancel, lease not found: %q", lease.LeaseID)
}
// RemoveExpiredLeases removes expired leases
func (c *SemaphoreV3) RemoveExpiredLeases(now time.Time) {
// See https://github.com/golang/go/wiki/SliceTricks#filtering-without-allocating
filtered := c.Spec.Leases[:0]
for _, lease := range c.Spec.Leases {
if lease.Expires.After(now) {
filtered = append(filtered, lease)
}
}
c.Spec.Leases = filtered
}
// leaseCount returns the number of active leases
func (c *SemaphoreV3) leaseCount() int64 {
return int64(len(c.Spec.Leases))
}
// LeaseRefs grants access to the underlying list
// of lease references
func (c *SemaphoreV3) LeaseRefs() []SemaphoreLeaseRef {
return c.Spec.Leases
}
// GetVersion returns resource version
func (c *SemaphoreV3) GetVersion() string {
return c.Version
}
// GetSubKind returns resource subkind
func (c *SemaphoreV3) GetSubKind() string {
return c.SubKind
}
// SetSubKind sets resource subkind
func (c *SemaphoreV3) SetSubKind(sk string) {
c.SubKind = sk
}
// GetKind returns resource kind
func (c *SemaphoreV3) GetKind() string {
return c.Kind
}
// GetResourceID returns resource ID
func (c *SemaphoreV3) GetResourceID() int64 {
return c.Metadata.ID
}
// SetResourceID sets resource ID
func (c *SemaphoreV3) SetResourceID(id int64) {
c.Metadata.ID = id
}
// GetName returns the name of the cluster.
func (c *SemaphoreV3) GetName() string {
return c.Metadata.Name
}
// SetName sets the name of the cluster.
func (c *SemaphoreV3) SetName(e string) {
c.Metadata.Name = e
}
// Expiry returns object expiry setting
func (c *SemaphoreV3) Expiry() time.Time {
return c.Metadata.Expiry()
}
// SetExpiry sets expiry time for the object
func (c *SemaphoreV3) SetExpiry(expires time.Time) {
c.Metadata.SetExpiry(expires)
}
// GetMetadata returns object metadata
func (c *SemaphoreV3) GetMetadata() Metadata {
return c.Metadata
}
// String represents a human readable version of the semaphore.
func (c *SemaphoreV3) String() string {
return fmt.Sprintf("Semaphore(kind=%v, name=%v, leases=%v)",
c.SubKind, c.Metadata.Name, c.leaseCount())
}
// setStaticFields sets static resource header and metadata fields.
func (c *SemaphoreV3) setStaticFields() {
c.Kind = KindSemaphore
c.Version = V3
}
// CheckAndSetDefaults checks validity of all parameters and sets defaults.
func (c *SemaphoreV3) CheckAndSetDefaults() error {
c.setStaticFields()
if err := c.Metadata.CheckAndSetDefaults(); err != nil {
return trace.Wrap(err)
}
// While theoretically there are scenarios with non-expiring semaphores
// however the flow don't need them right now, and they add a lot of edge
// cases, so the code does not support them.
if c.Expiry().IsZero() {
return trace.BadParameter("set semaphore expiry time")
}
if c.SubKind == "" {
return trace.BadParameter("supply semaphore SubKind parameter")
}
return nil
}
// Semaphores provides ability to control
// how many shared resources of some kind are acquired at the same time,
// used to implement concurrent sessions control in a distributed environment
type Semaphores interface {
// AcquireSemaphore acquires lease with requested resources from semaphore
AcquireSemaphore(ctx context.Context, params AcquireSemaphoreRequest) (*SemaphoreLease, error)
// KeepAliveSemaphoreLease updates semaphore lease
KeepAliveSemaphoreLease(ctx context.Context, lease SemaphoreLease) error
// CancelSemaphoreLease cancels semaphore lease early
CancelSemaphoreLease(ctx context.Context, lease SemaphoreLease) error
// GetSemaphores returns a list of semaphores matching supplied filter.
GetSemaphores(ctx context.Context, filter SemaphoreFilter) ([]Semaphore, error)
// DeleteSemaphore deletes a semaphore matching supplied filter.
DeleteSemaphore(ctx context.Context, filter SemaphoreFilter) error
}
// Match checks if the supplied semaphore matches this filter.
func (f *SemaphoreFilter) Match(sem Semaphore) bool {
if f.SemaphoreKind != "" && f.SemaphoreKind != sem.GetSubKind() {
return false
}
if f.SemaphoreName != "" && f.SemaphoreName != sem.GetName() {
return false
}
return true
}