-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
tenant_side_test.go
1611 lines (1431 loc) · 50.5 KB
/
tenant_side_test.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.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package tenantcostclient_test
import (
"bytes"
"context"
gosql "database/sql"
"fmt"
"io"
"net/http"
"net/http/httptest"
"reflect"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
_ "github.com/cockroachdb/cockroach/pkg/ccl" // ccl init hooks
"github.com/cockroachdb/cockroach/pkg/ccl/changefeedccl"
"github.com/cockroachdb/cockroach/pkg/ccl/multitenantccl/tenantcostclient"
"github.com/cockroachdb/cockroach/pkg/cloud"
"github.com/cockroachdb/cockroach/pkg/cloud/nodelocal"
"github.com/cockroachdb/cockroach/pkg/cloud/nullsink"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobstest"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/kvtenant"
"github.com/cockroachdb/cockroach/pkg/kv/kvpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/multitenant"
"github.com/cockroachdb/cockroach/pkg/multitenant/multitenantio"
"github.com/cockroachdb/cockroach/pkg/multitenant/tenantcostmodel"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/systemschema"
"github.com/cockroachdb/cockroach/pkg/sql/distsql"
"github.com/cockroachdb/cockroach/pkg/sql/execinfra"
"github.com/cockroachdb/cockroach/pkg/sql/sqlliveness"
"github.com/cockroachdb/cockroach/pkg/sql/sqlliveness/slbase"
"github.com/cockroachdb/cockroach/pkg/sql/stats"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/datapathutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/ctxgroup"
"github.com/cockroachdb/cockroach/pkg/util/ioctx"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/metric"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/datadriven"
"github.com/cockroachdb/errors"
"github.com/stretchr/testify/require"
yaml "gopkg.in/yaml.v2"
)
// TestDataDriven tests the tenant-side cost controller in an isolated setting.
func TestDataDriven(t *testing.T) {
defer leaktest.AfterTest(t)()
datadriven.Walk(t, datapathutils.TestDataPath(t), func(t *testing.T, path string) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
var ts testState
ts.start(t)
defer ts.stop()
datadriven.RunTest(t, path, func(t *testing.T, d *datadriven.TestData) string {
args := parseArgs(t, d)
fn, ok := testStateCommands[d.Cmd]
if !ok {
d.Fatalf(t, "unknown command %s", d.Cmd)
}
return fn(&ts, t, d, args)
})
})
}
type testState struct {
timeSrc *timeutil.ManualTime
settings *cluster.Settings
stopper *stop.Stopper
provider *testProvider
controller multitenant.TenantSideCostController
eventWait *eventWaiter
// external usage values, accessed using atomic.
cpuUsage time.Duration
pgwireEgressBytes int64
requestDoneCh map[string]chan struct{}
}
var eventTypeStr = map[tenantcostclient.TestEventType]string{
tenantcostclient.TickProcessed: "tick",
tenantcostclient.LowRUNotification: "low-ru",
tenantcostclient.TokenBucketResponseProcessed: "token-bucket-response",
tenantcostclient.TokenBucketResponseError: "token-bucket-response-error",
}
const timeFormat = "15:04:05.000"
var t0 = time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC)
const timeout = 10 * time.Second
func (ts *testState) start(t *testing.T) {
ctx := context.Background()
ts.requestDoneCh = make(map[string]chan struct{})
ts.timeSrc = timeutil.NewManualTime(t0)
ts.eventWait = newEventWaiter(ts.timeSrc)
ts.settings = cluster.MakeTestingClusterSettings()
// Fix settings so that the defaults can be changed without updating the test.
tenantcostclient.TargetPeriodSetting.Override(ctx, &ts.settings.SV, 10*time.Second)
tenantcostclient.CPUUsageAllowance.Override(ctx, &ts.settings.SV, 10*time.Millisecond)
tenantcostclient.InitialRequestSetting.Override(ctx, &ts.settings.SV, 10000)
ts.stopper = stop.NewStopper()
var err error
ts.provider = newTestProvider()
ts.controller, err = tenantcostclient.TestingTenantSideCostController(
ts.settings,
roachpb.MustMakeTenantID(5),
ts.provider,
ts.timeSrc,
ts.eventWait,
)
if err != nil {
t.Fatal(err)
}
externalUsageFn := func(context.Context) multitenant.ExternalUsage {
return multitenant.ExternalUsage{
CPUSecs: time.Duration(atomic.LoadInt64((*int64)(&ts.cpuUsage))).Seconds(),
PGWireEgressBytes: uint64(atomic.LoadInt64(&ts.pgwireEgressBytes)),
}
}
nextLiveInstanceIDFn := func(ctx context.Context) base.SQLInstanceID {
return 0
}
instanceID := base.SQLInstanceID(1)
sessionID := sqlliveness.SessionID("foo")
if err := ts.controller.Start(
ctx, ts.stopper, instanceID, sessionID, externalUsageFn, nextLiveInstanceIDFn,
); err != nil {
t.Fatal(err)
}
// Wait for main loop to start in order to avoid race conditions where a test
// starts before the main loop has been initialized.
if !ts.eventWait.WaitForEvent(tenantcostclient.MainLoopStarted) {
t.Fatal("did not receive event MainLoopStarted")
}
}
func (ts *testState) stop() {
ts.stopper.Stop(context.Background())
}
type cmdArgs struct {
count int64
bytes int64
repeat int64
label string
wait bool
networkCost float64
}
func parseBytesVal(arg datadriven.CmdArg) (int64, error) {
if len(arg.Vals) != 1 {
return 0, errors.Newf("expected one value for bytes")
}
val, err := strconv.ParseInt(arg.Vals[0], 10, 64)
if err != nil {
return 0, errors.Wrap(err, "could not convert value to integer")
}
return val, nil
}
func parseArgs(t *testing.T, d *datadriven.TestData) cmdArgs {
var res cmdArgs
res.count = 1
for _, args := range d.CmdArgs {
switch args.Key {
case "count":
if len(args.Vals) != 1 {
d.Fatalf(t, "expected one value for count")
}
val, err := strconv.Atoi(args.Vals[0])
if err != nil {
d.Fatalf(t, "invalid count value")
}
res.count = int64(val)
case "bytes":
v, err := parseBytesVal(args)
if err != nil {
d.Fatalf(t, err.Error())
}
res.bytes = v
case "repeat":
if len(args.Vals) != 1 {
d.Fatalf(t, "expected one value for repeat")
}
val, err := strconv.Atoi(args.Vals[0])
if err != nil {
d.Fatalf(t, "invalid repeat value")
}
res.repeat = int64(val)
case "label":
if len(args.Vals) != 1 || args.Vals[0] == "" {
d.Fatalf(t, "label requires a value")
}
res.label = args.Vals[0]
case "wait":
if len(args.Vals) != 1 {
d.Fatalf(t, "expected one value for wait")
}
switch args.Vals[0] {
case "true":
res.wait = true
case "false":
default:
d.Fatalf(t, "invalid wait value")
}
case "networkCost":
if len(args.Vals) != 1 {
d.Fatalf(t, "expected one value for networkCost")
}
val, err := strconv.ParseFloat(args.Vals[0], 64)
if err != nil {
d.Fatalf(t, "invalid networkCost value")
}
res.networkCost = val
default:
d.Fatalf(t, "uknown command: '%s'", args.Key)
}
}
return res
}
var testStateCommands = map[string]func(
*testState, *testing.T, *datadriven.TestData, cmdArgs,
) string{
"read": (*testState).read,
"write": (*testState).write,
"await": (*testState).await,
"not-completed": (*testState).notCompleted,
"advance": (*testState).advance,
"wait-for-event": (*testState).waitForEvent,
"timers": (*testState).timers,
"cpu": (*testState).cpu,
"pgwire-egress": (*testState).pgwireEgress,
"external-egress": (*testState).externalEgress,
"external-ingress": (*testState).externalIngress,
"enable-external-ru-accounting": (*testState).enableRUAccounting,
"disable-external-ru-accounting": (*testState).disableRUAccounting,
"usage": (*testState).usage,
"metrics": (*testState).metrics,
"configure": (*testState).configure,
"token-bucket": (*testState).tokenBucket,
"unblock-request": (*testState).unblockRequest,
}
// runOperation invokes the given operation function on a background goroutine.
// If label is empty, runOperation will synchronously wait for the operation to
// complete. Otherwise, it will enter the label in the requestDoneCh map so that
// the caller can wait for it to complete.
func (ts *testState) runOperation(t *testing.T, d *datadriven.TestData, label string, op func()) {
runInBackground := func(op func()) chan struct{} {
ch := make(chan struct{})
go func() {
op()
close(ch)
}()
return ch
}
if label != "" {
// Async case.
if _, ok := ts.requestDoneCh[label]; ok {
d.Fatalf(t, "label %v already in use", label)
}
ts.requestDoneCh[label] = runInBackground(op)
} else {
// Sync case.
select {
case <-runInBackground(op):
case <-time.After(timeout):
d.Fatalf(t, "request timed out")
}
}
}
// request simulates processing a read or write. If a label is provided, the
// request is started in the background.
func (ts *testState) request(
t *testing.T, d *datadriven.TestData, isWrite bool, args cmdArgs,
) string {
ctx := context.Background()
repeat := args.repeat
if repeat == 0 {
repeat = 1
}
var writeCount, readCount, writeBytes, readBytes int64
var writeNetworkCost, readNetworkCost tenantcostmodel.NetworkCost
if isWrite {
writeCount = args.count
writeBytes = args.bytes
writeNetworkCost = tenantcostmodel.NetworkCost(args.networkCost)
} else {
readCount = args.count
readBytes = args.bytes
readNetworkCost = tenantcostmodel.NetworkCost(args.networkCost)
}
reqInfo := tenantcostmodel.TestingRequestInfo(1, writeCount, writeBytes, writeNetworkCost)
respInfo := tenantcostmodel.TestingResponseInfo(!isWrite, readCount, readBytes, readNetworkCost)
for ; repeat > 0; repeat-- {
ts.runOperation(t, d, args.label, func() {
if err := ts.controller.OnRequestWait(ctx); err != nil {
t.Errorf("OnRequestWait error: %v", err)
}
if err := ts.controller.OnResponseWait(ctx, reqInfo, respInfo); err != nil {
t.Errorf("OnResponseWait error: %v", err)
}
})
}
return ""
}
func (ts *testState) externalIngress(t *testing.T, _ *datadriven.TestData, args cmdArgs) string {
usage := multitenant.ExternalIOUsage{IngressBytes: args.bytes}
if err := ts.controller.OnExternalIOWait(context.Background(), usage); err != nil {
t.Errorf("OnExternalIOWait error: %s", err)
}
return ""
}
func (ts *testState) externalEgress(t *testing.T, d *datadriven.TestData, args cmdArgs) string {
ctx := context.Background()
usage := multitenant.ExternalIOUsage{EgressBytes: args.bytes}
ts.runOperation(t, d, args.label, func() {
if err := ts.controller.OnExternalIOWait(ctx, usage); err != nil {
t.Errorf("OnExternalIOWait error: %s", err)
}
})
return ""
}
func (ts *testState) enableRUAccounting(_ *testing.T, _ *datadriven.TestData, _ cmdArgs) string {
tenantcostclient.ExternalIORUAccountingMode.Override(context.Background(), &ts.settings.SV, "on")
return ""
}
func (ts *testState) disableRUAccounting(_ *testing.T, _ *datadriven.TestData, _ cmdArgs) string {
tenantcostclient.ExternalIORUAccountingMode.Override(context.Background(), &ts.settings.SV, "off")
return ""
}
// read simulates processing a read. If a label is provided, the request is
// started in the background.
func (ts *testState) read(t *testing.T, d *datadriven.TestData, args cmdArgs) string {
return ts.request(t, d, false /* isWrite */, args)
}
// write simulates processing a write. If a label is provided, the request is
// started in the background.
func (ts *testState) write(t *testing.T, d *datadriven.TestData, args cmdArgs) string {
return ts.request(t, d, true /* isWrite */, args)
}
// await waits until the given request completes.
func (ts *testState) await(t *testing.T, d *datadriven.TestData, args cmdArgs) string {
ch, ok := ts.requestDoneCh[args.label]
if !ok {
d.Fatalf(t, "unknown label %q", args.label)
}
select {
case <-ch:
case <-time.After(timeout):
d.Fatalf(t, "await(%q) timed out", args.label)
}
delete(ts.requestDoneCh, args.label)
return ""
}
// notCompleted verifies that the request with the given label has not completed
// yet.
func (ts *testState) notCompleted(t *testing.T, d *datadriven.TestData, args cmdArgs) string {
ch, ok := ts.requestDoneCh[args.label]
if !ok {
d.Fatalf(t, "unknown label %v", args.label)
}
// Sleep a bit to give a chance for a bug to manifest.
time.Sleep(1 * time.Millisecond)
select {
case <-ch:
d.Fatalf(t, "request %v completed unexpectedly", args.label)
default:
}
return ""
}
// advance advances the clock by the provided duration and returns the new
// current time.
//
// advance
// 2s
// ----
// 00:00:02.000
//
// An optional "wait" argument will cause advance to block until it receives a
// tick event, indicating the clock change has been processed.
func (ts *testState) advance(t *testing.T, d *datadriven.TestData, args cmdArgs) string {
ctx := context.Background()
dur, err := time.ParseDuration(d.Input)
if err != nil {
d.Fatalf(t, "failed to parse input as duration: %v", err)
}
if log.ExpensiveLogEnabled(ctx, 1) {
log.Infof(ctx, "Advance %v", dur)
}
ts.timeSrc.Advance(dur)
if args.wait {
// Wait for tick event.
ts.waitForEvent(t, &datadriven.TestData{Input: "tick"}, cmdArgs{})
}
return ts.timeSrc.Now().Format(timeFormat)
}
// waitForEvent waits until the tenant controller reports the given event
// type(s), at the current time.
func (ts *testState) waitForEvent(t *testing.T, d *datadriven.TestData, _ cmdArgs) string {
typs := make(map[string]tenantcostclient.TestEventType)
for ev, evStr := range eventTypeStr {
typs[evStr] = ev
}
typ, ok := typs[d.Input]
if !ok {
d.Fatalf(t, "unknown event type %s (supported types: %v)", d.Input, typs)
}
if !ts.eventWait.WaitForEvent(typ) {
d.Fatalf(t, "did not receive event %s", d.Input)
}
return ""
}
// unblockRequest resumes a token bucket request that was blocked by the
// "blockRequest" configuration option.
func (ts *testState) unblockRequest(t *testing.T, _ *datadriven.TestData, _ cmdArgs) string {
ts.provider.unblockRequest(t)
return ""
}
// timers waits for the set of open timers to match the expected output.
// timers is critical to avoid synchronization problems in testing. The command
// outputs the set of timers in increasing order with each timer's deadline on
// its own line.
//
// The following example would wait for there to be two outstanding timers at
// 00:00:01.000 and 00:00:02.000.
//
// timers
// ----
// 00:00:01.000
// 00:00:02.000
func (ts *testState) timers(t *testing.T, d *datadriven.TestData, _ cmdArgs) string {
// If we are rewriting the test, just sleep a bit before returning the
// timers.
if d.Rewrite {
time.Sleep(time.Second)
return timesToString(ts.timeSrc.Timers())
}
exp := strings.TrimSpace(d.Expected)
if err := testutils.SucceedsWithinError(func() error {
got := timesToString(ts.timeSrc.Timers())
if got != exp {
return errors.Errorf("got: %q, exp: %q", got, exp)
}
return nil
}, timeout); err != nil {
d.Fatalf(t, "failed to find expected timers: %v", err)
}
return d.Expected
}
func timesToString(times []time.Time) string {
strs := make([]string, len(times))
for i, t := range times {
strs[i] = t.Format(timeFormat)
}
return strings.Join(strs, "\n")
}
// configure the test provider.
func (ts *testState) configure(t *testing.T, d *datadriven.TestData, _ cmdArgs) string {
var cfg testProviderConfig
if err := yaml.UnmarshalStrict([]byte(d.Input), &cfg); err != nil {
d.Fatalf(t, "failed to parse request yaml: %v", err)
}
ts.provider.configure(cfg)
return ""
}
// tokenBucket dumps the current state of the tenant's token bucket.
func (ts *testState) tokenBucket(*testing.T, *datadriven.TestData, cmdArgs) string {
return tenantcostclient.TestingTokenBucketString(ts.controller)
}
// cpu adds CPU usage which will be observed by the controller on the next main
// loop tick.
func (ts *testState) cpu(t *testing.T, d *datadriven.TestData, _ cmdArgs) string {
duration, err := time.ParseDuration(d.Input)
if err != nil {
d.Fatalf(t, "error parsing cpu duration: %v", err)
}
atomic.AddInt64((*int64)(&ts.cpuUsage), int64(duration))
return ""
}
// pgwire adds PGWire egress usage which will be observed by the controller on the next
// main loop tick.
func (ts *testState) pgwireEgress(t *testing.T, d *datadriven.TestData, _ cmdArgs) string {
bytes, err := strconv.Atoi(d.Input)
if err != nil {
d.Fatalf(t, "error parsing pgwire bytes value: %v", err)
}
atomic.AddInt64(&ts.pgwireEgressBytes, int64(bytes))
return ""
}
// usage prints out the latest consumption. Callers are responsible for
// triggering calls to the token bucket provider and waiting for responses.
func (ts *testState) usage(*testing.T, *datadriven.TestData, cmdArgs) string {
c := ts.provider.consumption()
return fmt.Sprintf(""+
"RU: %.2f\n"+
"KVRU: %.2f\n"+
"CrossRegionNetworkRU: %.2f\n"+
"Reads: %d requests in %d batches (%d bytes)\n"+
"Writes: %d requests in %d batches (%d bytes)\n"+
"SQL Pods CPU seconds: %.2f\n"+
"PGWire egress: %d bytes\n"+
"ExternalIO egress: %d bytes\n"+
"ExternalIO ingress: %d bytes\n",
c.RU,
c.KVRU,
c.CrossRegionNetworkRU,
c.ReadRequests,
c.ReadBatches,
c.ReadBytes,
c.WriteRequests,
c.WriteBatches,
c.WriteBytes,
c.SQLPodsCPUSeconds,
c.PGWireEgressBytes,
c.ExternalIOEgressBytes,
c.ExternalIOIngressBytes,
)
}
// metrics prints out cost client related consumption metrics. Callers are
// responsible for waiting on tick events since that is when metrics will be
// updated.
func (ts *testState) metrics(*testing.T, *datadriven.TestData, cmdArgs) string {
metricNames := []string{
"tenant.sql_usage.request_units",
"tenant.sql_usage.kv_request_units",
"tenant.sql_usage.read_batches",
"tenant.sql_usage.read_requests",
"tenant.sql_usage.read_bytes",
"tenant.sql_usage.write_batches",
"tenant.sql_usage.write_requests",
"tenant.sql_usage.write_bytes",
"tenant.sql_usage.sql_pods_cpu_seconds",
"tenant.sql_usage.pgwire_egress_bytes",
"tenant.sql_usage.external_io_ingress_bytes",
"tenant.sql_usage.external_io_egress_bytes",
"tenant.sql_usage.cross_region_network_ru",
}
state := make(map[string]interface{})
v := reflect.ValueOf(ts.controller.Metrics()).Elem()
for i := 0; i < v.NumField(); i++ {
switch typ := v.Field(i).Interface().(type) {
case metric.Iterable:
typ.Inspect(func(v interface{}) {
switch it := v.(type) {
case *metric.Counter:
state[typ.GetName()] = it.Count()
case *metric.CounterFloat64:
state[typ.GetName()] = fmt.Sprintf("%.2f", it.Count())
}
})
}
}
var output string
for _, name := range metricNames {
v, ok := state[name]
if !ok {
panic(fmt.Sprintf("missing data for metric %q", name))
}
output += fmt.Sprintf("%s: %v\n", name, v)
}
return output
}
type event struct {
time time.Time
typ tenantcostclient.TestEventType
}
type eventWaiter struct {
timeSrc *timeutil.ManualTime
ch chan event
}
var _ tenantcostclient.TestInstrumentation = (*eventWaiter)(nil)
func newEventWaiter(timeSrc *timeutil.ManualTime) *eventWaiter {
return &eventWaiter{timeSrc: timeSrc, ch: make(chan event, 10000)}
}
// Event implements the TestInstrumentation interface.
func (ew *eventWaiter) Event(now time.Time, typ tenantcostclient.TestEventType) {
ev := event{
time: now,
typ: typ,
}
select {
case ew.ch <- ev:
if testing.Verbose() {
log.Infof(context.Background(), "event %s at %s\n",
eventTypeStr[typ], now.Format(timeFormat))
}
default:
panic("events channel full")
}
}
// WaitForEvent returns true if it receives the given event type at the current
// time. If it fails to do this before timeout, it returns false.
func (ew *eventWaiter) WaitForEvent(typ tenantcostclient.TestEventType) bool {
now := ew.timeSrc.Now()
for {
select {
case ev := <-ew.ch:
if ev.time == now && ev.typ == typ {
return true
}
// Else drop the event.
case <-time.After(timeout):
return false
}
}
}
// testProvider is a testing implementation of kvtenant.TokenBucketProvider,
type testProvider struct {
mu struct {
syncutil.Mutex
consumption kvpb.TenantConsumption
lastSeqNum int64
cfg testProviderConfig
}
recvOnRequest chan struct{}
sendOnRequest chan struct{}
}
type testProviderConfig struct {
// If zero, the provider always grants RUs immediately. If positive, the
// provider grants RUs at this rate. If negative, the provider never grants
// RUs.
Throttle float64 `yaml:"throttle"`
// If set, the provider always errors out.
ProviderError bool `yaml:"error"`
// If set, the provider blocks after receiving each TokenBucket request and
// waits until unblockRequest is called.
ProviderBlock bool `yaml:"block"`
FallbackRate float64 `yaml:"fallback_rate"`
}
var _ kvtenant.TokenBucketProvider = (*testProvider)(nil)
func newTestProvider() *testProvider {
return &testProvider{
recvOnRequest: make(chan struct{}),
sendOnRequest: make(chan struct{}),
}
}
func (tp *testProvider) configure(cfg testProviderConfig) {
tp.mu.Lock()
defer tp.mu.Unlock()
tp.mu.cfg = cfg
}
// waitForRequest waits until the next TokenBucket request.
func (tp *testProvider) waitForRequest(t *testing.T) {
t.Helper()
// Try to send through the unbuffered channel, which blocks until TokenBucket
// is called.
select {
case tp.recvOnRequest <- struct{}{}:
case <-time.After(timeout):
t.Fatal("did not receive request")
}
}
func (tp *testProvider) consumption() kvpb.TenantConsumption {
tp.mu.Lock()
defer tp.mu.Unlock()
return tp.mu.consumption
}
// waitForConsumption waits for the next TokenBucket request and returns the
// total consumption.
func (tp *testProvider) waitForConsumption(t *testing.T) kvpb.TenantConsumption {
tp.waitForRequest(t)
// it is possible that the TokenBucket request was in the process of being
// prepared; we have to wait for another one to make sure the latest
// consumption is incorporated.
tp.waitForRequest(t)
return tp.consumption()
}
// unblockRequest unblocks a TokenBucket request that was blocked by the "block"
// configuration option. This is used to test race conditions.
func (tp *testProvider) unblockRequest(t *testing.T) {
t.Helper()
// Try to receive through the unbuffered channel, which blocks until
// TokenBucket sends.
select {
case <-tp.sendOnRequest:
case <-time.After(timeout):
t.Fatal("did not receive request")
}
}
// TokenBucket implements the kvtenant.TokenBucketProvider interface.
func (tp *testProvider) TokenBucket(
_ context.Context, in *kvpb.TokenBucketRequest,
) (*kvpb.TokenBucketResponse, error) {
tp.mu.Lock()
defer tp.mu.Unlock()
select {
case <-tp.recvOnRequest:
default:
}
if in.SeqNum <= tp.mu.lastSeqNum {
panic("non-increasing sequence number")
}
tp.mu.lastSeqNum = in.SeqNum
if tp.mu.cfg.ProviderError {
return nil, errors.New("injected error")
}
if tp.mu.cfg.ProviderBlock {
// Block until unblockRequest is called.
select {
case tp.sendOnRequest <- struct{}{}:
case <-time.After(timeout):
return nil, errors.New("TokenBucket was never unblocked")
}
}
tp.mu.consumption.Add(&in.ConsumptionSinceLastRequest)
res := &kvpb.TokenBucketResponse{}
rate := tp.mu.cfg.Throttle
if rate >= 0 {
res.GrantedRU = in.RequestedRU
if rate > 0 {
res.TrickleDuration = time.Duration(in.RequestedRU / rate * float64(time.Second))
if res.TrickleDuration > in.TargetRequestPeriod {
res.GrantedRU *= in.TargetRequestPeriod.Seconds() / res.TrickleDuration.Seconds()
res.TrickleDuration = in.TargetRequestPeriod
}
}
}
res.FallbackRate = tp.mu.cfg.FallbackRate
return res, nil
}
// TestWaitingRU verifies that multiple concurrent requests that stack up in the
// quota pool are reflected in AvailableRU.
func TestWaitingRU(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
// Disable CPU consumption so that it doesn't interfere with test.
st := cluster.MakeTestingClusterSettings()
tenantcostclient.CPUUsageAllowance.Override(ctx, &st.SV, time.Second)
testProvider := newTestProvider()
testProvider.configure(testProviderConfig{ProviderError: true})
tenantID := serverutils.TestTenantID()
timeSource := timeutil.NewManualTime(t0)
eventWait := newEventWaiter(timeSource)
ctrl, err := tenantcostclient.TestingTenantSideCostController(
st, tenantID, testProvider, timeSource, eventWait)
require.NoError(t, err)
// Immediately consume the initial 5K RUs.
require.NoError(t, ctrl.OnResponseWait(ctx,
tenantcostmodel.TestingRequestInfo(1, 1, 5117952, 0), tenantcostmodel.ResponseInfo{}))
stopper := stop.NewStopper()
defer stopper.Stop(ctx)
externalUsage := func(ctx context.Context) multitenant.ExternalUsage {
return multitenant.ExternalUsage{}
}
nextLiveInstanceID := func(ctx context.Context) base.SQLInstanceID { return 2 }
require.NoError(t, ctrl.Start(
ctx, stopper, 1, "test", externalUsage, nextLiveInstanceID))
// Wait for the initial token bucket response.
require.True(t, eventWait.WaitForEvent(tenantcostclient.TokenBucketResponseError))
// Send 20 KV requests for 1K RU each.
const count = 20
const fillRate = 100
req := tenantcostmodel.TestingRequestInfo(1, 1, 1021952, 0)
resp := tenantcostmodel.TestingResponseInfo(false, 0, 0, 0)
testutils.SucceedsWithin(t, func() error {
// Refill the token bucket at a fixed 100 RU/s so that we can limit
// non-determinism in the test.
tenantcostclient.TestingSetRate(ctrl, fillRate)
var doneCount int64
for i := 0; i < count; i++ {
require.NoError(t, ctrl.OnRequestWait(ctx))
}
for i := 0; i < count; i++ {
go func(i int) {
require.NoError(t, ctrl.OnResponseWait(ctx, req, resp))
atomic.AddInt64(&doneCount, 1)
}(i)
}
// Allow some responses to queue up before refilling the available RUs.
time.Sleep(time.Millisecond)
// If available RUs drop below -1K, then multiple responses must be waiting.
succeeded := false
for i := 0; i < count; i++ {
available := tenantcostclient.TestingAvailableRU(ctrl)
if available < -1000 {
succeeded = true
}
timeSource.Advance(10 * time.Second)
require.True(t, eventWait.WaitForEvent(tenantcostclient.TickProcessed))
}
// Wait for all background goroutines to finish. It's necessary to
// advance time while waiting in order to resolve a race condition: the
// quota pool gets a "tryAgainAfter" value that gets added to the current
// time in order to set a retry timer. However, the current time might be
// updated at any instant by the foreground goroutine. Therefore, it's
// possible for there to be sufficient tokens in the bucket, and yet have
// one or more background goroutines waiting for them.
testutils.SucceedsWithin(t, func() error {
if atomic.LoadInt64(&doneCount) == count {
return nil
}
// Zero out bucket fill rate so that advancing time does not grant
// new tokens.
tenantcostclient.TestingSetRate(ctrl, 0)
timeSource.Advance(10 * time.Second)
time.Sleep(time.Millisecond)
return errors.Errorf("waiting for background goroutines to finish (now=%v, timers=%v)",
timeSource.Now(), timesToString(timeSource.Timers()))
}, timeout)
const allowedDelta = 0.01
available := tenantcostclient.TestingAvailableRU(ctrl)
if succeeded {
require.InDelta(t, 0, float64(available), allowedDelta)
return nil
}
return errors.Errorf("RUs did not drop below 1K: %0.2f", available)
}, 2*time.Minute)
}
// TestConsumption verifies consumption reporting from a tenant server process.
func TestConsumption(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
hostServer := serverutils.StartServerOnly(t, base.TestServerArgs{DefaultTestTenant: base.TestControlsTenantsExplicitly})
defer hostServer.Stopper().Stop(context.Background())
const targetPeriod = time.Millisecond
st := cluster.MakeTestingClusterSettings()
tenantcostclient.TargetPeriodSetting.Override(context.Background(), &st.SV, targetPeriod)
tenantcostclient.CPUUsageAllowance.Override(context.Background(), &st.SV, 0)
testProvider := newTestProvider()
_, tenantDB := serverutils.StartTenant(t, hostServer, base.TestTenantArgs{
TenantID: serverutils.TestTenantID(),
Settings: st,
TestingKnobs: base.TestingKnobs{
TenantTestingKnobs: &sql.TenantTestingKnobs{
OverrideTokenBucketProvider: func(kvtenant.TokenBucketProvider) kvtenant.TokenBucketProvider {
return testProvider
},
},
},
})
r := sqlutils.MakeSQLRunner(tenantDB)
// Create a secondary index to ensure that writes to both indexes are
// recorded in metrics.
r.Exec(t, "CREATE TABLE t (v STRING, w STRING, INDEX (w, v))")
// Do some writes and reads and check the reported consumption. Repeat the
// test a few times, since background requests can trick the test into
// passing.
for repeat := 0; repeat < 5; repeat++ {
beforeWrite := testProvider.waitForConsumption(t)
r.Exec(t, "INSERT INTO t (v) SELECT repeat('1234567890', 1024) FROM generate_series(1, 10) AS g(i)")
const expectedBytes = 10 * 10 * 1024
// Try a few times because background activity can trigger bucket
// requests before the test query does.
testutils.SucceedsSoon(t, func() error {
afterWrite := testProvider.waitForConsumption(t)
delta := afterWrite
delta.Sub(&beforeWrite)
if delta.WriteBatches < 1 || delta.WriteRequests < 2 || delta.WriteBytes < expectedBytes*2 {
return errors.Newf("usage after write: %s", delta.String())
}
return nil
})
beforeRead := testProvider.waitForConsumption(t)
r.QueryStr(t, "SELECT min(v) FROM t")
// Try a few times because background activity can trigger bucket
// requests before the test query does.
testutils.SucceedsSoon(t, func() error {
afterRead := testProvider.waitForConsumption(t)
delta := afterRead
delta.Sub(&beforeRead)
if delta.ReadBatches < 1 || delta.ReadRequests < 1 || delta.ReadBytes < expectedBytes {
return errors.Newf("usage after read: %s", delta.String())
}
return nil
})
r.Exec(t, "DELETE FROM t WHERE true")
}
// Make sure some CPU usage is reported.
testutils.SucceedsSoon(t, func() error {
c := testProvider.waitForConsumption(t)
if c.SQLPodsCPUSeconds == 0 {
return errors.New("no CPU usage reported")
}
if c.PGWireEgressBytes == 0 {
return errors.New("no pgwire egress bytes reported")
}