-
Notifications
You must be signed in to change notification settings - Fork 23
/
quota-scheduler.go
575 lines (513 loc) · 17.2 KB
/
quota-scheduler.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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
package quotascheduler
import (
"context"
"path"
"sync"
"time"
"github.com/jonboulle/clockwork"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/fx"
"go.uber.org/multierr"
"google.golang.org/protobuf/proto"
flowcontrolv1 "github.com/fluxninja/aperture/api/v2/gen/proto/go/aperture/flowcontrol/check/v1"
policylangv1 "github.com/fluxninja/aperture/api/v2/gen/proto/go/aperture/policy/language/v1"
policysyncv1 "github.com/fluxninja/aperture/api/v2/gen/proto/go/aperture/policy/sync/v1"
agentinfo "github.com/fluxninja/aperture/v2/pkg/agent-info"
"github.com/fluxninja/aperture/v2/pkg/config"
distcache "github.com/fluxninja/aperture/v2/pkg/dist-cache"
ratelimiter "github.com/fluxninja/aperture/v2/pkg/dmap-funcs/rate-limiter"
globaltokenbucket "github.com/fluxninja/aperture/v2/pkg/dmap-funcs/rate-limiter/global-token-bucket"
lazysync "github.com/fluxninja/aperture/v2/pkg/dmap-funcs/rate-limiter/lazy-sync"
etcdclient "github.com/fluxninja/aperture/v2/pkg/etcd/client"
etcdwatcher "github.com/fluxninja/aperture/v2/pkg/etcd/watcher"
"github.com/fluxninja/aperture/v2/pkg/jobs"
"github.com/fluxninja/aperture/v2/pkg/labels"
"github.com/fluxninja/aperture/v2/pkg/labelstatus"
"github.com/fluxninja/aperture/v2/pkg/log"
"github.com/fluxninja/aperture/v2/pkg/metrics"
"github.com/fluxninja/aperture/v2/pkg/notifiers"
workloadscheduler "github.com/fluxninja/aperture/v2/pkg/policies/flowcontrol/actuators/workload-scheduler"
"github.com/fluxninja/aperture/v2/pkg/policies/flowcontrol/iface"
"github.com/fluxninja/aperture/v2/pkg/policies/paths"
"github.com/fluxninja/aperture/v2/pkg/scheduler"
"github.com/fluxninja/aperture/v2/pkg/status"
)
const quotaSchedulerStatusRoot = "quota_scheduler"
var fxTag = config.NameTag(quotaSchedulerStatusRoot)
func quotaSchedulerModule() fx.Option {
return fx.Options(
fx.Provide(
fx.Annotate(
provideQuotaSchedulerWatchers,
fx.ResultTags(fxTag),
),
),
fx.Invoke(
fx.Annotate(
setupQuotaSchedulerFactory,
fx.ParamTags(fxTag),
),
),
)
}
func provideQuotaSchedulerWatchers(
etcdClient *etcdclient.Client,
ai *agentinfo.AgentInfo,
) (notifiers.Watcher, error) {
agentGroupName := ai.GetAgentGroup()
etcdPath := path.Join(paths.QuotaSchedulerConfigPath,
paths.AgentGroupPrefix(agentGroupName))
watcher, err := etcdwatcher.NewWatcher(etcdClient, etcdPath)
if err != nil {
return nil, err
}
return watcher, nil
}
type quotaSchedulerFactory struct {
engineAPI iface.Engine
registry status.Registry
decisionsWatcher notifiers.Watcher
distCache *distcache.DistCache
auditJobGroup *jobs.JobGroup
rateLimiterJobGroup *jobs.JobGroup
wsFactory *workloadscheduler.Factory
agentGroupName string
labelStatusJobGroup *jobs.JobGroup
labelStatusFactory *labelstatus.LabelStatusFactory
}
// main fx app.
func setupQuotaSchedulerFactory(
watcher notifiers.Watcher,
lifecycle fx.Lifecycle,
e iface.Engine,
distCache *distcache.DistCache,
statusRegistry status.Registry,
prometheusRegistry *prometheus.Registry,
etcdClient *etcdclient.Client,
ai *agentinfo.AgentInfo,
wsFactory *workloadscheduler.Factory,
labelStatusFactory *labelstatus.LabelStatusFactory,
) error {
agentGroupName := ai.GetAgentGroup()
etcdPath := path.Join(paths.QuotaSchedulerDecisionsPath)
decisionsWatcher, err := etcdwatcher.NewWatcher(etcdClient, etcdPath)
if err != nil {
return err
}
reg := statusRegistry.Child("component", quotaSchedulerStatusRoot)
logger := reg.GetLogger()
auditJobGroup, err := jobs.NewJobGroup(reg.Child("sync", "audit_jobs"), jobs.JobGroupConfig{}, nil)
if err != nil {
logger.Error().Err(err).Msg("Failed to create audit job group")
return err
}
rateLimiterJobGroup, err := jobs.NewJobGroup(reg.Child("sync", "rate_limiter_audit_jobs"), jobs.JobGroupConfig{}, nil)
if err != nil {
logger.Error().Err(err).Msg("Failed to create rate limiter audit job group")
return err
}
labelStatusJobGroup, err := jobs.NewJobGroup(reg.Child("label_status", "load_scheduler"), jobs.JobGroupConfig{}, nil)
if err != nil {
logger.Error().Err(err).Msg("Failed to create labels status job group")
return err
}
quotaSchedulerFactory := "aSchedulerFactory{
engineAPI: e,
distCache: distCache,
auditJobGroup: auditJobGroup,
rateLimiterJobGroup: rateLimiterJobGroup,
decisionsWatcher: decisionsWatcher,
agentGroupName: agentGroupName,
registry: reg,
wsFactory: wsFactory,
labelStatusJobGroup: labelStatusJobGroup,
labelStatusFactory: labelStatusFactory,
}
fxDriver, err := notifiers.NewFxDriver(reg, prometheusRegistry,
config.NewProtobufUnmarshaller,
[]notifiers.FxOptionsFunc{quotaSchedulerFactory.newQuotaSchedulerOptions})
if err != nil {
return err
}
lifecycle.Append(fx.Hook{
OnStart: func(context.Context) error {
err = auditJobGroup.Start()
if err != nil {
return err
}
err = rateLimiterJobGroup.Start()
if err != nil {
return err
}
err = labelStatusJobGroup.Start()
if err != nil {
return err
}
err = decisionsWatcher.Start()
if err != nil {
return err
}
return nil
},
OnStop: func(context.Context) error {
var err, merr error
err = decisionsWatcher.Stop()
if err != nil {
merr = multierr.Append(merr, err)
}
err = labelStatusJobGroup.Stop()
if err != nil {
merr = multierr.Append(merr, err)
}
err = rateLimiterJobGroup.Stop()
if err != nil {
merr = multierr.Append(merr, err)
}
err = auditJobGroup.Stop()
if err != nil {
merr = multierr.Append(merr, err)
}
reg.Detach()
return merr
},
})
notifiers.WatcherLifecycle(lifecycle, watcher, []notifiers.PrefixNotifier{fxDriver})
return nil
}
// per component fx app.
func (qsFactory *quotaSchedulerFactory) newQuotaSchedulerOptions(
key notifiers.Key,
unmarshaller config.Unmarshaller,
reg status.Registry,
) (fx.Option, error) {
logger := qsFactory.registry.GetLogger()
wrapperMessage := &policysyncv1.QuotaSchedulerWrapper{}
err := unmarshaller.Unmarshal(wrapperMessage)
if err != nil || wrapperMessage.QuotaScheduler == nil {
reg.SetStatus(status.NewStatus(nil, err), nil)
logger.Warn().Err(err).Msg("Failed to unmarshal quota scheduler config")
return fx.Options(), err
}
qsProto := wrapperMessage.QuotaScheduler
qsProto.Scheduler, err = workloadscheduler.SanitizeSchedulerProto(qsProto.Scheduler)
if err != nil {
logger.Error().Err(err).Msg("Failed to sanitize scheduler proto")
return fx.Options(), err
}
qs := "aScheduler{
Component: wrapperMessage.GetCommonAttributes(),
proto: qsProto,
qsFactory: qsFactory,
registry: reg,
clock: clockwork.NewRealClock(),
labelStatusJobGroup: qsFactory.labelStatusJobGroup,
}
qs.name = iface.ComponentKey(qs)
qs.tokensLabelKeyStatus = qsFactory.labelStatusFactory.New("tokens_label_key", qs.GetPolicyName(), qs.GetComponentId())
qs.priorityLabelKeyStatus = qsFactory.labelStatusFactory.New("priority_label_key", qs.GetPolicyName(), qs.GetComponentId())
qs.workloadLabelKeyStatus = qsFactory.labelStatusFactory.New("workload_label_key", qs.GetPolicyName(), qs.GetComponentId())
qs.fairnessLabelKeyStatus = qsFactory.labelStatusFactory.New("fairness_label_key", qs.GetPolicyName(), qs.GetComponentId())
return fx.Options(
fx.Invoke(
qs.setup,
),
), nil
}
// quotaScheduler implements rate limiter on the data plane side.
type quotaScheduler struct {
schedulers sync.Map
iface.Component
registry status.Registry
limiter ratelimiter.RateLimiter
clock clockwork.Clock
qsFactory *quotaSchedulerFactory
inner *globaltokenbucket.GlobalTokenBucket
proto *policylangv1.QuotaScheduler
schedulerMetrics *workloadscheduler.SchedulerMetrics
name string
labelStatusJobGroup *jobs.JobGroup
tokensLabelKeyStatus *labelstatus.LabelStatus
priorityLabelKeyStatus *labelstatus.LabelStatus
workloadLabelKeyStatus *labelstatus.LabelStatus
fairnessLabelKeyStatus *labelstatus.LabelStatus
}
func (qs *quotaScheduler) setup(lifecycle fx.Lifecycle) error {
logger := qs.registry.GetLogger()
etcdKey := paths.AgentComponentKey(qs.qsFactory.agentGroupName,
qs.GetPolicyName(),
qs.GetComponentId())
// decision notifier
decisionUnmarshaller, err := config.NewProtobufUnmarshaller(nil)
if err != nil {
return err
}
decisionNotifier, err := notifiers.NewUnmarshalKeyNotifier(
notifiers.Key(etcdKey),
decisionUnmarshaller,
qs.decisionUpdateCallback,
)
if err != nil {
return err
}
metricLabels := make(prometheus.Labels)
metricLabels[metrics.PolicyNameLabel] = qs.GetPolicyName()
metricLabels[metrics.PolicyHashLabel] = qs.GetPolicyHash()
metricLabels[metrics.ComponentIDLabel] = qs.GetComponentId()
lifecycle.Append(fx.Hook{
OnStart: func(context.Context) error {
var err error
idleDuration := qs.proto.RateLimiter.GetMaxIdleTime().AsDuration()
job := jobs.NewBasicJob(qs.name, qs.audit)
// register job with job group
err = qs.qsFactory.auditJobGroup.RegisterJob(job, jobs.JobConfig{
ExecutionPeriod: config.MakeDuration(idleDuration),
})
if err != nil {
return err
}
qs.schedulerMetrics, err = qs.qsFactory.wsFactory.NewSchedulerMetrics(metricLabels)
if err != nil {
logger.Error().Err(err).Msg("Failed to create scheduler metrics")
return err
}
qs.inner, err = globaltokenbucket.NewGlobalTokenBucket(
qs.qsFactory.distCache,
qs.name,
qs.proto.RateLimiter.GetInterval().AsDuration(),
qs.proto.RateLimiter.GetMaxIdleTime().AsDuration(),
qs.proto.RateLimiter.GetContinuousFill(),
qs.proto.RateLimiter.GetDelayInitialFill(),
qs.qsFactory.rateLimiterJobGroup,
)
if err != nil {
logger.Error().Err(err).Msg("Failed to create limiter")
return err
}
qs.limiter = qs.inner
// check whether lazy limiter is enabled
if lazySyncConfig := qs.proto.RateLimiter.GetLazySync(); lazySyncConfig != nil {
if lazySyncConfig.GetEnabled() {
qs.limiter, err = lazysync.NewLazySyncRateLimiter(
qs.limiter,
qs.proto.RateLimiter.GetInterval().AsDuration(),
lazySyncConfig.GetNumSync(),
qs.qsFactory.auditJobGroup,
)
if err != nil {
logger.Error().Err(err).Msg("Failed to create lazy limiter")
return err
}
}
}
// add decisions notifier
err = qs.qsFactory.decisionsWatcher.AddKeyNotifier(decisionNotifier)
if err != nil {
logger.Error().Err(err).Msg("Failed to add decision notifier")
return err
}
// add to data engine
err = qs.qsFactory.engineAPI.RegisterScheduler(qs)
if err != nil {
logger.Error().Err(err).Msg("Failed to register scheduler")
return err
}
return nil
},
OnStop: func(context.Context) error {
var merr, err error
// remove from data engine
err = qs.qsFactory.engineAPI.UnregisterScheduler(qs)
if err != nil {
logger.Error().Err(err).Msg("Failed to unregister rate limiter")
merr = multierr.Append(merr, err)
}
// remove decisions notifier
err = qs.qsFactory.decisionsWatcher.RemoveKeyNotifier(decisionNotifier)
if err != nil {
logger.Error().Err(err).Msg("Failed to remove decision notifier")
merr = multierr.Append(merr, err)
}
err = qs.limiter.Close()
if err != nil {
logger.Error().Err(err).Msg("Failed to close limiter")
merr = multierr.Append(merr, err)
}
err = qs.schedulerMetrics.Delete()
if err != nil {
logger.Error().Err(err).Msg("Failed to delete scheduler metrics")
merr = multierr.Append(merr, err)
}
err = qs.qsFactory.auditJobGroup.DeregisterJob(qs.name)
if err != nil {
logger.Error().Err(err).Msg("Failed to deregister job")
merr = multierr.Append(merr, err)
}
qs.registry.SetStatus(status.NewStatus(nil, merr), nil)
return merr
},
})
return nil
}
// GetSelectors returns the selectors for the rate limiter.
func (qs *quotaScheduler) GetSelectors() []*policylangv1.Selector {
return qs.proto.GetSelectors()
}
func (qs *quotaScheduler) getLabelKey(labels labels.Labels) (string, bool) {
labelKey := qs.proto.RateLimiter.GetLimitByLabelKey()
if labelKey == "" {
// Deprecated: Remove in v3.0.0
labelKey = qs.proto.RateLimiter.GetLabelKey()
}
var label string
if labelKey == "" {
label = "default"
} else {
labelValue, found := labels.Get(labelKey)
if !found {
return "", false
}
label = labelKey + ":" + labelValue
}
return label, true
}
// Decide runs the limiter.
func (qs *quotaScheduler) Decide(ctx context.Context, labels labels.Labels) *flowcontrolv1.LimiterDecision {
reason := flowcontrolv1.LimiterDecision_LIMITER_REASON_UNSPECIFIED
dropped := false
label := ""
schedulerInfo := &flowcontrolv1.LimiterDecision_SchedulerInfo{
WorkloadIndex: metrics.DefaultWorkloadIndex,
}
returnDecision := func() *flowcontrolv1.LimiterDecision {
return &flowcontrolv1.LimiterDecision{
PolicyName: qs.GetPolicyName(),
PolicyHash: qs.GetPolicyHash(),
ComponentId: qs.GetComponentId(),
Dropped: dropped,
DeniedResponseStatusCode: qs.proto.GetScheduler().GetDeniedResponseStatusCode(),
Reason: reason,
Details: &flowcontrolv1.LimiterDecision_QuotaSchedulerInfo_{
QuotaSchedulerInfo: &flowcontrolv1.LimiterDecision_QuotaSchedulerInfo{
Label: label,
WorkloadIndex: schedulerInfo.WorkloadIndex,
TokensInfo: schedulerInfo.TokensInfo,
Priority: schedulerInfo.Priority,
},
},
}
}
if qs.limiter.GetPassThrough() {
return returnDecision()
}
var found bool
label, found = qs.getLabelKey(labels)
if !found {
reason = flowcontrolv1.LimiterDecision_LIMITER_REASON_KEY_NOT_FOUND
return returnDecision()
}
// lookup the scheduler
existing, found := qs.schedulers.Load(label)
if !found {
tokenBucket := scheduler.NewGlobalTokenBucket(label, qs.limiter)
s, err := qs.qsFactory.wsFactory.NewScheduler(
qs.clock,
qs.registry,
qs.proto.Scheduler,
qs,
tokenBucket,
qs.schedulerMetrics,
qs.tokensLabelKeyStatus,
qs.priorityLabelKeyStatus,
qs.workloadLabelKeyStatus,
qs.fairnessLabelKeyStatus,
)
if err != nil {
log.Error().Err(err).Msg("Failed to create scheduler")
return returnDecision()
}
// add to the map using LoadOrStore
existing, _ = qs.schedulers.LoadOrStore(label, s)
}
s := existing.(*workloadscheduler.Scheduler)
schedulerDecision, _ := s.Decide(ctx, labels)
schedulerInfo = schedulerDecision.GetLoadSchedulerInfo()
dropped = schedulerDecision.GetDropped()
return returnDecision()
}
// Revert returns the tokens to the limiter.
func (qs *quotaScheduler) Revert(ctx context.Context, labels labels.Labels, decision *flowcontrolv1.LimiterDecision) {
if qs.limiter.GetPassThrough() {
return
}
// return to the underlying rate limiter
if qsDecision, ok := decision.GetDetails().(*flowcontrolv1.LimiterDecision_QuotaSchedulerInfo_); ok {
tokens := qsDecision.QuotaSchedulerInfo.TokensInfo.Consumed
if tokens > 0 {
label, found := qs.getLabelKey(labels)
if found {
qs.limiter.TakeIfAvailable(ctx, label, float64(-tokens))
}
}
}
}
func (qs *quotaScheduler) audit(ctx context.Context) (proto.Message, error) {
now := time.Now()
// range through the map and sync the counters
qs.schedulers.Range(func(label, value interface{}) bool {
s := value.(*workloadscheduler.Scheduler)
lastAccess, size := s.Info()
// if this counter has not synced in a while, then remove it from the map
if now.After(lastAccess.Add(qs.proto.RateLimiter.MaxIdleTime.AsDuration())) &&
size == 0 {
qs.schedulers.Delete(label)
return true
}
return true
})
return nil, nil
}
func (qs *quotaScheduler) decisionUpdateCallback(event notifiers.Event, unmarshaller config.Unmarshaller) {
logger := qs.registry.GetLogger()
if event.Type == notifiers.Remove {
logger.Debug().Msg("Decision removed")
qs.limiter.SetPassThrough(true)
return
}
var wrapperMessage policysyncv1.RateLimiterDecisionWrapper
err := unmarshaller.Unmarshal(&wrapperMessage)
if err != nil || wrapperMessage.RateLimiterDecision == nil {
return
}
commonAttributes := wrapperMessage.GetCommonAttributes()
if commonAttributes == nil {
log.Error().Msg("Common attributes not found")
return
}
if commonAttributes.PolicyHash != qs.GetPolicyHash() {
return
}
limitDecision := wrapperMessage.RateLimiterDecision
qs.inner.SetBucketCapacity(limitDecision.BucketCapacity)
qs.inner.SetFillAmount(limitDecision.FillAmount)
qs.inner.SetPassThrough(limitDecision.PassThrough)
}
// GetLimiterID returns the limiter ID.
func (qs *quotaScheduler) GetLimiterID() iface.LimiterID {
return iface.LimiterID{
PolicyName: qs.GetPolicyName(),
PolicyHash: qs.GetPolicyHash(),
ComponentID: qs.GetComponentId(),
}
}
// GetLatencyObserver returns the latency observer.
func (qs *quotaScheduler) GetLatencyObserver(labels map[string]string) prometheus.Observer {
return qs.qsFactory.wsFactory.GetLatencyObserver(labels)
}
// GetRequestCounter returns counter for tracking number of times rateLimiter was triggered.
func (qs *quotaScheduler) GetRequestCounter(labels map[string]string) prometheus.Counter {
return qs.qsFactory.wsFactory.GetRequestCounter(labels)
}
// GetRampMode is always false for quotaSchedulers.
func (qs *quotaScheduler) GetRampMode() bool {
return false
}