-
Notifications
You must be signed in to change notification settings - Fork 11
/
runtime.go
484 lines (381 loc) · 12.5 KB
/
runtime.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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// Package runtime implements the controller runtime.
package runtime
import (
"context"
"fmt"
"sync"
"github.com/siderolabs/gen/channel"
"github.com/siderolabs/gen/optional"
"go.uber.org/zap"
"github.com/cosi-project/runtime/pkg/controller"
"github.com/cosi-project/runtime/pkg/controller/runtime/internal/adapter"
"github.com/cosi-project/runtime/pkg/controller/runtime/internal/cache"
"github.com/cosi-project/runtime/pkg/controller/runtime/internal/dependency"
"github.com/cosi-project/runtime/pkg/controller/runtime/internal/qruntime"
"github.com/cosi-project/runtime/pkg/controller/runtime/internal/reduced"
"github.com/cosi-project/runtime/pkg/controller/runtime/internal/rruntime"
"github.com/cosi-project/runtime/pkg/controller/runtime/options"
"github.com/cosi-project/runtime/pkg/resource"
"github.com/cosi-project/runtime/pkg/state"
)
var _ controller.Engine = (*Runtime)(nil)
// Runtime implements controller runtime.
type Runtime struct { //nolint:govet
depDB *dependency.Database
state state.State
cache *cache.ResourceCache
logger *zap.Logger
watchCh chan []state.Event
watchErrors chan error
watchedMu sync.Mutex
watched map[watchKey]bool // value is true if the watch populates the cache
controllersMu sync.RWMutex
controllersCond *sync.Cond
controllersRunning int
controllers map[string]adapter.Adapter
runCtx context.Context //nolint:containedctx
runCtxCancel context.CancelFunc
options options.Options
}
type watchKey struct {
Namespace resource.Namespace
Type resource.Type
}
// watchBuffer provides a buffer to aggregate multiple match events.
//
// This improves efficiency of a deduplication algorithm.
const watchBuffer = 16
// NewRuntime initializes controller runtime object.
func NewRuntime(st state.State, logger *zap.Logger, opt ...options.Option) (*Runtime, error) {
runtime := &Runtime{
state: st,
logger: logger,
controllers: map[string]adapter.Adapter{},
watchCh: make(chan []state.Event, watchBuffer),
watchErrors: make(chan error, 1),
watched: map[watchKey]bool{},
options: options.DefaultOptions(),
}
for _, o := range opt {
o(&runtime.options)
}
runtime.controllersCond = sync.NewCond(&runtime.controllersMu)
var err error
runtime.depDB, err = dependency.NewDatabase()
if err != nil {
return nil, fmt.Errorf("error creating dependency database: %w", err)
}
runtime.cache = cache.NewResourceCache(runtime.options.CachedResources)
for _, cachedRead := range runtime.options.CachedResources {
// mark the cached resources as watched & cached
runtime.watched[watchKey{
Namespace: cachedRead.Namespace,
Type: cachedRead.Type,
}] = true
}
return runtime, nil
}
// RegisterController registers new controller.
func (runtime *Runtime) RegisterController(ctrl controller.Controller) error {
runtime.controllersMu.Lock()
defer runtime.controllersMu.Unlock()
name := ctrl.Name()
if _, exists := runtime.controllers[name]; exists {
return fmt.Errorf("controller %q already registered", name)
}
adapter, err := rruntime.NewAdapter(ctrl,
adapter.Options{
Logger: runtime.logger,
State: runtime.state,
Cache: runtime.cache,
DepDB: runtime.depDB,
RuntimeOptions: runtime.options,
RegisterWatch: runtime.watch,
},
)
if err != nil {
return fmt.Errorf("error initializing controller %q adapter: %w", name, err)
}
runtime.registerAdapter(name, adapter)
return nil
}
// RegisterQController registers new QController.
func (runtime *Runtime) RegisterQController(ctrl controller.QController) error {
runtime.controllersMu.Lock()
defer runtime.controllersMu.Unlock()
name := ctrl.Name()
if _, exists := runtime.controllers[name]; exists {
return fmt.Errorf("controller %q already registered", name)
}
adapter, err := qruntime.NewAdapter(
ctrl,
adapter.Options{
Logger: runtime.logger,
State: runtime.state,
Cache: runtime.cache,
DepDB: runtime.depDB,
RuntimeOptions: runtime.options,
RegisterWatch: runtime.watch,
},
)
if err != nil {
return fmt.Errorf("error initializing controller %q adapter: %w", name, err)
}
runtime.registerAdapter(name, adapter)
return nil
}
func (runtime *Runtime) registerAdapter(name string, adapter adapter.Adapter) {
runtime.controllers[name] = adapter
if runtime.runCtx != nil {
// runtime has already been started
runtime.controllersRunning++
go func() {
defer func() {
runtime.controllersMu.Lock()
defer runtime.controllersMu.Unlock()
runtime.controllersRunning--
runtime.controllersCond.Signal()
}()
adapter.Run(runtime.runCtx)
}()
}
}
// Run all the controller loops.
func (runtime *Runtime) Run(ctx context.Context) error {
if err := func() error {
runtime.controllersMu.Lock()
defer runtime.controllersMu.Unlock()
if runtime.runCtx != nil {
return fmt.Errorf("runtime has already been started")
}
runtime.runCtx, runtime.runCtxCancel = context.WithCancel(ctx)
if err := runtime.setupWatches(); err != nil {
runtime.runCtxCancel()
return err
}
go runtime.processWatched()
for _, adapter := range runtime.controllers {
runtime.controllersRunning++
go func() {
defer func() {
runtime.controllersMu.Lock()
defer runtime.controllersMu.Unlock()
runtime.controllersRunning--
runtime.controllersCond.Signal()
}()
adapter.Run(runtime.runCtx)
}()
}
return nil
}(); err != nil {
return err
}
var watchErr error
select {
case <-runtime.runCtx.Done():
case watchErr = <-runtime.watchErrors:
watchErr = fmt.Errorf("controller runtime watch error: %w", watchErr)
}
runtime.controllersMu.Lock()
runtime.runCtxCancel()
for runtime.controllersRunning > 0 {
runtime.controllersCond.Wait()
}
runtime.controllersMu.Unlock()
return watchErr
}
// GetDependencyGraph returns dependency graph between resources and controllers.
func (runtime *Runtime) GetDependencyGraph() (*controller.DependencyGraph, error) {
return runtime.depDB.Export()
}
func (runtime *Runtime) setupWatches() error {
runtime.watchedMu.Lock()
defer runtime.watchedMu.Unlock()
for key, cached := range runtime.watched {
kind := resource.NewMetadata(key.Namespace, key.Type, "", resource.Version{})
if err := runtime.state.WatchKindAggregated(runtime.runCtx, kind, runtime.watchCh, state.WithBootstrapContents(cached)); err != nil {
return err
}
}
return nil
}
func (runtime *Runtime) watch(resourceNamespace resource.Namespace, resourceType resource.Type) error {
runtime.watchedMu.Lock()
defer runtime.watchedMu.Unlock()
key := watchKey{
Namespace: resourceNamespace,
Type: resourceType,
}
if _, exists := runtime.watched[key]; exists {
return nil
}
runtime.watched[key] = false
// watch is called with controllersMu locked, so this access is synchronized
if runtime.runCtx == nil {
return nil
}
kind := resource.NewMetadata(resourceNamespace, resourceType, "", resource.Version{})
return runtime.state.WatchKindAggregated(runtime.runCtx, kind, runtime.watchCh)
}
type dedup map[reduced.Metadata]struct{}
func (d dedup) takeOne() reduced.Metadata {
for k := range d {
delete(d, k)
return k
}
panic("dedup is empty")
}
func (runtime *Runtime) processWatched() {
// Perform deduplication of events based on the reduction of the event value to the reducedMetadata.
//
// deduplication process consists of two goroutines:
// 1. the first goroutine reads events from the watch channel as fast as possible,
// reduces the event value to 'reducedMetadata' and pushes them to the map
// 2. the second goroutine consumes a map from the first goroutine, performs the work required
// to trigger updates in the dependent controller
//
// The design idea is to consume watch events as fast as possible, while delaying "heavy" work
// to the second goroutine.
//
// There is a trick being used which sends a single map back and forth between the two goroutines.
// There is no locking required, as the map is owned by a single goroutine at a single moment of time.
// Additional channel 'empty' is used to block the second goroutine when there are no events to process.
ch := make(chan dedup, 1)
empty := make(chan dedup, 1)
empty <- dedup{}
go runtime.deduplicateWatchEvents(ch, empty)
go runtime.deliverDeduplicatedEvents(ch, empty)
}
// processEvents processes a group of watch events producing deduplicated map of reducedMetadata.
//
// processEvents returns false if the watch failed and the runtime should abort.
func (runtime *Runtime) processEvents(events []state.Event, m dedup) bool {
eventLoop:
for _, e := range events {
if e.Type == state.Errored {
// watch failed, we need to abort
runtime.watchErrors <- e.Error
return false
}
// if the resource is cached, we activated a watch with BootstrapContents option, so we need some special handling:
// - before Bootstrapped event is received, we ignore events from the point of controller notification, but call Append on the cache
// - on Bootstrapped event, we notify the cache that it can start serving reads
// - after Bootstrapped event, we process events normally, and notify cache about updated/deleted resources
//
// if the resource is not cached, this section is noop
if e.Type == state.Bootstrapped {
runtime.logger.Debug("bootstrapped event received",
zap.String("namespace", e.Resource.Metadata().Namespace()),
zap.String("type", e.Resource.Metadata().Type()),
zap.Int("cache_size", runtime.cache.Len(e.Resource.Metadata().Namespace(), e.Resource.Metadata().Type())),
)
runtime.cache.MarkBootstrapped(e.Resource.Metadata().Namespace(), e.Resource.Metadata().Type())
continue eventLoop
}
cacheHandled, cacheBootstrapped := runtime.cache.IsHandledBootstrapped(e.Resource.Metadata().Namespace(), e.Resource.Metadata().Type())
if cacheHandled {
switch {
case !cacheBootstrapped:
runtime.cache.CacheAppend(e.Resource)
// if bootstrapping is not finished, we ignore those events from the point of notifying the caller
continue eventLoop
case e.Type == state.Created || e.Type == state.Updated:
runtime.cache.CachePut(e.Resource)
case e.Type == state.Destroyed:
runtime.cache.CacheRemove(e.Resource)
}
}
m[reduced.NewMetadata(e.Resource.Metadata())] = struct{}{}
}
return true
}
// deduplicateWatchEvents deduplicates events from the watch channel into the map sent to the channel ch.
func (runtime *Runtime) deduplicateWatchEvents(ch chan dedup, empty chan dedup) {
for {
var events []state.Event
// wait for an event
select {
case <-runtime.runCtx.Done():
return
case events = <-runtime.watchCh:
}
// acquire a map
var m dedup
select {
case m = <-empty:
case m = <-ch:
case <-runtime.runCtx.Done():
return
}
if !runtime.processEvents(events, m) {
return
}
// we might have not accumulated any events
if len(m) == 0 {
if !channel.SendWithContext(runtime.runCtx, empty, m) {
return
}
continue
}
// drain the watchCh by consuming all immediately available events
drainer:
for {
select {
case events = <-runtime.watchCh:
if !runtime.processEvents(events, m) {
return
}
case <-runtime.runCtx.Done():
return
default:
break drainer
}
}
// send the map to the second goroutine for processing
if !channel.SendWithContext(runtime.runCtx, ch, m) {
return
}
}
}
// deliverDeduplicatedEvents delivers events from the deduplicated channel to the controllers.
func (runtime *Runtime) deliverDeduplicatedEvents(ch chan dedup, empty chan<- dedup) {
for {
// wait for a map
var m dedup
select {
case m = <-ch:
case <-runtime.runCtx.Done():
return
}
// consume any first key of the map
k := m.takeOne()
// send the map back to the first goroutine
if len(m) > 0 {
if !channel.SendWithContext(runtime.runCtx, ch, m) {
return
}
} else {
if !channel.SendWithContext(runtime.runCtx, empty, m) {
return
}
}
// notify controllers
controllers, err := runtime.depDB.GetDependentControllers(controller.Input{
Namespace: k.Namespace,
Type: k.Typ,
ID: optional.Some(k.ID),
})
if err != nil {
runtime.logger.Error("failed to get dependent controllers", zap.Error(err))
continue
}
runtime.controllersMu.RLock()
for _, ctrl := range controllers {
runtime.controllers[ctrl].WatchTrigger(&k)
}
runtime.controllersMu.RUnlock()
}
}