-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
granter.go
2584 lines (2388 loc) · 107 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/roachpb"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/util/admission/admissionpb"
"github.com/cockroachdb/cockroach/pkg/util/humanizeutil"
"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/logtags"
"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)
// EnabledSoftSlotGranting can be set to false to disable soft slot granting.
var EnabledSoftSlotGranting = settings.RegisterBoolSetting(
settings.TenantWritable,
"admission.soft_slot_granting.enabled",
"soft slot granting is disabled if this setting is set to false",
true,
)
// MinFlushUtilizationFraction is a lower-bound on the dynamically adjusted
// flush utilization target fraction that attempts to reduce write stalls. Set
// it to a high fraction (>>1, e.g. 10), to effectively disable flush based
// tokens.
//
// The target fraction is used to multiply the (measured) peak flush rate, to
// compute the flush tokens. For example, if the dynamic target fraction (for
// which this setting provides a lower bound) is currently 0.75, then
// 0.75*peak-flush-rate will be used to set the flush tokens. The lower bound
// of 0.5 should not need to be tuned, and should not be tuned without
// consultation with a domain expert. If the storage.write-stall-nanos
// indicates significant write stalls, and the granter logs show that the
// dynamic target fraction has already reached the lower bound, one can
// consider lowering it slightly and then observe the effect.
var MinFlushUtilizationFraction = settings.RegisterFloatSetting(
settings.SystemOnly,
"admission.min_flush_util_fraction",
"when computing flush tokens, this fraction is a lower bound on the dynamically "+
"adjusted flush utilization target fraction that attempts to reduce write stalls. Set "+
"it to a high fraction (>>1, e.g. 10), to disable flush based tokens. The dynamic "+
"target fraction is used to multiply the (measured) peak flush rate, to compute the flush "+
"tokens. If the storage.write-stall-nanos indicates significant write stalls, and the granter "+
"logs show that the dynamic target fraction has already reached the lower bound, one can "+
"consider lowering it slightly (after consultation with domain experts)", 0.5,
settings.PositiveFloat)
// 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 a single queued
// request. It returns > 0 if the grant was accepted, else returns 0. 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.
// When accepted, the return value indicates the number of slots/tokens that
// were used.
// REQUIRES: count <= 1 for slots.
granted(grantChainID grantChainID) int64
close()
}
// 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.
//
// StoreGrantCoordinators and its corresponding StoreWorkQueues are a hybrid
// -- they use tokens (as explained later). However, there is useful
// completion information such as how many tokens were actually used, which
// can differ from the up front information, and is utilized to adjust the
// available tokens.
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 slots/tokens for a piece of work
// that has encountered no waiting/queued work. This is the fast path that
// avoids queueing in the requester.
//
// REQUIRES: count > 0. count == 1 for slots.
tryGet(count int64) bool
// returnGrant is called for:
// - returning slots after use.
// - returning tokens when the work did not end up using all the tokens.
// - 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 last case occurs despite the 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 a count > 0, but later
// when the goroutine doing the work noticed that it had been granted, there
// is a possibility that that raced with cancellation.
//
// REQUIRES: count > 0. count == 1 for slots.
returnGrant(count int64)
// tookWithoutPermission informs the granter that a slot or tokens were
// taken unilaterally, without permission. This is useful:
// - Slots: this is useful since 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.
// - Tokens: this is useful when the initial estimated tokens for a unit of
// work turned out to be an underestimate.
//
// REQUIRES: count > 0. count == 1 for slots.
tookWithoutPermission(count int64)
// 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/tokens. 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 Priority.
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(count int64) grantResult
// returnGrantLocked is the real implementation of returnGrant.
returnGrantLocked(count int64)
// tookWithoutPermissionLocked is the real implementation of
// tookWithoutPermission.
tookWithoutPermissionLocked(count int64)
// getPairedRequester returns the requester implementation that this granter
// interacts with.
getPairedRequester() requester
}
// For the cpu-bound slot case we have background activities (like Pebble
// compactions) that would like to utilize additional slots if available (e.g.
// to do concurrent compression of ssblocks). These activities do not want to
// wait for a slot, since they can proceed without the slot at their usual
// slower pace (e.g. without doing concurrent compression). They also are
// sensitive to small overheads in their tight loops, and cannot afford the
// overhead of interacting with admission control at a fine granularity (like
// asking for a slot when compressing each ssblock). A coarse granularity
// interaction causes a delay in returning slots to admission control, and we
// don't want that delay to cause admission delay for normal work. Hence, we
// model slots granted to background activities as "soft-slots". Think of
// regular used slots as "hard-slots", in that we assume that the holder of
// the slot is still "using" it, while a soft-slot is "squishy" and in some
// cases we can pretend that it is not being used. Say we are allowed
// to allocate up to M slots. In this scheme, when allocating a soft-slot
// one must conform to usedSoftSlots+usedSlots <= M, and when allocating
// a regular (hard) slot one must conform to usedSlots <= M.
//
// That is, soft-slots allow for over-commitment until the soft-slots are
// returned, which may mean some additional queueing in the goroutine
// scheduler.
//
// We have another wrinkle in that we do not want to maintain a single M. For
// these optional background activities we desire to do them only when the
// load is low enough. This is because at high load, all work suffers from
// additional queueing in the goroutine scheduler. So we want to make sure
// regular work does not suffer such goroutine scheduler queueing because we
// granted too many soft-slots and caused CPU utilization to be high. So we
// maintain two kinds of M, totalHighLoadSlots and totalModerateLoadSlots.
// totalHighLoadSlots are estimated so as to allow CPU utilization to be high,
// while totalModerateLoadSlots are trying to keep queuing in the goroutine
// scheduler to a lower level. So the revised equations for allocation are:
// - Allocating a soft-slot: usedSoftSlots+usedSlots <= totalModerateLoadSlots
// - Allocating a regular slot: usedSlots <= totalHighLoadSlots
//
// NB: we may in the future add other kinds of background activities that do
// not have a lag in interacting with admission control, but want to schedule
// them only under moderate load. Those activities will be counted in
// usedSlots but when granting a slot to such an activity, the equation will
// be usedSoftSlots+usedSlots <= totalModerateLoadSlots.
//
// That is, let us not confuse that moderate load slot allocation is only for
// soft-slots. Soft-slots are introduced only for squishiness.
//
// slotGranter implements granterWithLockedCalls.
type slotGranter struct {
coord *GrantCoordinator
workKind WorkKind
requester requester
usedSlots int
usedSoftSlots int
totalHighLoadSlots int
totalModerateLoadSlots int
skipSlotEnforcement bool
// 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
usedSlotsMetric *metric.Gauge
usedSoftSlotsMetric *metric.Gauge
}
var _ granterWithLockedCalls = &slotGranter{}
func (sg *slotGranter) getPairedRequester() requester {
return sg.requester
}
func (sg *slotGranter) grantKind() grantKind {
return slot
}
func (sg *slotGranter) tryGet(count int64) bool {
return sg.coord.tryGet(sg.workKind, count)
}
func (sg *slotGranter) tryGetLocked(count int64) grantResult {
if count != 1 {
panic(errors.AssertionFailedf("unexpected count: %d", count))
}
if sg.cpuOverload != nil && sg.cpuOverload.isOverloaded() {
return grantFailDueToSharedResource
}
if sg.usedSlots < sg.totalHighLoadSlots || sg.skipSlotEnforcement {
sg.usedSlots++
sg.usedSlotsMetric.Update(int64(sg.usedSlots))
return grantSuccess
}
if sg.workKind == KVWork {
return grantFailDueToSharedResource
}
return grantFailLocal
}
func (sg *slotGranter) returnGrant(count int64) {
sg.coord.returnGrant(sg.workKind, count)
}
func (sg *slotGranter) tryGetSoftSlots(count int) int {
sg.coord.mu.Lock()
defer sg.coord.mu.Unlock()
spareModerateLoadSlots := sg.totalModerateLoadSlots - sg.usedSoftSlots - sg.usedSlots
if spareModerateLoadSlots <= 0 {
return 0
}
allocatedSlots := count
if allocatedSlots > spareModerateLoadSlots {
allocatedSlots = spareModerateLoadSlots
}
sg.usedSoftSlots += allocatedSlots
sg.usedSoftSlotsMetric.Update(int64(sg.usedSoftSlots))
return allocatedSlots
}
func (sg *slotGranter) returnSoftSlots(count int) {
sg.coord.mu.Lock()
defer sg.coord.mu.Unlock()
sg.usedSoftSlots -= count
sg.usedSoftSlotsMetric.Update(int64(sg.usedSoftSlots))
if sg.usedSoftSlots < 0 {
panic("used soft slots is negative")
}
}
func (sg *slotGranter) returnGrantLocked(count int64) {
if count != 1 {
panic(errors.AssertionFailedf("unexpected count: %d", count))
}
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(count int64) {
sg.coord.tookWithoutPermission(sg.workKind, count)
}
func (sg *slotGranter) tookWithoutPermissionLocked(count int64) {
if count != 1 {
panic(errors.AssertionFailedf("unexpected count: %d", count))
}
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 int64
maxBurstTokens int64
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(count int64) bool {
return tg.coord.tryGet(tg.workKind, count)
}
func (tg *tokenGranter) tryGetLocked(count int64) grantResult {
if tg.cpuOverload != nil && tg.cpuOverload.isOverloaded() {
return grantFailDueToSharedResource
}
if tg.availableBurstTokens > 0 || tg.skipTokenEnforcement {
tg.availableBurstTokens -= count
return grantSuccess
}
return grantFailLocal
}
func (tg *tokenGranter) returnGrant(count int64) {
tg.coord.returnGrant(tg.workKind, count)
}
func (tg *tokenGranter) returnGrantLocked(count int64) {
tg.availableBurstTokens += count
if tg.availableBurstTokens > tg.maxBurstTokens {
tg.availableBurstTokens = tg.maxBurstTokens
}
}
func (tg *tokenGranter) tookWithoutPermission(count int64) {
tg.coord.tookWithoutPermission(tg.workKind, count)
}
func (tg *tokenGranter) tookWithoutPermissionLocked(count int64) {
tg.availableBurstTokens -= count
}
func (tg *tokenGranter) continueGrantChain(grantChainID grantChainID) {
tg.coord.continueGrantChain(tg.workKind, grantChainID)
}
// kvStoreTokenGranter implements granterWithLockedCalls. It is used for
// grants to KVWork to a store, that is limited by IO tokens.
type kvStoreTokenGranter struct {
coord *GrantCoordinator
requester requester
// There is no rate limiting in granting these tokens. That is, they are all
// burst tokens.
availableIOTokens int64
// startingIOTokens is the number of tokens set by
// setAvailableIOTokensLocked. It is used to compute the tokens used, by
// computing startingIOTokens-availableIOTokens.
startingIOTokens int64
ioTokensExhaustedDurationMetric *metric.Counter
exhaustedStart time.Time
writeLM, ingestedLM tokensLinearModel
}
var _ granterWithLockedCalls = &kvStoreTokenGranter{}
var _ granterWithIOTokens = &kvStoreTokenGranter{}
var _ granterWithStoreWriteDone = &kvStoreTokenGranter{}
func (sg *kvStoreTokenGranter) getPairedRequester() requester {
return sg.requester
}
func (sg *kvStoreTokenGranter) grantKind() grantKind {
return token
}
func (sg *kvStoreTokenGranter) tryGet(count int64) bool {
return sg.coord.tryGet(KVWork, count)
}
func (sg *kvStoreTokenGranter) tryGetLocked(count int64) grantResult {
if sg.availableIOTokens > 0 {
sg.subtractTokens(count, false)
return grantSuccess
}
return grantFailLocal
}
func (sg *kvStoreTokenGranter) returnGrant(count int64) {
sg.coord.returnGrant(KVWork, count)
}
func (sg *kvStoreTokenGranter) returnGrantLocked(count int64) {
sg.subtractTokens(-count, false)
}
func (sg *kvStoreTokenGranter) tookWithoutPermission(count int64) {
sg.coord.tookWithoutPermission(KVWork, count)
}
func (sg *kvStoreTokenGranter) tookWithoutPermissionLocked(count int64) {
sg.subtractTokens(count, false)
}
func (sg *kvStoreTokenGranter) subtractTokens(count int64, forceTickMetric bool) {
avail := sg.availableIOTokens
sg.availableIOTokens -= count
if count > 0 && avail > 0 && sg.availableIOTokens <= 0 {
// Transition from > 0 to <= 0.
sg.exhaustedStart = timeutil.Now()
} else if count < 0 && avail <= 0 && (sg.availableIOTokens > 0 || forceTickMetric) {
// Transition from <= 0 to > 0, or forced to tick the metric. The latter
// ensures that if the available tokens stay <= 0, we don't show a sudden
// change in the metric after minutes of exhaustion (we had observed such
// behavior prior to this change).
now := timeutil.Now()
exhaustedMicros := now.Sub(sg.exhaustedStart).Microseconds()
sg.ioTokensExhaustedDurationMetric.Inc(exhaustedMicros)
if sg.availableIOTokens <= 0 {
sg.exhaustedStart = now
}
}
}
func (sg *kvStoreTokenGranter) continueGrantChain(grantChainID grantChainID) {
sg.coord.continueGrantChain(KVWork, grantChainID)
}
func (sg *kvStoreTokenGranter) setAvailableIOTokensLocked(tokens int64) (tokensUsed int64) {
tokensUsed = sg.startingIOTokens - sg.availableIOTokens
// It is possible for availableIOTokens to be negative because of
// tookWithoutPermission or because tryGet will satisfy requests until
// availableIOTokens become <= 0. We want to remember this previous
// over-allocation.
sg.subtractTokens(-tokens, true)
if sg.availableIOTokens > tokens {
// Clamp to tokens.
sg.availableIOTokens = tokens
}
sg.startingIOTokens = tokens
return tokensUsed
}
func (sg *kvStoreTokenGranter) setAdmittedDoneModelsLocked(
writeLM tokensLinearModel, ingestedLM tokensLinearModel,
) {
sg.writeLM = writeLM
sg.ingestedLM = ingestedLM
}
func (sg *kvStoreTokenGranter) storeWriteDone(
originalTokens int64, doneInfo StoreWorkDoneInfo,
) (additionalTokens int64) {
// We don't bother with the *Locked dance through the GrantCoordinator here
// since the grant coordinator doesn't know when to call the tryGrant since
// it does not know whether tokens have become available.
sg.coord.mu.Lock()
exhaustedFunc := func() bool {
return sg.availableIOTokens <= 0
}
wasExhausted := exhaustedFunc()
actualTokens :=
int64(float64(doneInfo.WriteBytes)*sg.writeLM.multiplier) + sg.writeLM.constant +
int64(float64(doneInfo.IngestedBytes)*sg.ingestedLM.multiplier) + sg.ingestedLM.constant
additionalTokensNeeded := actualTokens - originalTokens
sg.subtractTokens(additionalTokensNeeded, false)
if additionalTokensNeeded < 0 {
isExhausted := exhaustedFunc()
if wasExhausted && !isExhausted {
sg.coord.tryGrant()
}
}
sg.coord.mu.Unlock()
return additionalTokensNeeded
}
// 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
// RunnableAlphaOverride is used to override the alpha value used to
// compute the ewma of the runnable goroutine counts. It is only used
// during testing. A 0 value indicates that there is no override.
RunnableAlphaOverride float64
SQLKVResponseBurstTokens int64
SQLSQLResponseBurstTokens int64
SQLStatementLeafStartWorkSlots int
SQLStatementRootStartWorkSlots int
TestingDisableSkipEnforcement bool
Settings *cluster.Settings
// Only non-nil for tests.
makeRequesterFunc makeRequesterFunc
makeStoreRequesterFunc makeStoreRequesterFunc
}
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{
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
type makeStoreRequesterFunc func(
_ log.AmbientContext, granter granterWithStoreWriteDone, settings *cluster.Settings,
opts workQueueOptions) storeRequester
// 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,
totalModerateSlotsMetric: metrics.KVTotalModerateSlots,
moderateSlotsClamp: opts.MaxCPUSlots,
runnableAlphaOverride: opts.RunnableAlphaOverride,
}
coord := &GrantCoordinator{
ambientCtx: ambientCtx,
settings: st,
cpuOverloadIndicator: kvSlotAdjuster,
cpuLoadListener: kvSlotAdjuster,
useGrantChains: true,
testingDisableSkipEnforcement: opts.TestingDisableSkipEnforcement,
numProcs: 1,
grantChainID: 1,
}
kvg := &slotGranter{
coord: coord,
workKind: KVWork,
totalHighLoadSlots: opts.MinCPUSlots,
totalModerateLoadSlots: opts.MinCPUSlots,
usedSlotsMetric: metrics.KVUsedSlots,
usedSoftSlotsMetric: metrics.KVUsedSoftSlots,
}
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,
totalHighLoadSlots: 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,
totalHighLoadSlots: 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)
makeStoreRequester := makeStoreWorkQueue
if opts.makeStoreRequesterFunc != nil {
makeStoreRequester = opts.makeStoreRequesterFunc
}
storeCoordinators := &StoreGrantCoordinators{
settings: st,
makeStoreRequesterFunc: makeStoreRequester,
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,