-
Notifications
You must be signed in to change notification settings - Fork 0
/
control.go
452 lines (398 loc) · 11.2 KB
/
control.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
package rsmap
import (
"context"
"errors"
"sync"
"time"
"github.com/daichitakahashi/oncewait"
"golang.org/x/sync/errgroup"
"github.com/daichitakahashi/rsmap/internal/ctl"
logsv1 "github.com/daichitakahashi/rsmap/internal/proto/logs/v1"
resource_mapv1 "github.com/daichitakahashi/rsmap/internal/proto/resource_map/v1"
"github.com/daichitakahashi/rsmap/internal/rendezvous"
"github.com/daichitakahashi/rsmap/logs"
)
// TODO
// * timeout for init and acquisition
var errClosing = errors.New("closing")
type initController struct {
_store logs.ResourceRecordStore[logsv1.InitRecord]
_resources sync.Map
_closing <-chan struct{}
}
func loadInitController(store logs.ResourceRecordStore[logsv1.InitRecord], closing <-chan struct{}) (*initController, error) {
c := &initController{
_store: store,
_closing: closing,
}
err := c._store.ForEach(func(name string, obj *logsv1.InitRecord) error {
if len(obj.Logs) == 0 {
return nil // Impossible path.
}
// Get last init status and operator.
last := obj.Logs[len(obj.Logs)-1]
if last.Event == logsv1.InitEvent_INIT_EVENT_FAILED {
return nil // Former try is failed and anyone haven't started next try yet.
}
completed := last.Event == logsv1.InitEvent_INIT_EVENT_COMPLETED
initCtl := ctl.NewInitCtl(completed)
if !completed {
<-initCtl.TryInit(
context.Background(),
logs.CallerContext(last.Context).String(),
)
}
c._resources.Store(name, initCtl)
return nil
})
if err != nil {
return nil, err
}
return c, nil
}
func (c *initController) tryInit(ctx context.Context, resourceName string, operator logs.CallerContext) (bool, error) {
v, _ := c._resources.LoadOrStore(resourceName, ctl.NewInitCtl(false))
initCtl := v.(*ctl.InitCtl)
var result ctl.TryInitResult
select {
case <-c._closing:
return false, errClosing
case result = <-initCtl.TryInit(ctx, operator.String()):
if result.Err != nil {
return false, result.Err
}
if !result.Try {
return false, nil
}
}
if result.Initiated {
// Update data on key value store.
err := c._store.Put([]string{resourceName}, func(_ string, r *logsv1.InitRecord, _ bool) {
r.Logs = append(r.Logs, &logsv1.InitLog{
Event: logsv1.InitEvent_INIT_EVENT_STARTED,
Context: operator,
Timestamp: time.Now().UnixNano(),
})
})
if err != nil {
return false, err
}
}
return true, nil
}
func (c *initController) complete(resourceName string, operator logs.CallerContext) error {
select {
case <-c._closing:
return errClosing
default:
}
v, found := c._resources.Load(resourceName)
if !found {
return errors.New("resource not found")
}
ctl := v.(*ctl.InitCtl)
err := ctl.Complete(operator.String())
if err != nil {
return err
}
return c._store.Put([]string{resourceName}, func(_ string, r *logsv1.InitRecord, _ bool) {
r.Logs = append(r.Logs, &logsv1.InitLog{
Event: logsv1.InitEvent_INIT_EVENT_COMPLETED,
Context: operator,
Timestamp: time.Now().UnixNano(),
})
})
}
func (c *initController) fail(resourceName string, operator logs.CallerContext) error {
select {
case <-c._closing:
return errClosing
default:
}
v, found := c._resources.Load(resourceName)
if !found {
return errors.New("resource not found")
}
ctl := v.(*ctl.InitCtl)
err := ctl.Fail(operator.String())
if err != nil {
return err
}
return c._store.Put([]string{resourceName}, func(_ string, r *logsv1.InitRecord, _ bool) {
r.Logs = append(r.Logs, &logsv1.InitLog{
Event: logsv1.InitEvent_INIT_EVENT_FAILED,
Context: operator,
Timestamp: time.Now().UnixNano(),
})
})
}
type (
// Control acquisition status and persistence.
acquireController struct {
_kv logs.ResourceRecordStore[logsv1.AcquisitionRecord]
_resources sync.Map
_closing <-chan struct{}
_multiMu sync.Mutex
}
resource struct {
once *oncewait.OnceWaiter
queue rendezvous.LimitedTermQueue
ctl *ctl.AcquisitionCtl
}
)
func loadAcquireController(store logs.ResourceRecordStore[logsv1.AcquisitionRecord], acquiringQueueTimeout time.Duration, closing <-chan struct{}) (*acquireController, error) {
c := &acquireController{
_kv: store,
_closing: closing,
}
err := store.ForEach(func(name string, obj *logsv1.AcquisitionRecord) error {
acquired := map[string]int64{}
b := rendezvous.NewBuilder()
// Replay stored acquisitions of the resource.
for _, log := range obj.Logs {
operator := logs.CallerContext(log.Context).String()
switch log.Event {
case logsv1.AcquisitionEvent_ACQUISITION_EVENT_ACQUIRING:
// Queue as "acquiring".
b.Add(operator)
case logsv1.AcquisitionEvent_ACQUISITION_EVENT_ACQUIRED:
// Consecutive acquisition is not recorded.
// So, we can skip the check of existing value.
//
// See: `(*ctl.AcquisitionCtl).Acquire()`
acquired[operator] = log.N
// Remove already acquired operation from queue.
b.Remove(operator)
case logsv1.AcquisitionEvent_ACQUISITION_EVENT_RELEASED:
// We assume that acquisition log is already processed.
delete(acquired, operator)
}
}
// Set replayed acquireCtl.
c._resources.Store(
name,
&resource{
queue: b.Start(acquiringQueueTimeout),
ctl: ctl.NewAcquisitionCtl(obj.Max, acquired),
},
)
return nil
})
if err != nil {
return nil, err
}
return c, nil
}
var emptyQueue = rendezvous.NewBuilder().Start(0)
func (r *resource) init(max int64) *resource {
if r.once != nil {
r.once.Do(func() {
r.queue = emptyQueue
r.ctl = ctl.NewAcquisitionCtl(max, map[string]int64{})
})
}
return r
}
func (r *resource) acquire(ctx context.Context, operator string, exclusive bool) (<-chan ctl.AcquisitionResult, bool) {
var (
ch <-chan ctl.AcquisitionResult
acquiring bool
)
// Wait dequeuing, because replayed "acquiring" operators take precedence.
r.queue.Dequeue(operator, func(bool) {
ch, acquiring = r.ctl.Acquire(ctx, operator, exclusive)
})
return ch, acquiring
}
func (c *acquireController) acquire(ctx context.Context, resourceName string, operator logs.CallerContext, max int64, exclusive bool) error {
select {
case <-c._closing:
return errClosing
default:
}
v, _ := c._resources.LoadOrStore(resourceName, &resource{
once: oncewait.New(),
})
r := v.(*resource).init(max)
// Start acquisition.
acCh, acquiring := r.acquire(ctx, operator.String(), exclusive)
// Due to trial of consecutive acquisition, not acquired.
if !acquiring {
return nil
}
// Append log "acquiring".
err := c._kv.Put([]string{resourceName}, func(_ string, r *logsv1.AcquisitionRecord, update bool) {
// Initial acquisition.
if !update {
r.Max = max
}
r.Logs = append(r.Logs, &logsv1.AcquisitionLog{
Event: logsv1.AcquisitionEvent_ACQUISITION_EVENT_ACQUIRING,
Context: operator,
Timestamp: time.Now().UnixNano(),
})
})
if err != nil {
return err
}
var result ctl.AcquisitionResult
select {
case <-c._closing:
return errClosing
case result = <-acCh:
if result.Err != nil {
return result.Err
}
}
return c._kv.Put([]string{resourceName}, func(_ string, r *logsv1.AcquisitionRecord, update bool) {
r.Logs = append(r.Logs, &logsv1.AcquisitionLog{
Event: logsv1.AcquisitionEvent_ACQUISITION_EVENT_ACQUIRED,
N: result.Acquired,
Context: operator,
Timestamp: time.Now().UnixNano(),
})
})
}
func (c *acquireController) acquireMulti(ctx context.Context, resources []*resource_mapv1.AcquireMultiEntry) error {
select {
case <-c._closing:
return errClosing
default:
}
type acquiringEntry struct {
entry *resource_mapv1.AcquireMultiEntry
acquired <-chan ctl.AcquisitionResult
}
identifiers := make([]string, 0, len(resources))
entries := make(map[string]acquiringEntry, len(resources))
// Lock for multiple locking.
c._multiMu.Lock()
for _, entry := range resources {
v, _ := c._resources.LoadOrStore(entry.ResourceName, &resource{
once: oncewait.New(),
})
r := v.(*resource).init(entry.MaxParallelism)
// Start acquisition.
acCh, acquiring := r.acquire(ctx, logs.CallerContext(entry.Context).String(), entry.Exclusive)
// Due to trial of consecutive acquisition, not acquired.
if acquiring {
identifiers = append(identifiers, entry.ResourceName)
entries[entry.ResourceName] = acquiringEntry{
entry: entry,
acquired: acCh,
}
}
}
c._multiMu.Unlock()
if len(identifiers) == 0 {
return nil
}
// Append log "acquiring".
ts := time.Now().UnixNano()
err := c._kv.Put(identifiers, func(identifier string, r *logsv1.AcquisitionRecord, update bool) {
e := entries[identifier]
// Initial acquisition.
if !update {
r.Max = e.entry.MaxParallelism
}
r.Logs = append(r.Logs, &logsv1.AcquisitionLog{
Event: logsv1.AcquisitionEvent_ACQUISITION_EVENT_ACQUIRING,
Context: e.entry.Context,
Timestamp: ts,
})
})
if err != nil {
return err
}
eg, _ := errgroup.WithContext(ctx)
for _, entry := range entries {
e := entry
eg.Go(func() error {
var result ctl.AcquisitionResult
select {
case <-c._closing:
return errClosing
case result = <-e.acquired:
if result.Err != nil {
return err
}
}
return c._kv.Put([]string{e.entry.ResourceName}, func(identifier string, r *logsv1.AcquisitionRecord, update bool) {
r.Logs = append(r.Logs, &logsv1.AcquisitionLog{
Event: logsv1.AcquisitionEvent_ACQUISITION_EVENT_ACQUIRED,
N: result.Acquired,
Context: e.entry.Context,
Timestamp: time.Now().UnixNano(),
})
})
})
}
return eg.Wait()
}
func (c *acquireController) release(resourceName string, operator logs.CallerContext) error {
select {
case <-c._closing:
return errClosing
default:
}
v, found := c._resources.Load(resourceName)
if !found {
// If the resource not found, return without error.
return nil
}
op := operator.String()
r := v.(*resource)
if !r.ctl.Acquired(op) {
// If not acquired, return without error.
return nil
}
err := c._kv.Put([]string{resourceName}, func(_ string, r *logsv1.AcquisitionRecord, _ bool) {
r.Logs = append(r.Logs, &logsv1.AcquisitionLog{
Event: logsv1.AcquisitionEvent_ACQUISITION_EVENT_RELEASED,
N: 0,
Context: operator,
Timestamp: time.Now().UnixNano(),
})
})
if err != nil {
return err
}
r.ctl.Release(op)
return nil
}
func (c *acquireController) releaseMulti(resources []*resource_mapv1.ReleaseMultiEntry) error {
select {
case <-c._closing:
return errClosing
default:
}
entries := make(map[string]*resource_mapv1.ReleaseMultiEntry, len(resources))
identifiers := make([]string, 0, len(resources))
for _, entry := range resources {
v, found := c._resources.Load(entry.ResourceName)
if !found {
// If the resource not found, skip it.
continue
}
r := v.(*resource)
op := logs.CallerContext(entry.Context).String()
if !r.ctl.Acquired(op) {
// If not acquired, skip it.
continue
}
entries[entry.ResourceName] = entry
identifiers = append(identifiers, entry.ResourceName)
// Release after log write.
defer r.ctl.Release(op)
}
ts := time.Now().UnixNano()
return c._kv.Put(identifiers, func(identifier string, r *logsv1.AcquisitionRecord, _ bool) {
e := entries[identifier]
r.Logs = append(r.Logs, &logsv1.AcquisitionLog{
Event: logsv1.AcquisitionEvent_ACQUISITION_EVENT_RELEASED,
N: 0,
Context: e.Context,
Timestamp: ts,
})
})
}