-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
granter.go
1815 lines (1661 loc) · 70.7 KB
/
granter.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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package admission
import (
"context"
"math"
"time"
"unsafe"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/metric"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/pebble"
"github.com/cockroachdb/redact"
)
// KVSlotAdjusterOverloadThreshold sets a goroutine runnable threshold at
// which the CPU will be considered overloaded, when running in a node that
// executes KV operations.
var KVSlotAdjusterOverloadThreshold = settings.RegisterIntSetting(
settings.TenantWritable,
"admission.kv_slot_adjuster.overload_threshold",
"when the number of runnable goroutines per CPU is greater than this threshold, the "+
"slot adjuster considers the cpu to be overloaded",
32, settings.PositiveInt)
// L0FileCountOverloadThreshold sets a file count threshold that signals an
// overloaded store.
var L0FileCountOverloadThreshold = settings.RegisterIntSetting(
settings.TenantWritable,
"admission.l0_file_count_overload_threshold",
"when the L0 file count exceeds this theshold, the store is considered overloaded",
l0FileCountOverloadThreshold, settings.PositiveInt)
// L0SubLevelCountOverloadThreshold sets a sub-level count threshold that
// signals an overloaded store.
var L0SubLevelCountOverloadThreshold = settings.RegisterIntSetting(
settings.TenantWritable,
"admission.l0_sub_level_count_overload_threshold",
"when the L0 sub-level count exceeds this threshold, the store is considered overloaded",
l0SubLevelCountOverloadThreshold, settings.PositiveInt)
// grantChainID is the ID for a grant chain. See continueGrantChain for
// details.
type grantChainID uint64
// noGrantChain is a sentinel value representing that the grant is not
// responsible for continuing a grant chain. It is only used internally in
// this file -- requester implementations do not need to concern themselves
// with this value.
var noGrantChain grantChainID = 0
// requester is an interface implemented by an object that orders admission
// work for a particular WorkKind. See WorkQueue for the implementation of
// requester.
type requester interface {
// hasWaitingRequests returns whether there are any waiting/queued requests
// of this WorkKind.
hasWaitingRequests() bool
// granted is called by a granter to grant admission to queued requests. It
// returns true if the grant was accepted, else returns false. A grant may
// not be accepted if the grant raced with request cancellation and there
// are now no waiting requests. The grantChainID is used when calling
// continueGrantChain -- see the comment with that method below.
granted(grantChainID grantChainID) bool
// getAdmittedCount returns the cumulative count of admitted work.
getAdmittedCount() uint64
}
// grantKind represents the two kind of ways we grant admission: using a slot
// or a token. The slot terminology is akin to a scheduler, where a scheduling
// slot must be free for a thread to run. But unlike a scheduler, we don't
// have visibility into the fact that work execution may be blocked on IO. So
// a slot can also be viewed as a limit on concurrency of ongoing work. The
// token terminology is inspired by token buckets. In this case the token is
// handed out for admission but it is not returned (unlike a slot). Unlike a
// token bucket, which shapes the rate, the current implementation (see
// tokenGranter) limits burstiness and does not do rate shaping -- this is
// because it is hard to predict what rate is appropriate given the difference
// in sizes of the work. This lack of rate shaping may change in the future
// and is not a limitation of the interfaces. Similarly, there is no rate
// shaping applied when granting slots and that may also change in the future.
// The main difference between a slot and a token is that a slot is used when
// we can know when the work is complete. Having this extra completion
// information can be advantageous in admission control decisions, so
// WorkKinds where this information is easily available use slots.
type grantKind int8
const (
slot grantKind = iota
token
)
// granter is paired with a requester in that a requester for a particular
// WorkKind will interact with a granter. See doc.go for an overview of how
// this fits into the overall structure.
type granter interface {
grantKind() grantKind
// tryGet is used by a requester to get a slot/token for a piece of work
// that has encountered no waiting/queued work. This is the fast path that
// avoids queueing in the requester.
tryGet() bool
// returnGrant is called for returning slots after use, and used for
// returning either slots or tokens when the grant raced with the work being
// canceled, and the grantee did not end up doing any work. The latter case
// occurs despite the bool return value on the requester.granted method --
// it is possible that the work was not canceled at the time when
// requester.grant was called, and hence returned true, but later when the
// goroutine doing the work noticed that it had been granted, there is a
// possibility that that raced with cancellation.
returnGrant()
// tookWithoutPermission informs the granter that a slot/token was taken
// unilaterally, without permission. Currently we only implement this for
// slots, since only KVWork is allowed to bypass admission control for high
// priority internal activities (e.g. node liveness) and for KVWork that
// generates other KVWork (like intent resolution of discovered intents).
// Not bypassing for the latter could result in single node or distributed
// deadlock, and since such work is typically not a major (on average)
// consumer of resources, we consider bypassing to be acceptable.
tookWithoutPermission()
// continueGrantChain is called by the requester at some point after grant
// was called on the requester. The expectation is that this is called by
// the grantee after its goroutine runs and notices that it has been granted
// a slot/token. This provides a natural throttling that reduces grant
// bursts by taking into immediate account the capability of the goroutine
// scheduler to schedule such work.
//
// In an experiment, using such grant chains reduced burstiness of grants by
// 5x and shifted ~2s of latency (at p99) from the scheduler into admission
// control (which is desirable since the latter is where we can
// differentiate between work).
//
// TODO(sumeer): the "grant chain" concept is subtle and under-documented.
// It's easy to go through most of this package thinking it has something to
// do with dependent requests (e.g. intent resolution chains on an end txn).
// It would help for a top-level comment on grantChainID or continueGrantChain
// to spell out what grant chains are, their purpose, and how they work with
// an example.
continueGrantChain(grantChainID grantChainID)
}
// WorkKind represents various types of work that are subject to admission
// control.
type WorkKind int8
// The list of WorkKinds are ordered from lower level to higher level, and
// also serves as a hard-wired ordering from most important to least important
// (for details on how this ordering is enacted, see the GrantCoordinator
// code).
//
// KVWork, SQLKVResponseWork, SQLSQLResponseWork are the lower-level work
// units that are expected to be primarily CPU bound (with disk IO for KVWork,
// but cache hit rates are typically high), and expected to be where most of
// the CPU consumption happens. These are prioritized in the order
// KVWork > SQLKVResponseWork > SQLSQLResponseWork
//
// The high prioritization of KVWork reduces the likelihood that non-SQL KV
// work will be starved. SQLKVResponseWork is prioritized over
// SQLSQLResponseWork since the former includes leaf DistSQL processing and we
// would like to release memory used up in RPC responses at lower layers of
// RPC tree. We expect that if SQLSQLResponseWork is delayed, it will
// eventually reduce new work being issued, which is a desirable form of
// natural backpressure.
//
// Furthermore, SQLStatementLeafStartWork and SQLStatementRootStartWork are
// prioritized lowest with
// SQLStatementLeafStartWork > SQLStatementRootStartWork
// This follows the same idea of prioritizing lower layers above higher layers
// since it releases memory caught up in lower layers, and exerts natural
// backpressure on the higher layer.
//
// Consider the example of a less important long-running single statement OLAP
// query competing with more important small OLTP queries in a single node
// setting. Say the OLAP query starts first and uses up all the KVWork slots,
// and the OLTP queries queue up for the KVWork slots. As the OLAP query
// KVWork completes, it will queue up for SQLKVResponseWork, which will not
// start because the OLTP queries are using up all available KVWork slots. As
// this OLTP KVWork completes, their SQLKVResponseWork will queue up. The
// WorkQueue for SQLKVResponseWork, when granting tokens, will first admit
// those for the more important OLTP queries. This will prevent or slow down
// admission of further work by the OLAP query.
//
// In an ideal world with the only shared resource (across WorkKinds) being
// CPU, and control over the CPU scheduler, we could pool all work, regardless
// of WorkKind into a single queue, and would not need to rely on this
// indirect backpressure and hard-wired ordering. However, we do not have
// control over the CPU scheduler, so we cannot preempt work with widely
// different cpu consumption. Additionally, (non-preemptible) memory is also a
// shared resource, and we wouldn't want to have partially done KVWork not
// finish, due to preemption in the CPU scheduler, since it can be holding
// significant amounts of memory (e.g. in scans).
//
// The aforementioned prioritization also enables us to get instantaneous
// feedback on CPU resource overload. This instantaneous feedback for a grant
// chain (mentioned earlier) happens in two ways:
// - the chain requires the grantee's goroutine to run.
// - the cpuOverloadIndicator (see later), specifically the implementation
// provided by kvSlotAdjuster, provides instantaneous feedback (which is
// viable only because KVWork is the highest priority).
//
// Weaknesses of this strict prioritization across WorkKinds:
// - Priority inversion: Lower importance KVWork, not derived from SQL, like
// GC of MVCC versions, will happen before user-facing SQLKVResponseWork.
// This is because the backpressure, described in the example above, does
// not apply to work generated from within the KV layer.
// TODO(sumeer): introduce a KVLowPriWork and put it last in this ordering,
// to get over this limitation.
// - Insufficient competition leading to poor isolation: Putting
// SQLStatementLeafStartWork, SQLStatementRootStartWork in this list, within
// the same GrantCoordinator, does provide node overload protection, but not
// necessarily performance isolation when we have WorkKinds of different
// importance. Consider the same OLAP example above: if the KVWork slots
// being full due to the OLAP query prevents SQLStatementRootStartWork for
// the OLTP queries, the competition is starved out before it has an
// opportunity to submit any KVWork. Given that control over admitting
// SQLStatement{Leaf,Root}StartWork is not primarily about CPU control (the
// lower-level work items are where cpu is consumed), we could decouple
// these two into a separate GrantCoordinator and only gate them with (high)
// fixed slot counts that allow for enough competition, plus a memory
// overload indicator.
// TODO(sumeer): experiment with this approach.
// - Continuing the previous bullet, low priority long-lived
// {SQLStatementLeafStartWork, SQLStatementRootStartWork} could use up all
// the slots, if there was no high priority work for some period of time,
// and therefore starve admission of the high priority work when it does
// appear. The typical solution to this is to put a max on the number of
// slots low priority can use. This would be viable if we did not allow
// arbitrary int8 values to be set for WorkPriority.
const (
// KVWork represents requests submitted to the KV layer, from the same node
// or a different node. They may originate from the SQL layer or the KV
// layer.
KVWork WorkKind = iota
// SQLKVResponseWork is response processing in SQL for a KV response from a
// local or remote node. This can be either leaf or root DistSQL work, i.e.,
// this is inter-layer and not necessarily inter-node.
SQLKVResponseWork
// SQLSQLResponseWork is response processing in SQL, for DistSQL RPC
// responses. This is root work happening in response to leaf SQL work,
// i.e., it is inter-node.
SQLSQLResponseWork
// SQLStatementLeafStartWork represents the start of leaf-level processing
// for a SQL statement.
SQLStatementLeafStartWork
// SQLStatementRootStartWork represents the start of root-level processing
// for a SQL statement.
SQLStatementRootStartWork
numWorkKinds
)
func workKindString(workKind WorkKind) redact.RedactableString {
switch workKind {
case KVWork:
return "kv"
case SQLKVResponseWork:
return "sql-kv-response"
case SQLSQLResponseWork:
return "sql-sql-response"
case SQLStatementLeafStartWork:
return "sql-leaf-start"
case SQLStatementRootStartWork:
return "sql-root-start"
default:
panic(errors.AssertionFailedf("unknown WorkKind"))
}
}
type grantResult int8
const (
grantSuccess grantResult = iota
// grantFailDueToSharedResource is returned when the granter is unable to
// grant because a shared resource (CPU or memory) is overloaded. For grant
// chains, this is a signal to terminate.
grantFailDueToSharedResource
// grantFailLocal is returned when the granter is unable to grant due to a
// local constraint -- insufficient tokens or slots.
grantFailLocal
)
// granterWithLockedCalls is an extension of the granter and requester
// interfaces that is used as an internal implementation detail of the
// GrantCoordinator. Note that an implementer of granterWithLockedCalls is
// mainly passing things through to the GrantCoordinator where the main logic
// lives. The *Locked() methods are where the differences in slots and tokens
// are handled.
type granterWithLockedCalls interface {
granter
// tryGetLocked is the real implementation of tryGet in the granter interface.
// Additionally, it is also used when continuing a grant chain.
tryGetLocked() grantResult
// returnGrantLocked is the real implementation of returnGrant.
returnGrantLocked()
// tookWithoutPermissionLocked is the real implementation of
// tookWithoutPermission.
tookWithoutPermissionLocked()
// getPairedRequester returns the requester implementation that this granter
// interacts with.
getPairedRequester() requester
}
// slotGranter implements granterWithLockedCalls.
type slotGranter struct {
coord *GrantCoordinator
workKind WorkKind
requester requester
usedSlots int
totalSlots int
// Optional. Nil for a slotGranter used for KVWork since the slots for that
// slotGranter are directly adjusted by the kvSlotAdjuster (using the
// kvSlotAdjuster here would provide a redundant identical signal).
cpuOverload cpuOverloadIndicator
// TODO(sumeer): Add an optional overload indicator for memory, that will be
// relevant for SQLStatementLeafStartWork and SQLStatementRootStartWork.
usedSlotsMetric *metric.Gauge
}
var _ granterWithLockedCalls = &slotGranter{}
func (sg *slotGranter) getPairedRequester() requester {
return sg.requester
}
func (sg *slotGranter) grantKind() grantKind {
return slot
}
func (sg *slotGranter) tryGet() bool {
return sg.coord.tryGet(sg.workKind)
}
func (sg *slotGranter) tryGetLocked() grantResult {
if sg.cpuOverload != nil && sg.cpuOverload.isOverloaded() {
return grantFailDueToSharedResource
}
if sg.usedSlots < sg.totalSlots {
sg.usedSlots++
sg.usedSlotsMetric.Update(int64(sg.usedSlots))
return grantSuccess
}
if sg.workKind == KVWork {
return grantFailDueToSharedResource
}
return grantFailLocal
}
func (sg *slotGranter) returnGrant() {
sg.coord.returnGrant(sg.workKind)
}
func (sg *slotGranter) returnGrantLocked() {
sg.usedSlots--
if sg.usedSlots < 0 {
panic(errors.AssertionFailedf("used slots is negative %d", sg.usedSlots))
}
sg.usedSlotsMetric.Update(int64(sg.usedSlots))
}
func (sg *slotGranter) tookWithoutPermission() {
sg.coord.tookWithoutPermission(sg.workKind)
}
func (sg *slotGranter) tookWithoutPermissionLocked() {
sg.usedSlots++
sg.usedSlotsMetric.Update(int64(sg.usedSlots))
}
func (sg *slotGranter) continueGrantChain(grantChainID grantChainID) {
sg.coord.continueGrantChain(sg.workKind, grantChainID)
}
// tokenGranter implements granterWithLockedCalls.
type tokenGranter struct {
coord *GrantCoordinator
workKind WorkKind
requester requester
availableBurstTokens int
maxBurstTokens int
skipTokenEnforcement bool
// Optional. Practically, both uses of tokenGranter, for SQLKVResponseWork
// and SQLSQLResponseWork have a non-nil value. We don't expect to use
// memory overload indicators here since memory accounting and disk spilling
// is what should be tasked with preventing OOMs, and we want to finish
// processing this lower-level work.
cpuOverload cpuOverloadIndicator
}
var _ granterWithLockedCalls = &tokenGranter{}
func (tg *tokenGranter) getPairedRequester() requester {
return tg.requester
}
func (tg *tokenGranter) refillBurstTokens(skipTokenEnforcement bool) {
tg.availableBurstTokens = tg.maxBurstTokens
tg.skipTokenEnforcement = skipTokenEnforcement
}
func (tg *tokenGranter) grantKind() grantKind {
return token
}
func (tg *tokenGranter) tryGet() bool {
return tg.coord.tryGet(tg.workKind)
}
func (tg *tokenGranter) tryGetLocked() grantResult {
if tg.cpuOverload != nil && tg.cpuOverload.isOverloaded() {
return grantFailDueToSharedResource
}
if tg.availableBurstTokens > 0 || tg.skipTokenEnforcement {
tg.availableBurstTokens--
return grantSuccess
}
return grantFailLocal
}
func (tg *tokenGranter) returnGrant() {
tg.coord.returnGrant(tg.workKind)
}
func (tg *tokenGranter) returnGrantLocked() {
tg.availableBurstTokens++
if tg.availableBurstTokens > tg.maxBurstTokens {
tg.availableBurstTokens = tg.maxBurstTokens
}
}
func (tg *tokenGranter) tookWithoutPermission() {
panic(errors.AssertionFailedf("unimplemented"))
}
func (tg *tokenGranter) tookWithoutPermissionLocked() {
panic(errors.AssertionFailedf("unimplemented"))
}
func (tg *tokenGranter) continueGrantChain(grantChainID grantChainID) {
tg.coord.continueGrantChain(tg.workKind, grantChainID)
}
// kvGranter implements granterWithLockedCalls. It is used for grants to
// KVWork, that are limited by slots (CPU bound work) and/or tokens (IO
// bound work).
type kvGranter struct {
coord *GrantCoordinator
requester requester
usedSlots int
totalSlots int
skipSlotEnforcement bool
ioTokensEnabled bool
// There is no rate limiting in granting these tokens. That is, they are all
// burst tokens.
availableIOTokens int64
// Metric pointers can be nil.
usedSlotsMetric *metric.Gauge
ioTokensExhaustedDurationMetric *metric.Counter
exhaustedStart time.Time
}
var _ granterWithLockedCalls = &kvGranter{}
func (sg *kvGranter) getPairedRequester() requester {
return sg.requester
}
func (sg *kvGranter) grantKind() grantKind {
// Slot represents that there is a completion indicator, and it does not
// matter that kvGranter internally uses both slots and tokens.
return slot
}
func (sg *kvGranter) tryGet() bool {
return sg.coord.tryGet(KVWork)
}
func (sg *kvGranter) tryGetLocked() grantResult {
if sg.usedSlots < sg.totalSlots || sg.skipSlotEnforcement {
if !sg.ioTokensEnabled || sg.availableIOTokens > 0 {
sg.usedSlots++
if sg.usedSlotsMetric != nil {
sg.usedSlotsMetric.Update(int64(sg.usedSlots))
}
if sg.ioTokensEnabled {
sg.availableIOTokens--
if sg.availableIOTokens == 0 {
sg.exhaustedStart = timeutil.Now()
}
}
return grantSuccess
}
return grantFailLocal
}
return grantFailDueToSharedResource
}
func (sg *kvGranter) returnGrant() {
sg.coord.returnGrant(KVWork)
}
func (sg *kvGranter) returnGrantLocked() {
sg.usedSlots--
if sg.usedSlots < 0 {
panic(errors.AssertionFailedf("used slots is negative %d", sg.usedSlots))
}
if sg.usedSlotsMetric != nil {
sg.usedSlotsMetric.Update(int64(sg.usedSlots))
}
}
func (sg *kvGranter) tookWithoutPermission() {
sg.coord.tookWithoutPermission(KVWork)
}
func (sg *kvGranter) tookWithoutPermissionLocked() {
sg.usedSlots++
if sg.usedSlotsMetric != nil {
sg.usedSlotsMetric.Update(int64(sg.usedSlots))
}
if sg.ioTokensEnabled {
sg.availableIOTokens--
if sg.availableIOTokens == 0 {
sg.exhaustedStart = timeutil.Now()
}
}
}
func (sg *kvGranter) continueGrantChain(grantChainID grantChainID) {
sg.coord.continueGrantChain(KVWork, grantChainID)
}
func (sg *kvGranter) setAvailableIOTokensLocked(tokens int64) {
wasExhausted := sg.ioTokensEnabled && sg.availableIOTokens <= 0
sg.ioTokensEnabled = true
if sg.availableIOTokens < 0 {
// Negative because of tookWithoutPermission.
sg.availableIOTokens += tokens
} else {
sg.availableIOTokens = tokens
}
if wasExhausted && sg.ioTokensExhaustedDurationMetric != nil {
// NB: sg.availableIOTokens may still be 0, i.e., tokens may continue to
// be exhausted. We do want to tick the metric so that it doesn't show a
// burst of activity after many minutes of exhaustion (which we had
// observed prior to this code).
now := timeutil.Now()
exhaustedMicros := now.Sub(sg.exhaustedStart).Microseconds()
sg.ioTokensExhaustedDurationMetric.Inc(exhaustedMicros)
if sg.availableIOTokens == 0 {
sg.exhaustedStart = now
}
}
}
// GrantCoordinator is the top-level object that coordinates grants across
// different WorkKinds (for more context see the comment in doc.go, and the
// comment where WorkKind is declared). Typically there will one
// GrantCoordinator in a node for CPU intensive work, and for nodes that also
// have the KV layer, one GrantCoordinator per store (these are managed by
// StoreGrantCoordinators) for KVWork that uses that store. See the
// NewGrantCoordinators and NewGrantCoordinatorSQL functions.
type GrantCoordinator struct {
ambientCtx log.AmbientContext
settings *cluster.Settings
lastCPULoadSamplePeriod time.Duration
// mu is ordered before any mutex acquired in a requester implementation.
// TODO(sumeer): move everything covered by mu into a nested struct.
mu syncutil.Mutex
// NB: Some granters can be nil.
granters [numWorkKinds]granterWithLockedCalls
// The WorkQueues behaving as requesters in each granterWithLockedCalls.
// This is kept separately only to service GetWorkQueue calls.
queues [numWorkKinds]requester
// The cpu fields can be nil, and the IO field can be nil, since a
// GrantCoordinator typically handles one of these two resources.
cpuOverloadIndicator cpuOverloadIndicator
cpuLoadListener CPULoadListener
ioLoadListener *ioLoadListener
// The latest value of GOMAXPROCS, received via CPULoad. Only initialized if
// the cpu resource is being handled by this GrantCoordinator.
numProcs int
// See the comment at continueGrantChain that explains how a grant chain
// functions and the motivation. When !useGrantChains, grant chains are
// disabled.
useGrantChains bool
// The admission control code needs high sampling frequency of the cpu load,
// and turns off admission control enforcement when the sampling frequency
// is too low. For testing queueing behavior, we do not want the enforcement
// to be turned off in a non-deterministic manner so add a testing flag to
// disable that feature.
testingDisableSkipEnforcement bool
// grantChainActive indicates whether a grant chain is active. If active,
// grantChainID is the ID of that chain. If !active, grantChainID is the ID
// of the next chain that will become active. IDs are assigned by
// incrementing grantChainID. If !useGrantChains, grantChainActive is never
// true.
grantChainActive bool
grantChainID grantChainID
// Index into granters, which represents the current WorkKind at which the
// grant chain is operating. Only relevant when grantChainActive is true.
grantChainIndex WorkKind
// See the comment at delayForGrantChainTermination for motivation.
grantChainStartTime time.Time
}
var _ CPULoadListener = &GrantCoordinator{}
// Options for constructing GrantCoordinators.
type Options struct {
MinCPUSlots int
MaxCPUSlots int
SQLKVResponseBurstTokens int
SQLSQLResponseBurstTokens int
SQLStatementLeafStartWorkSlots int
SQLStatementRootStartWorkSlots int
TestingDisableSkipEnforcement bool
Settings *cluster.Settings
// Only non-nil for tests.
makeRequesterFunc makeRequesterFunc
}
var _ base.ModuleTestingKnobs = &Options{}
// ModuleTestingKnobs implements the base.ModuleTestingKnobs interface.
func (*Options) ModuleTestingKnobs() {}
// DefaultOptions are the default settings for various admission control knobs.
var DefaultOptions Options = Options{
MinCPUSlots: 1,
MaxCPUSlots: 100000, /* TODO(sumeer): add cluster setting */
SQLKVResponseBurstTokens: 100000, /* TODO(sumeer): add cluster setting */
SQLSQLResponseBurstTokens: 100000, /* TODO(sumeer): add cluster setting */
SQLStatementLeafStartWorkSlots: 100, /* arbitrary, and unused */
SQLStatementRootStartWorkSlots: 100, /* arbitrary, and unused */
}
// Override applies values from "override" to the receiver that differ from Go
// defaults.
func (o *Options) Override(override *Options) {
if override.MinCPUSlots != 0 {
o.MinCPUSlots = override.MinCPUSlots
}
if override.MaxCPUSlots != 0 {
o.MaxCPUSlots = override.MaxCPUSlots
}
if override.SQLKVResponseBurstTokens != 0 {
o.SQLKVResponseBurstTokens = override.SQLKVResponseBurstTokens
}
if override.SQLSQLResponseBurstTokens != 0 {
o.SQLSQLResponseBurstTokens = override.SQLSQLResponseBurstTokens
}
if override.SQLStatementLeafStartWorkSlots != 0 {
o.SQLStatementLeafStartWorkSlots = override.SQLStatementLeafStartWorkSlots
}
if override.SQLStatementRootStartWorkSlots != 0 {
o.SQLStatementRootStartWorkSlots = override.SQLStatementRootStartWorkSlots
}
if override.TestingDisableSkipEnforcement {
o.TestingDisableSkipEnforcement = true
}
}
type makeRequesterFunc func(
_ log.AmbientContext, workKind WorkKind, granter granter, settings *cluster.Settings,
opts workQueueOptions) requester
// NewGrantCoordinators constructs GrantCoordinators and WorkQueues for a
// regular cluster node. Caller is responsible for hooking up
// GrantCoordinators.Regular to receive calls to CPULoad, and to set a
// PebbleMetricsProvider on GrantCoordinators.Stores. Every request must pass
// through GrantCoordinators.Regular, while only subsets of requests pass
// through each store's GrantCoordinator. We arrange these such that requests
// (that need to) first pass through a store's GrantCoordinator and then
// through the regular one. This ensures that we are not using slots in the
// latter on requests that are blocked elsewhere for admission. Additionally,
// we don't want the CPU scheduler signal that is implicitly used in grant
// chains to delay admission through the per store GrantCoordinators since
// they are not trying to control CPU usage, so we turn off grant chaining in
// those coordinators.
func NewGrantCoordinators(
ambientCtx log.AmbientContext, opts Options,
) (GrantCoordinators, []metric.Struct) {
makeRequester := makeWorkQueue
if opts.makeRequesterFunc != nil {
makeRequester = opts.makeRequesterFunc
}
st := opts.Settings
metrics := makeGranterMetrics()
metricStructs := append([]metric.Struct(nil), metrics)
kvSlotAdjuster := &kvSlotAdjuster{
settings: st,
minCPUSlots: opts.MinCPUSlots,
maxCPUSlots: opts.MaxCPUSlots,
totalSlotsMetric: metrics.KVTotalSlots,
}
coord := &GrantCoordinator{
ambientCtx: ambientCtx,
settings: st,
cpuOverloadIndicator: kvSlotAdjuster,
cpuLoadListener: kvSlotAdjuster,
useGrantChains: true,
testingDisableSkipEnforcement: opts.TestingDisableSkipEnforcement,
numProcs: 1,
grantChainID: 1,
}
kvg := &kvGranter{
coord: coord,
totalSlots: opts.MinCPUSlots,
usedSlotsMetric: metrics.KVUsedSlots,
}
kvSlotAdjuster.granter = kvg
coord.queues[KVWork] = makeRequester(ambientCtx, KVWork, kvg, st, makeWorkQueueOptions(KVWork))
kvg.requester = coord.queues[KVWork]
coord.granters[KVWork] = kvg
tg := &tokenGranter{
coord: coord,
workKind: SQLKVResponseWork,
availableBurstTokens: opts.SQLKVResponseBurstTokens,
maxBurstTokens: opts.SQLKVResponseBurstTokens,
cpuOverload: kvSlotAdjuster,
}
coord.queues[SQLKVResponseWork] = makeRequester(
ambientCtx, SQLKVResponseWork, tg, st, makeWorkQueueOptions(SQLKVResponseWork))
tg.requester = coord.queues[SQLKVResponseWork]
coord.granters[SQLKVResponseWork] = tg
tg = &tokenGranter{
coord: coord,
workKind: SQLSQLResponseWork,
availableBurstTokens: opts.SQLSQLResponseBurstTokens,
maxBurstTokens: opts.SQLSQLResponseBurstTokens,
cpuOverload: kvSlotAdjuster,
}
coord.queues[SQLSQLResponseWork] = makeRequester(ambientCtx,
SQLSQLResponseWork, tg, st, makeWorkQueueOptions(SQLSQLResponseWork))
tg.requester = coord.queues[SQLSQLResponseWork]
coord.granters[SQLSQLResponseWork] = tg
sg := &slotGranter{
coord: coord,
workKind: SQLStatementLeafStartWork,
totalSlots: opts.SQLStatementLeafStartWorkSlots,
cpuOverload: kvSlotAdjuster,
usedSlotsMetric: metrics.SQLLeafStartUsedSlots,
}
coord.queues[SQLStatementLeafStartWork] = makeRequester(ambientCtx,
SQLStatementLeafStartWork, sg, st, makeWorkQueueOptions(SQLStatementLeafStartWork))
sg.requester = coord.queues[SQLStatementLeafStartWork]
coord.granters[SQLStatementLeafStartWork] = sg
sg = &slotGranter{
coord: coord,
workKind: SQLStatementRootStartWork,
totalSlots: opts.SQLStatementRootStartWorkSlots,
cpuOverload: kvSlotAdjuster,
usedSlotsMetric: metrics.SQLRootStartUsedSlots,
}
coord.queues[SQLStatementRootStartWork] = makeRequester(ambientCtx,
SQLStatementRootStartWork, sg, st, makeWorkQueueOptions(SQLStatementRootStartWork))
sg.requester = coord.queues[SQLStatementRootStartWork]
coord.granters[SQLStatementRootStartWork] = sg
metricStructs = appendMetricStructsForQueues(metricStructs, coord)
storeWorkQueueMetrics := makeWorkQueueMetrics(string(workKindString(KVWork)) + "-stores")
metricStructs = append(metricStructs, storeWorkQueueMetrics)
storeCoordinators := &StoreGrantCoordinators{
settings: st,
makeRequesterFunc: makeRequester,
kvIOTokensExhaustedDuration: metrics.KVIOTokensExhaustedDuration,
workQueueMetrics: storeWorkQueueMetrics,
}
return GrantCoordinators{Stores: storeCoordinators, Regular: coord}, metricStructs
}
// NewGrantCoordinatorSQL constructs a GrantCoordinator and WorkQueues for a
// single-tenant SQL node in a multi-tenant cluster. Caller is responsible for
// hooking this up to receive calls to CPULoad.
func NewGrantCoordinatorSQL(
ambientCtx log.AmbientContext, opts Options,
) (*GrantCoordinator, []metric.Struct) {
makeRequester := makeWorkQueue
if opts.makeRequesterFunc != nil {
makeRequester = opts.makeRequesterFunc
}
st := opts.Settings
metrics := makeGranterMetrics()
metricStructs := append([]metric.Struct(nil), metrics)
sqlNodeCPU := &sqlNodeCPUOverloadIndicator{}
coord := &GrantCoordinator{
ambientCtx: ambientCtx,
settings: st,
cpuOverloadIndicator: sqlNodeCPU,
cpuLoadListener: sqlNodeCPU,
useGrantChains: true,
numProcs: 1,
grantChainID: 1,
}
tg := &tokenGranter{
coord: coord,
workKind: SQLKVResponseWork,
availableBurstTokens: opts.SQLKVResponseBurstTokens,
maxBurstTokens: opts.SQLKVResponseBurstTokens,
cpuOverload: sqlNodeCPU,
}
coord.queues[SQLKVResponseWork] = makeRequester(ambientCtx,
SQLKVResponseWork, tg, st, makeWorkQueueOptions(SQLKVResponseWork))
tg.requester = coord.queues[SQLKVResponseWork]
coord.granters[SQLKVResponseWork] = tg
tg = &tokenGranter{
coord: coord,
workKind: SQLSQLResponseWork,
availableBurstTokens: opts.SQLSQLResponseBurstTokens,
maxBurstTokens: opts.SQLSQLResponseBurstTokens,
cpuOverload: sqlNodeCPU,
}
coord.queues[SQLSQLResponseWork] = makeRequester(ambientCtx,
SQLSQLResponseWork, tg, st, makeWorkQueueOptions(SQLSQLResponseWork))
tg.requester = coord.queues[SQLSQLResponseWork]
coord.granters[SQLSQLResponseWork] = tg
sg := &slotGranter{
coord: coord,
workKind: SQLStatementLeafStartWork,
totalSlots: opts.SQLStatementLeafStartWorkSlots,
cpuOverload: sqlNodeCPU,
usedSlotsMetric: metrics.SQLLeafStartUsedSlots,
}
coord.queues[SQLStatementLeafStartWork] = makeRequester(ambientCtx,
SQLStatementLeafStartWork, sg, st, makeWorkQueueOptions(SQLStatementLeafStartWork))
sg.requester = coord.queues[SQLStatementLeafStartWork]
coord.granters[SQLStatementLeafStartWork] = sg
sg = &slotGranter{
coord: coord,
workKind: SQLStatementRootStartWork,
totalSlots: opts.SQLStatementRootStartWorkSlots,
cpuOverload: sqlNodeCPU,
usedSlotsMetric: metrics.SQLRootStartUsedSlots,
}
coord.queues[SQLStatementRootStartWork] = makeRequester(ambientCtx,
SQLStatementRootStartWork, sg, st, makeWorkQueueOptions(SQLStatementRootStartWork))
sg.requester = coord.queues[SQLStatementRootStartWork]
coord.granters[SQLStatementRootStartWork] = sg
return coord, appendMetricStructsForQueues(metricStructs, coord)
}
func appendMetricStructsForQueues(ms []metric.Struct, coord *GrantCoordinator) []metric.Struct {
for i := range coord.queues {
if coord.queues[i] != nil {
q, ok := coord.queues[i].(*WorkQueue)
if ok {
ms = append(ms, q.metrics)
}
}
}
return ms
}
// pebbleMetricsTick is called every adjustmentInterval seconds and passes
// through to the ioLoadListener, so that it can adjust the plan for future IO
// token allocations.
func (coord *GrantCoordinator) pebbleMetricsTick(ctx context.Context, m *pebble.Metrics) {
coord.ioLoadListener.pebbleMetricsTick(ctx, m)
}
// allocateIOTokensTick tells the ioLoadListener to allocate tokens.
func (coord *GrantCoordinator) allocateIOTokensTick() {
coord.ioLoadListener.allocateTokensTick()
coord.mu.Lock()
defer coord.mu.Unlock()
if !coord.grantChainActive {
coord.tryGrant()
}
// Else, let the grant chain finish. We could terminate it, but token
// replenishment occurs at 1s granularity which is coarse enough to not
// bother. Also, in production we turn off grant chains on the
// GrantCoordinators used for IO, so we will always call tryGrant.
}
// testingTryGrant is only for unit tests, since they sometimes cut out
// support classes like the ioLoadListener.
func (coord *GrantCoordinator) testingTryGrant() {
coord.mu.Lock()
defer coord.mu.Unlock()
if !coord.grantChainActive {
coord.tryGrant()
}
}
// GetWorkQueue returns the WorkQueue for a particular WorkKind. Can be nil if
// the NewGrantCoordinator* function does not construct a WorkQueue for that
// work.
func (coord *GrantCoordinator) GetWorkQueue(workKind WorkKind) *WorkQueue {
return coord.queues[workKind].(*WorkQueue)
}
// CPULoad implements CPULoadListener and is called periodically (see
// CPULoadListener for details). The same frequency is used for refilling the
// burst tokens since synchronizing the two means that the refilled burst can
// take into account the latest schedulers stats (indirectly, via the
// implementation of cpuOverloadIndicator).
func (coord *GrantCoordinator) CPULoad(runnable int, procs int, samplePeriod time.Duration) {
ctx := coord.ambientCtx.AnnotateCtx(context.Background())
if coord.lastCPULoadSamplePeriod != 0 && coord.lastCPULoadSamplePeriod != samplePeriod &&
KVAdmissionControlEnabled.Get(&coord.settings.SV) {
log.Infof(ctx, "CPULoad switching to period %s", samplePeriod.String())
}
coord.lastCPULoadSamplePeriod = samplePeriod
coord.mu.Lock()
defer coord.mu.Unlock()
coord.numProcs = procs
coord.cpuLoadListener.CPULoad(runnable, procs, samplePeriod)
// Slot adjustment and token refilling requires 1ms periods to work well. If
// the CPULoad ticks are less frequent, there is no guarantee that the
// tokens or slots will be sufficient to service requests. This is
// particularly the case for slots where we dynamically adjust them, and
// high contention can suddenly result in high slot utilization even while
// cpu utilization stays low. We don't want to artificially bottleneck
// request processing when we are in this slow CPULoad ticks regime since we
// can't adjust slots or refill tokens fast enough. So we explicitly tell
// the granters to not do token or slot enforcement.
skipEnforcement := samplePeriod > time.Millisecond
coord.granters[SQLKVResponseWork].(*tokenGranter).refillBurstTokens(skipEnforcement)
coord.granters[SQLSQLResponseWork].(*tokenGranter).refillBurstTokens(skipEnforcement)
if coord.granters[KVWork] != nil {
if !coord.testingDisableSkipEnforcement {
kvg := coord.granters[KVWork].(*kvGranter)
kvg.skipSlotEnforcement = skipEnforcement
}
}
if coord.grantChainActive && !coord.tryTerminateGrantChain() {
return
}
coord.tryGrant()
}
// tryGet is called by granter.tryGet with the WorkKind.
func (coord *GrantCoordinator) tryGet(workKind WorkKind) bool {
coord.mu.Lock()
defer coord.mu.Unlock()
// It is possible that a grant chain is active, and has not yet made its way
// to this workKind. So it may be more reasonable to queue. But we have some
// concerns about incurring the delay of multiple goroutine context switches
// so we ignore this case.
res := coord.granters[workKind].tryGetLocked()
switch res {
case grantSuccess:
// Grant chain may be active, but it did not get in the way of this grant,
// and the effect of this grant in terms of overload will be felt by the
// grant chain.
return true
case grantFailDueToSharedResource:
// This could be a transient overload, that may not be noticed by the
// grant chain. We don't want it to continue granting to lower priority
// WorkKinds, while a higher priority one is waiting, so we terminate it.
if coord.grantChainActive && coord.grantChainIndex >= workKind {
coord.tryTerminateGrantChain()
}
return false
case grantFailLocal:
return false
default:
panic(errors.AssertionFailedf("unknown grantResult"))