-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
helpers_test.go
1401 lines (1260 loc) · 43.4 KB
/
helpers_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 2018 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 changefeedccl
import (
"context"
gosql "database/sql"
gojson "encoding/json"
"fmt"
"math"
"math/rand"
"net/url"
"os"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"testing"
"time"
apd "github.com/cockroachdb/apd/v3"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/ccl/changefeedccl/cdctest"
"github.com/cockroachdb/cockroach/pkg/ccl/changefeedccl/changefeedbase"
_ "github.com/cockroachdb/cockroach/pkg/ccl/multiregionccl" // allow locality-related mutations
"github.com/cockroachdb/cockroach/pkg/ccl/multiregionccl/multiregionccltestutils"
_ "github.com/cockroachdb/cockroach/pkg/ccl/partitionccl"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/server"
"github.com/cockroachdb/cockroach/pkg/server/serverpb"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/execinfra"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/skip"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/log/eventpb"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
"github.com/lib/pq"
"github.com/stretchr/testify/require"
)
var testSinkFlushFrequency = 100 * time.Millisecond
// maybeDisableDeclarativeSchemaChangesForTest will disable the declarative
// schema changer with a probability of 10% using the provided SQL DB
// connection. This returns true if the declarative schema changer is disabled.
func maybeDisableDeclarativeSchemaChangesForTest(t testing.TB, sqlDB *sqlutils.SQLRunner) bool {
disable := rand.Float32() < 0.1
if disable {
t.Log("using legacy schema changer")
sqlDB.Exec(t, "SET use_declarative_schema_changer='off'")
sqlDB.Exec(t, "SET CLUSTER SETTING sql.defaults.use_declarative_schema_changer='off'")
}
return disable
}
func waitForSchemaChange(
t testing.TB, sqlDB *sqlutils.SQLRunner, stmt string, arguments ...interface{},
) {
sqlDB.Exec(t, stmt, arguments...)
row := sqlDB.QueryRow(t, "SELECT job_id FROM [SHOW JOBS] WHERE job_type = 'NEW SCHEMA CHANGE' OR job_type ='SCHEMA CHANGE' ORDER BY created DESC LIMIT 1")
var jobID string
row.Scan(&jobID)
testutils.SucceedsSoon(t, func() error {
row := sqlDB.QueryRow(t, "SELECT status FROM [SHOW JOBS] WHERE job_id = $1", jobID)
var status string
row.Scan(&status)
if status != "succeeded" {
return fmt.Errorf("Job %s had status %s, wanted 'succeeded'", jobID, status)
}
return nil
})
}
func readNextMessages(
ctx context.Context, f cdctest.TestFeed, numMessages int,
) ([]cdctest.TestFeedMessage, error) {
var actual []cdctest.TestFeedMessage
lastMessage := timeutil.Now()
for len(actual) < numMessages {
if ctx.Err() != nil {
return nil, ctx.Err()
}
if log.V(1) {
log.Infof(context.Background(), "About to read a message (%d out of %d)", len(actual), numMessages)
}
m, err := f.Next()
if log.V(1) {
if m != nil {
log.Infof(context.Background(), `msg %s: %s->%s (%s) (%s)`,
m.Topic, m.Key, m.Value, m.Resolved, timeutil.Since(lastMessage))
} else {
log.Infof(context.Background(), `err %v`, err)
}
}
lastMessage = timeutil.Now()
if err != nil {
return nil, err
}
if m == nil {
return nil, errors.AssertionFailedf(`expected message`)
}
if len(m.Key) > 0 || len(m.Value) > 0 {
actual = append(actual,
cdctest.TestFeedMessage{
Topic: m.Topic,
Key: m.Key,
Value: m.Value,
},
)
}
}
return actual, nil
}
func stripTsFromPayloads(payloads []cdctest.TestFeedMessage) ([]string, error) {
var actual []string
for _, m := range payloads {
var value []byte
var message map[string]interface{}
if err := gojson.Unmarshal(m.Value, &message); err != nil {
return nil, errors.Wrapf(err, `unmarshal: %s`, m.Value)
}
delete(message, "updated")
value, err := reformatJSON(message)
if err != nil {
return nil, err
}
actual = append(actual, fmt.Sprintf(`%s: %s->%s`, m.Topic, m.Key, value))
}
return actual, nil
}
func extractUpdatedFromValue(value []byte) (float64, error) {
var updatedRaw struct {
Updated string `json:"updated"`
}
if err := gojson.Unmarshal(value, &updatedRaw); err != nil {
return -1, errors.Wrapf(err, `unmarshal: %s`, value)
}
updatedVal, err := strconv.ParseFloat(updatedRaw.Updated, 64)
if err != nil {
return -1, errors.Wrapf(err, "error parsing updated timestamp: %s", updatedRaw.Updated)
}
return updatedVal, nil
}
func checkPerKeyOrdering(payloads []cdctest.TestFeedMessage) (bool, error) {
// map key to list of timestamp, ensure each list is ordered
keysToTimestamps := make(map[string][]float64)
for _, msg := range payloads {
key := string(msg.Key)
updatedTimestamp, err := extractUpdatedFromValue(msg.Value)
if err != nil {
return false, err
}
if _, ok := keysToTimestamps[key]; !ok {
keysToTimestamps[key] = []float64{}
}
if len(keysToTimestamps[key]) > 0 {
if updatedTimestamp < keysToTimestamps[key][len(keysToTimestamps[key])-1] {
return false, nil
}
}
keysToTimestamps[key] = append(keysToTimestamps[key], updatedTimestamp)
}
return true, nil
}
func assertPayloadsBase(
t testing.TB, f cdctest.TestFeed, expected []string, stripTs bool, perKeyOrdered bool,
) {
t.Helper()
timeout := assertPayloadsTimeout()
if len(expected) > 100 {
// Webhook sink is very slow; We have few tests that read 1000 messages.
timeout += time.Duration(math.Log(float64(len(expected)))) * time.Minute
}
require.NoError(t,
withTimeout(f, timeout,
func(ctx context.Context) (err error) {
return assertPayloadsBaseErr(ctx, f, expected, stripTs, perKeyOrdered)
},
))
}
func assertPayloadsBaseErr(
ctx context.Context, f cdctest.TestFeed, expected []string, stripTs bool, perKeyOrdered bool,
) error {
actual, err := readNextMessages(ctx, f, len(expected))
if err != nil {
return err
}
var actualFormatted []string
for _, m := range actual {
actualFormatted = append(actualFormatted, fmt.Sprintf(`%s: %s->%s`, m.Topic, m.Key, m.Value))
}
if perKeyOrdered {
ordered, err := checkPerKeyOrdering(actual)
if err != nil {
return err
}
if !ordered {
return errors.Newf("payloads violate CDC per-key ordering guarantees:\n %s",
strings.Join(actualFormatted, "\n "))
}
}
// strip timestamps after checking per-key ordering since check uses timestamps
if stripTs {
// format again with timestamps stripped
actualFormatted, err = stripTsFromPayloads(actual)
if err != nil {
return err
}
}
sort.Strings(expected)
sort.Strings(actualFormatted)
if !reflect.DeepEqual(expected, actualFormatted) {
return errors.Newf("expected\n %s\ngot\n %s",
strings.Join(expected, "\n "), strings.Join(actualFormatted, "\n "))
}
return nil
}
func assertPayloadsTimeout() time.Duration {
if util.RaceEnabled {
return 5 * time.Minute
}
return 30 * time.Second
}
func withTimeout(
f cdctest.TestFeed, timeout time.Duration, fn func(ctx context.Context) error,
) error {
var jobID jobspb.JobID
if jobFeed, ok := f.(cdctest.EnterpriseTestFeed); ok {
jobID = jobFeed.JobID()
}
return timeutil.RunWithTimeout(context.Background(),
fmt.Sprintf("withTimeout-%d", jobID), timeout,
func(ctx context.Context) error {
defer stopFeedWhenDone(ctx, f)()
return fn(ctx)
},
)
}
func assertPayloads(t testing.TB, f cdctest.TestFeed, expected []string) {
t.Helper()
assertPayloadsBase(t, f, expected, false, false)
}
func assertPayloadsStripTs(t testing.TB, f cdctest.TestFeed, expected []string) {
t.Helper()
assertPayloadsBase(t, f, expected, true, false)
}
// assert that the messages received by the sink maintain per-key ordering guarantees. then,
// strip the timestamp from the messages and compare them to the expected payloads.
func assertPayloadsPerKeyOrderedStripTs(t testing.TB, f cdctest.TestFeed, expected []string) {
t.Helper()
assertPayloadsBase(t, f, expected, true, true)
}
func avroToJSON(t testing.TB, reg *cdctest.SchemaRegistry, avroBytes []byte) []byte {
json, err := reg.AvroToJSON(avroBytes)
require.NoError(t, err)
return json
}
func assertRegisteredSubjects(t testing.TB, reg *cdctest.SchemaRegistry, expected []string) {
t.Helper()
actual := reg.Subjects()
sort.Strings(expected)
sort.Strings(actual)
if !reflect.DeepEqual(expected, actual) {
t.Fatalf("expected\n %s\ngot\n %s",
strings.Join(expected, "\n "), strings.Join(actual, "\n "))
}
}
func parseTimeToHLC(t testing.TB, s string) hlc.Timestamp {
t.Helper()
d, _, err := apd.NewFromString(s)
if err != nil {
t.Fatal(err)
}
ts, err := hlc.DecimalToHLC(d)
if err != nil {
t.Fatal(err)
}
return ts
}
// Expect to receive a resolved timestamp and the partition it belongs to from
// a test changefeed.
func expectResolvedTimestamp(t testing.TB, f cdctest.TestFeed) (hlc.Timestamp, string) {
t.Helper()
m, err := f.Next()
if err != nil {
t.Fatal(err)
} else if m == nil {
t.Fatal(`expected message`)
}
return extractResolvedTimestamp(t, m), m.Partition
}
// resolvedRaw represents a JSON object containing the single key "resolved"
// with a resolved timestamp value.
type resolvedRaw struct {
Resolved string `json:"resolved"`
}
func extractResolvedTimestamp(t testing.TB, m *cdctest.TestFeedMessage) hlc.Timestamp {
t.Helper()
if m.Key != nil {
t.Fatalf(`unexpected row %s: %s -> %s`, m.Topic, m.Key, m.Value)
}
if m.Resolved == nil {
t.Fatal(`expected a resolved timestamp notification`)
}
var resolved resolvedRaw
if err := gojson.Unmarshal(m.Resolved, &resolved); err != nil {
t.Fatal(err)
}
return parseTimeToHLC(t, resolved.Resolved)
}
func expectResolvedTimestampAvro(t testing.TB, f cdctest.TestFeed) hlc.Timestamp {
t.Helper()
m, err := f.Next()
if err != nil {
t.Fatal(err)
} else if m == nil {
t.Fatal(`expected message`)
}
if m.Key != nil {
t.Fatalf(`unexpected row %s: %s -> %s`, m.Topic, m.Key, m.Value)
}
if m.Resolved == nil {
t.Fatal(`expected a resolved timestamp notification`)
}
var resolvedNative interface{}
err = gojson.Unmarshal(m.Resolved, &resolvedNative)
if err != nil {
t.Fatal(err)
}
resolved := resolvedNative.(map[string]interface{})[`resolved`]
return parseTimeToHLC(t, resolved.(map[string]interface{})[`string`].(string))
}
var serverSetupStatements = `
SET CLUSTER SETTING kv.rangefeed.enabled = true;
SET CLUSTER SETTING kv.closed_timestamp.target_duration = '1s';
SET CLUSTER SETTING changefeed.experimental_poll_interval = '10ms';
SET CLUSTER SETTING sql.defaults.vectorize=on;
ALTER TENANT ALL SET CLUSTER SETTING changefeed.experimental_poll_interval = '10ms';
ALTER TENANT ALL SET CLUSTER SETTING sql.defaults.vectorize=on;
CREATE DATABASE d;
`
var tenantSetupStatements = `
CREATE DATABASE d;
`
func startTestFullServer(
t testing.TB, options feedTestOptions,
) (serverutils.TestServerInterface, *gosql.DB, func()) {
knobs := base.TestingKnobs{
DistSQL: &execinfra.TestingKnobs{Changefeed: &TestingKnobs{}},
JobsTestingKnobs: jobs.NewTestingKnobsWithShortIntervals(),
Server: &server.TestingKnobs{},
}
if options.knobsFn != nil {
options.knobsFn(&knobs)
}
args := base.TestServerArgs{
Knobs: knobs,
// This test suite is already probabilistically running with
// tenants. No need for the test tenant.
DefaultTestTenant: base.TestControlsTenantsExplicitly,
UseDatabase: `d`,
ExternalIODir: options.externalIODir,
Settings: options.settings,
}
if options.argsFn != nil {
options.argsFn(&args)
}
resetRetry := testingUseFastRetry()
resetFlushFrequency := changefeedbase.TestingSetDefaultMinCheckpointFrequency(testSinkFlushFrequency)
s, db, _ := serverutils.StartServer(t, args)
ctx := context.Background()
cleanup := func() {
s.Stopper().Stop(ctx)
resetFlushFrequency()
resetRetry()
}
var err error
defer func() {
if err != nil {
cleanup()
require.NoError(t, err)
}
}()
sqlDB := sqlutils.MakeSQLRunner(db)
sqlDB.ExecMultiple(t, strings.Split(serverSetupStatements, ";")...)
if region := serverArgsRegion(args); region != "" {
_, err = db.ExecContext(ctx, fmt.Sprintf(`ALTER DATABASE d PRIMARY REGION "%s"`, region))
require.NoError(t, err)
}
return s, db, cleanup
}
// startTestCluster starts a 3 node cluster.
//
// Note, if a testfeed depends on particular testing knobs, those may
// need to be applied to each of the servers in the test cluster
// returned from this function.
func startTestCluster(t testing.TB) (serverutils.TestClusterInterface, *gosql.DB, func()) {
skip.UnderStressRace(t, "multinode setup doesn't work under testrace")
ctx := context.Background()
knobs := base.TestingKnobs{
DistSQL: &execinfra.TestingKnobs{Changefeed: &TestingKnobs{}},
JobsTestingKnobs: jobs.NewTestingKnobsWithShortIntervals(),
}
resetRetry := testingUseFastRetry()
resetFlushFrequency := changefeedbase.TestingSetDefaultMinCheckpointFrequency(testSinkFlushFrequency)
cluster, db, cleanup := multiregionccltestutils.TestingCreateMultiRegionCluster(
t, 3 /* numServers */, knobs,
multiregionccltestutils.WithUseDatabase("d"),
)
cleanupAndReset := func() {
cleanup()
resetFlushFrequency()
resetRetry()
}
var err error
defer func() {
if err != nil {
cleanupAndReset()
require.NoError(t, err)
}
}()
sqlDB := sqlutils.MakeSQLRunner(db)
sqlDB.ExecMultiple(t, strings.Split(serverSetupStatements, ";")...)
_, err = db.ExecContext(ctx, `ALTER DATABASE d PRIMARY REGION "us-east1"`)
return cluster, db, cleanupAndReset
}
func waitForTenantPodsActive(
t testing.TB, tenantServer serverutils.ApplicationLayerInterface, numPods int,
) {
testutils.SucceedsWithin(t, func() error {
status := tenantServer.StatusServer().(serverpb.SQLStatusServer)
var nodes *serverpb.NodesListResponse
var err error
for nodes == nil || len(nodes.Nodes) != numPods {
nodes, err = status.NodesList(context.Background(), nil)
if err != nil {
return err
}
}
return nil
}, 10*time.Second)
}
func startTestTenant(
t testing.TB, systemServer serverutils.TestServerInterface, options feedTestOptions,
) (roachpb.TenantID, serverutils.ApplicationLayerInterface, *gosql.DB, func()) {
knobs := base.TestingKnobs{
DistSQL: &execinfra.TestingKnobs{Changefeed: &TestingKnobs{}},
JobsTestingKnobs: jobs.NewTestingKnobsWithShortIntervals(),
Server: &server.TestingKnobs{},
}
if options.knobsFn != nil {
options.knobsFn(&knobs)
}
tenantID := serverutils.TestTenantID()
tenantArgs := base.TestTenantArgs{
// crdb_internal.create_tenant called by StartTenant
TenantID: tenantID,
UseDatabase: `d`,
TestingKnobs: knobs,
ExternalIODir: options.externalIODir,
Settings: options.settings,
}
tenantServer, tenantDB := serverutils.StartTenant(t, systemServer, tenantArgs)
// Re-run setup on the tenant as well
tenantRunner := sqlutils.MakeSQLRunner(tenantDB)
tenantRunner.ExecMultiple(t, strings.Split(tenantSetupStatements, ";")...)
waitForTenantPodsActive(t, tenantServer, 1)
resetRetry := testingUseFastRetry()
return tenantID, tenantServer, tenantDB, func() {
tenantServer.AppStopper().Stop(context.Background())
resetRetry()
}
}
type cdcTestFn func(*testing.T, TestServer, cdctest.TestFeedFactory)
type cdcTestWithSystemFn func(*testing.T, TestServerWithSystem, cdctest.TestFeedFactory)
type updateArgsFn func(args *base.TestServerArgs)
type updateKnobsFn func(knobs *base.TestingKnobs)
type feedTestOptions struct {
useTenant bool
forceNoExternalConnectionURI bool
forceRootUserConnection bool
argsFn updateArgsFn
knobsFn updateKnobsFn
externalIODir string
allowedSinkTypes []string
disabledSinkTypes []string
disableSyntheticTimestamps bool
settings *cluster.Settings
}
type feedTestOption func(opts *feedTestOptions)
// feedTestNoTenants is a feedTestOption that will prohibit this tests
// from randomly running on a tenant.
var feedTestNoTenants = func(opts *feedTestOptions) { opts.useTenant = false }
// feedTestNoExternalConnection is a feedTestOption that will prohibit this test
// from randomly creating an external connection URI and providing that as the sink
// rather than directly specifying it. (Feed tests never actually connect to anything external.)
var feedTestNoExternalConnection = func(opts *feedTestOptions) { opts.forceNoExternalConnectionURI = true }
// feedTestUseRootUserConnection is a feedTestOption that will force the cdctest.TestFeedFactory
// to use the root user connection when creating changefeeds. This disables the typical behavior of cdc tests where
// tests randomly choose between the root user connection or a test user connection where the test user
// has privileges to create changefeeds on tables in the default database `d` only.
var feedTestUseRootUserConnection = func(opts *feedTestOptions) { opts.forceRootUserConnection = true }
// feedTestNoForcedSyntheticTimestamps is a feedTestOption that will prevent
// the test from randomly forcing timestamps to be synthetic and offset five seconds into the future from
// what they would otherwise be. It doesn't prevent synthetic timestamps but they're otherwise unlikely to
// occur in tests.
var feedTestNoForcedSyntheticTimestamps = func(opts *feedTestOptions) { opts.disableSyntheticTimestamps = true }
var feedTestForceSink = func(sinkType string) feedTestOption {
return feedTestRestrictSinks(sinkType)
}
var feedTestRestrictSinks = func(sinkTypes ...string) feedTestOption {
return func(opts *feedTestOptions) { opts.allowedSinkTypes = append(opts.allowedSinkTypes, sinkTypes...) }
}
var feedTestEnterpriseSinks = func(opts *feedTestOptions) {
feedTestOmitSinks("sinkless")(opts)
}
var feedTestOmitSinks = func(sinkTypes ...string) feedTestOption {
return func(opts *feedTestOptions) { opts.disabledSinkTypes = append(opts.disabledSinkTypes, sinkTypes...) }
}
func (opts feedTestOptions) omitSinks(sinks ...string) feedTestOptions {
res := opts
res.disabledSinkTypes = append(opts.disabledSinkTypes, sinks...)
return res
}
// withArgsFn is a feedTestOption that allow the caller to modify the
// TestServerArgs before they are used to create the test server. Note
// that in multi-tenant tests, these will only apply to the kvServer
// and not the sqlServer.
func withArgsFn(fn updateArgsFn) feedTestOption {
return func(opts *feedTestOptions) { opts.argsFn = fn }
}
// withKnobsFn is a feedTestOption that allows the caller to modify
// the testing knobs used by the test server. For multi-tenant
// testing, these knobs are applied to both the kv and sql nodes.
func withKnobsFn(fn updateKnobsFn) feedTestOption {
return func(opts *feedTestOptions) { opts.knobsFn = fn }
}
// Silence the linter.
var _ = withKnobsFn(nil /* fn */)
func newTestOptions() feedTestOptions {
// percentTenant is the percentage of tests that will be run against
// a SQL-node in a multi-tenant server. 1 for all tests to be run on a
// tenant.
const percentTenant = 0.5
return feedTestOptions{
useTenant: rand.Float32() < percentTenant,
}
}
func makeOptions(opts ...feedTestOption) feedTestOptions {
options := newTestOptions()
for _, o := range opts {
o(&options)
}
if !options.disableSyntheticTimestamps && rand.Intn(2) == 0 {
// Offset all timestamps a random (but consistent per test) amount into the
// future to ensure we can handle that. Always chooses an integer number of
// seconds for easier debugging and so that 0 is a possibility.
offset := int64(rand.Intn(6)) * time.Second.Nanoseconds()
// TODO(#105053): Remove this line
_ = offset
oldKnobsFn := options.knobsFn
options.knobsFn = func(knobs *base.TestingKnobs) {
if oldKnobsFn != nil {
oldKnobsFn(knobs)
}
knobs.DistSQL.(*execinfra.TestingKnobs).
Changefeed.(*TestingKnobs).FeedKnobs.ModifyTimestamps = func(t *hlc.Timestamp) {
// NOTE(ricky): This line of code should be uncommented.
// It used to be just t.Add(offset, 0), but t.Add() has no side
// effects so this was a no-op. *t = t.Add(offset, 0) is correct,
// but causes test failures.
// TODO(#105053): Uncomment and fix test failures
//*t = t.Add(offset, 0)
t.Synthetic = true
}
}
}
return options
}
func serverArgsRegion(args base.TestServerArgs) string {
for _, tier := range args.Locality.Tiers {
if tier.Key == "region" {
return tier.Value
}
}
return ""
}
// expectNotice creates a pretty crude database connection that doesn't involve
// a lot of cdc test framework, use with caution. Driver-agnostic tools don't
// have clean ways of inspecting incoming notices.
func expectNotice(
t *testing.T, s serverutils.ApplicationLayerInterface, sql string, expected string,
) {
url, cleanup := sqlutils.PGUrl(t, s.SQLAddr(), t.Name(), url.User(username.RootUser))
defer cleanup()
base, err := pq.NewConnector(url.String())
if err != nil {
t.Fatal(err)
}
actual := "(no notice)"
connector := pq.ConnectorWithNoticeHandler(base, func(n *pq.Error) {
actual = n.Message
})
dbWithHandler := gosql.OpenDB(connector)
defer dbWithHandler.Close()
sqlDB := sqlutils.MakeSQLRunner(dbWithHandler)
sqlDB.Exec(t, sql)
require.Equal(t, expected, actual)
}
// These retry opts are configured so that we don't perform a read transaction
// on the job record too often. It's important to avoid contending
// with the write txn which updates the job progress. If we read too often, we
// may continously invalidate the writes, preventing checkpoints from
// being written.
var jobRecordPollFrequency = 3 * time.Second
var jobRecordRetryOpts = retry.Options{
InitialBackoff: jobRecordPollFrequency,
Multiplier: 1,
MaxBackoff: 5 * time.Second,
MaxRetries: 30,
}
// waitForCheckpoint waits for the specified job to have a non-empty checkpoint
func waitForCheckpoint(t *testing.T, jf cdctest.EnterpriseTestFeed, jr *jobs.Registry) {
for r := retry.Start(jobRecordRetryOpts); ; {
t.Log("waiting for checkpoint")
progress := loadProgress(t, jf, jr)
if p := progress.GetChangefeed(); p != nil && p.Checkpoint != nil && len(p.Checkpoint.Spans) > 0 {
t.Logf("read checkpoint %v", p.Checkpoint)
return
}
if !r.Next() {
t.Fatal("could not read checkpoint")
}
}
}
// waitForHighwater waits for the specified job to have a non-nil highwater.
func waitForHighwater(t *testing.T, jf cdctest.EnterpriseTestFeed, jr *jobs.Registry) {
for r := retry.Start(jobRecordRetryOpts); ; {
t.Log("waiting for highwater")
progress := loadProgress(t, jf, jr)
if hw := progress.GetHighWater(); hw != nil && !hw.IsEmpty() {
t.Logf("read highwater %s", hw)
return
}
if !r.Next() {
t.Fatal("could not read highwater")
}
}
}
func loadProgress(
t *testing.T, jobFeed cdctest.EnterpriseTestFeed, jobRegistry *jobs.Registry,
) jobspb.Progress {
t.Helper()
jobID := jobFeed.JobID()
job, err := jobRegistry.LoadJob(context.Background(), jobID)
require.NoError(t, err)
if job.Status().Terminal() {
t.Errorf("tried to load progress for job %v but it has reached terminal status %s with error %s", job, job.Status(), jobFeed.FetchTerminalJobErr())
}
return job.Progress()
}
func feed(
t testing.TB, f cdctest.TestFeedFactory, create string, args ...interface{},
) cdctest.TestFeed {
t.Helper()
feed, err := f.Feed(create, args...)
if err != nil {
t.Fatal(err)
}
return feed
}
func asUser(
t testing.TB, f cdctest.TestFeedFactory, user string, fn func(runner *sqlutils.SQLRunner),
) {
t.Helper()
require.NoError(t, f.AsUser(user, fn))
}
func expectErrCreatingFeed(
t testing.TB, f cdctest.TestFeedFactory, create string, errSubstring string,
) {
t.Helper()
t.Logf("expecting %s to error", create)
feed, err := f.Feed(create)
if feed != nil {
defer func() { _ = feed.Close() }()
}
if err == nil {
// Sinkless test feeds don't error until you try to read the first row.
if _, sinkless := feed.(*sinklessFeed); sinkless {
_, err = feed.Next()
}
}
if err == nil {
t.Errorf("No error from %s", create)
} else {
require.Contains(t, err.Error(), errSubstring)
}
}
func closeFeed(t testing.TB, f cdctest.TestFeed) {
if err := f.Close(); err != nil {
t.Fatal(err)
}
}
func closeFeedIgnoreError(t testing.TB, f cdctest.TestFeed) {
defer func() {
if e := recover(); e != nil {
t.Log(e)
}
}()
t.Helper()
if err := f.Close(); err != nil {
t.Log(err)
}
}
// TestServer is a struct to allow tests to operate on a shared API regardless
// of a test running as the system tenant or a secondary tenant
type TestServer struct {
DB *gosql.DB
Server serverutils.ApplicationLayerInterface
Codec keys.SQLCodec
TestingKnobs base.TestingKnobs
}
// TestServerWithSystem provides access to the system db and server for a
// TestServer. This is useful for some tests that explicitly require access to
// the system tenant, for example if
// desctestutils.TestingGetPublicTableDescriptor is being called.
type TestServerWithSystem struct {
TestServer
SystemDB *gosql.DB
SystemServer serverutils.TestServerInterface
}
func makeSystemServer(
t *testing.T, opts ...feedTestOption,
) (testServer TestServerWithSystem, cleanup func()) {
options := makeOptions(opts...)
return makeSystemServerWithOptions(t, options)
}
var _ = makeSystemServer // silence unused warning
func makeSystemServerWithOptions(
t *testing.T, options feedTestOptions,
) (testServer TestServerWithSystem, cleanup func()) {
systemServer, systemDB, clusterCleanup := startTestFullServer(t, options)
return TestServerWithSystem{
TestServer: TestServer{
DB: systemDB,
Server: systemServer,
TestingKnobs: *systemServer.SystemLayer().TestingKnobs(),
Codec: keys.SystemSQLCodec,
},
SystemServer: systemServer,
SystemDB: systemDB,
}, func() {
clusterCleanup()
}
}
func makeTenantServer(
t *testing.T, opts ...feedTestOption,
) (testServer TestServerWithSystem, cleanup func()) {
options := makeOptions(opts...)
return makeTenantServerWithOptions(t, options)
}
func makeTenantServerWithOptions(
t *testing.T, options feedTestOptions,
) (testServer TestServerWithSystem, cleanup func()) {
systemServer, systemDB, clusterCleanup := startTestFullServer(t, options)
tenantID, tenantServer, tenantDB, tenantCleanup := startTestTenant(t, systemServer, options)
return TestServerWithSystem{
TestServer: TestServer{
DB: tenantDB,
Server: tenantServer,
TestingKnobs: *tenantServer.TestingKnobs(),
Codec: keys.MakeSQLCodec(tenantID),
},
SystemDB: systemDB,
SystemServer: systemServer,
}, func() {
tenantCleanup()
clusterCleanup()
}
}
func makeServer(
t *testing.T, opts ...feedTestOption,
) (testServer TestServerWithSystem, cleanup func()) {
options := makeOptions(opts...)
return makeServerWithOptions(t, options)
}
func makeServerWithOptions(
t *testing.T, options feedTestOptions,
) (server TestServerWithSystem, cleanup func()) {
if options.useTenant {
t.Logf("making server as secondary tenant")
return makeTenantServerWithOptions(t, options)
}
t.Logf("making server as system tenant")
return makeSystemServerWithOptions(t, options)
}
func randomSinkType(opts ...feedTestOption) string {
options := makeOptions(opts...)
return randomSinkTypeWithOptions(options)
}
func randomSinkTypeWithOptions(options feedTestOptions) string {
sinkWeights := map[string]int{
"kafka": 3,
"enterprise": 1,
"webhook": 1,
"pubsub": 1,
"sinkless": 2,
"cloudstorage": 0,
}
if options.externalIODir != "" {
sinkWeights["cloudstorage"] = 3
}
if options.allowedSinkTypes != nil {
sinkWeights = map[string]int{}
for _, sinkType := range options.allowedSinkTypes {
sinkWeights[sinkType] = 1
}
}
if options.disabledSinkTypes != nil {
for _, sinkType := range options.disabledSinkTypes {
sinkWeights[sinkType] = 0
}
}
weightTotal := 0
for _, weight := range sinkWeights {
weightTotal += weight
}
if weightTotal == 0 {
// This exists for testing purposes, where one may want to run all tests on
// the same sink and set sinkWeights to be 1 only for that sink, but some
// tests explicitly disallow that sink and therefore have no valid sinks.
return "skip"
}
p := rand.Float32() * float32(weightTotal)
var sum float32 = 0
for sink, weight := range sinkWeights {
sum += float32(weight)
if p <= sum {
return sink
}
}
return "skip" // unreachable
}
// addCloudStorageOptions adds the options necessary to enable a server to run a
// cloudstorage changefeed on it
func addCloudStorageOptions(t *testing.T, options *feedTestOptions) (cleanup func()) {
dir, dirCleanupFn := testutils.TempDir(t)
options.externalIODir = dir
return dirCleanupFn
}
func makeFeedFactory(
t *testing.T,
sinkType string,
s serverutils.ApplicationLayerInterface,
db *gosql.DB,
testOpts ...feedTestOption,
) (factory cdctest.TestFeedFactory, sinkCleanup func()) {
options := makeOptions(testOpts...)
return makeFeedFactoryWithOptions(t, sinkType, s, db, options)
}
func makeFeedFactoryWithOptions(
t *testing.T, sinkType string, srvOrCluster interface{}, db *gosql.DB, options feedTestOptions,
) (factory cdctest.TestFeedFactory, sinkCleanup func()) {
t.Logf("making %s feed factory", sinkType)
s := func() serverutils.ApplicationLayerInterface {
switch s := srvOrCluster.(type) {
case serverutils.ApplicationLayerInterface:
return s
case serverutils.TestClusterInterface:
return s.Server(0)
default:
t.Fatalf("unexpected argument type %T", s)
return nil
}
}()
pgURLForUser := func(u string, pass ...string) (url.URL, func()) {
t.Logf("pgURL %s %s", sinkType, u)
if len(pass) < 1 {
return sqlutils.PGUrl(t, s.SQLAddr(), t.Name(), url.User(u))
}
return url.URL{
Scheme: "postgres",
User: url.UserPassword(u, pass[0]),
Host: s.SQLAddr()}, func() {}
}
switch sinkType {
case "kafka":
f := makeKafkaFeedFactory(srvOrCluster, db)
userDB, cleanup := getInitialDBForEnterpriseFactory(t, s, db, options)
f.(*kafkaFeedFactory).configureUserDB(userDB)