-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
testfeed_test.go
2530 lines (2227 loc) · 66.8 KB
/
testfeed_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 changefeedccl
import (
"bufio"
"bytes"
"context"
gosql "database/sql"
"encoding/base64"
gojson "encoding/json"
"fmt"
"math/rand"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
pubsubv1 "cloud.google.com/go/pubsub/apiv1"
pb "cloud.google.com/go/pubsub/apiv1/pubsubpb"
"cloud.google.com/go/pubsub/pstest"
"github.com/Shopify/sarama"
"github.com/cockroachdb/cockroach-go/v2/crdb"
"github.com/cockroachdb/cockroach/pkg/ccl/changefeedccl/cdcevent"
"github.com/cockroachdb/cockroach/pkg/ccl/changefeedccl/cdctest"
"github.com/cockroachdb/cockroach/pkg/ccl/changefeedccl/changefeedbase"
"github.com/cockroachdb/cockroach/pkg/ccl/changefeedccl/kvevent"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/distsql"
"github.com/cockroachdb/cockroach/pkg/sql/isql"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/sem/eval"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondatapb"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/jobutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/contextutil"
"github.com/cockroachdb/cockroach/pkg/util/ctxgroup"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/json"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/parquet"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
"github.com/jackc/pgx/v4"
"google.golang.org/api/option"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type sinklessFeedFactory struct {
s serverutils.TestTenantInterface
// postgres url used for creating sinkless changefeeds. This may be the same as
// the rootURL.
sink url.URL
// postgres url for the root user, used for test internals.
rootURL url.URL
sinkForUser sinkForUser
}
// makeSinklessFeedFactory returns a TestFeedFactory implementation using the
// `experimental-sql` uri.
func makeSinklessFeedFactory(
s serverutils.TestTenantInterface, sink url.URL, rootConn url.URL, sinkForUser sinkForUser,
) cdctest.TestFeedFactory {
return &sinklessFeedFactory{s: s, sink: sink, rootURL: rootConn, sinkForUser: sinkForUser}
}
// AsUser executes fn as the specified user.
func (f *sinklessFeedFactory) AsUser(user string, fn func(*sqlutils.SQLRunner)) error {
prevSink := f.sink
password := `hunter2`
if err := f.setPassword(user, password); err != nil {
return err
}
defer func() { f.sink = prevSink }()
var cleanup func()
f.sink, cleanup = f.sinkForUser(user, password)
pgconn := url.URL{
Scheme: "postgres",
User: url.UserPassword(user, password),
Host: f.Server().SQLAddr(),
Path: `d`,
}
db2, err := gosql.Open("postgres", pgconn.String())
if err != nil {
return err
}
defer db2.Close()
userDB := sqlutils.MakeSQLRunner(db2)
fn(userDB)
cleanup()
return nil
}
func (f *sinklessFeedFactory) setPassword(user, password string) error {
rootDB, err := gosql.Open("postgres", f.rootURL.String())
if err != nil {
return err
}
defer rootDB.Close()
_, err = rootDB.Exec(fmt.Sprintf(`ALTER USER %s WITH PASSWORD '%s'`, user, password))
return err
}
// Feed implements the TestFeedFactory interface
func (f *sinklessFeedFactory) Feed(create string, args ...interface{}) (cdctest.TestFeed, error) {
sink := f.sink
sink.RawQuery = sink.Query().Encode()
// Use pgx directly instead of database/sql so we can close the conn
// (instead of returning it to the pool).
pgxConfig, err := pgx.ParseConfig(sink.String())
if err != nil {
return nil, err
}
s := &sinklessFeed{
seenTrackerMap: make(map[string]struct{}),
create: create,
args: args,
connCfg: pgxConfig,
}
return s, s.start()
}
// Server implements the TestFeedFactory interface.
func (f *sinklessFeedFactory) Server() serverutils.TestTenantInterface {
return f.s
}
type seenTracker interface {
reset()
}
type seenTrackerMap map[string]struct{}
func (t seenTrackerMap) markSeen(m *cdctest.TestFeedMessage) (isNew bool) {
// TODO(dan): This skips duplicates, since they're allowed by the
// semantics of our changefeeds. Now that we're switching to RangeFeed,
// this can actually happen (usually because of splits) and cause flakes.
// However, we really should be de-duping key+ts, this is too coarse.
// Fixme.
seenKey := m.Topic + m.Partition + string(m.Key) + string(m.Value)
if _, ok := t[seenKey]; ok {
return false
}
t[seenKey] = struct{}{}
return true
}
func (t seenTrackerMap) reset() {
for k := range t {
delete(t, k)
}
}
// sinklessFeed is an implementation of the `TestFeed` interface for a
// "sinkless" (results returned over pgwire) feed.
type sinklessFeed struct {
seenTrackerMap
create string
args []interface{}
connCfg *pgx.ConnConfig
conn *pgx.Conn
rows pgx.Rows
latestResolved hlc.Timestamp
}
var _ cdctest.TestFeed = (*sinklessFeed)(nil)
func timeout() time.Duration {
if util.RaceEnabled {
return 5 * time.Minute
}
return 30 * time.Second
}
// Partitions implements the TestFeed interface.
func (c *sinklessFeed) Partitions() []string { return []string{`sinkless`} }
// Next implements the TestFeed interface.
func (c *sinklessFeed) Next() (*cdctest.TestFeedMessage, error) {
defer time.AfterFunc(timeout(), func() {
_ = c.conn.Close(context.Background())
}).Stop()
m := &cdctest.TestFeedMessage{Partition: `sinkless`}
for {
if !c.rows.Next() {
return nil, c.rows.Err()
}
var maybeTopic gosql.NullString
if err := c.rows.Scan(&maybeTopic, &m.Key, &m.Value); err != nil {
return nil, err
}
if len(maybeTopic.String) > 0 {
m.Topic = maybeTopic.String
if isNew := c.markSeen(m); !isNew {
continue
}
return m, nil
}
m.Resolved = m.Value
m.Key, m.Value = nil, nil
// Keep track of the latest resolved timestamp so Resume can use it.
// TODO(dan): Also do this for non-json feeds.
if _, resolved, err := cdctest.ParseJSONValueTimestamps(m.Resolved); err == nil {
c.latestResolved.Forward(resolved)
}
return m, nil
}
}
// Resume implements the TestFeed interface.
func (c *sinklessFeed) start() (err error) {
c.conn, err = pgx.ConnectConfig(context.Background(), c.connCfg)
if err != nil {
return err
}
create := c.create
if !c.latestResolved.IsEmpty() {
// NB: The TODO in Next means c.latestResolved is currently never set for
// non-json feeds.
if strings.Contains(create, `WITH`) {
create += fmt.Sprintf(`, cursor='%s'`, c.latestResolved.AsOfSystemTime())
} else {
create += fmt.Sprintf(` WITH cursor='%s'`, c.latestResolved.AsOfSystemTime())
}
}
c.rows, err = c.conn.Query(context.Background(), create, c.args...)
return err
}
// Close implements the TestFeed interface.
func (c *sinklessFeed) Close() error {
c.rows = nil
return c.conn.Close(context.Background())
}
type logger interface {
Log(args ...interface{})
}
type externalConnectionFeedFactory struct {
cdctest.TestFeedFactory
db *gosql.DB
logger logger
}
type externalConnectionCreator func(uri string) error
func (e *externalConnectionFeedFactory) Feed(
create string, args ...interface{},
) (_ cdctest.TestFeed, err error) {
randomExternalConnectionName := fmt.Sprintf("testconn%d", rand.Int63())
var c externalConnectionCreator = func(uri string) error {
e.logger.Log("creating external connection")
createConnStmt := fmt.Sprintf(`CREATE EXTERNAL CONNECTION %s AS '%s'`, randomExternalConnectionName, uri)
_, err := e.db.Exec(createConnStmt)
e.logger.Log("ran create external connection")
if err != nil {
e.logger.Log("error creating external connection:" + err.Error())
}
return err
}
args = append([]interface{}{c}, args...)
parsed, err := parser.ParseOne(create)
if err != nil {
return nil, err
}
createStmt := parsed.AST.(*tree.CreateChangefeed)
if createStmt.SinkURI != nil {
return nil, errors.Errorf(
`unexpected uri provided: "INTO %s"`, tree.AsString(createStmt.SinkURI))
}
createStmt.SinkURI = tree.NewStrVal(`external://` + randomExternalConnectionName)
return e.TestFeedFactory.Feed(createStmt.String(), args...)
}
func setURI(
createStmt *tree.CreateChangefeed, uri string, allowOverride bool, args *[]interface{},
) error {
if createStmt.SinkURI != nil {
u, err := url.Parse(tree.AsStringWithFlags(createStmt.SinkURI, tree.FmtBareStrings))
if err != nil {
return err
}
if u.Scheme == changefeedbase.SinkSchemeExternalConnection {
fn, ok := (*args)[0].(externalConnectionCreator)
if ok {
*args = (*args)[1:]
return fn(uri)
}
}
if allowOverride {
return nil
}
return errors.Errorf(
`unexpected uri provided: "INTO %s"`, tree.AsString(createStmt.SinkURI))
}
createStmt.SinkURI = tree.NewStrVal(uri)
return nil
}
// reportErrorResumer is a job resumer which reports OnFailOrCancel events.
type reportErrorResumer struct {
wrapped jobs.Resumer
jobFailed func()
}
var _ jobs.Resumer = (*reportErrorResumer)(nil)
// Resume implements jobs.Resumer
func (r *reportErrorResumer) Resume(ctx context.Context, execCtx interface{}) error {
return r.wrapped.Resume(ctx, execCtx)
}
// OnFailOrCancel implements jobs.Resumer
func (r *reportErrorResumer) OnFailOrCancel(
ctx context.Context, execCtx interface{}, jobErr error,
) error {
defer r.jobFailed()
return r.wrapped.OnFailOrCancel(ctx, execCtx, jobErr)
}
// OnPauseRequest implements PauseRequester interface.
func (r *reportErrorResumer) OnPauseRequest(
ctx context.Context, execCtx interface{}, txn isql.Txn, details *jobspb.Progress,
) error {
return r.wrapped.(*changefeedResumer).OnPauseRequest(ctx, execCtx, txn, details)
}
type wrapSinkFn func(sink Sink) Sink
// jobFeed indicates that the feed is an "enterprise feed" -- that is,
// it uses jobs system to manage its state.
type jobFeed struct {
db *gosql.DB
shutdown chan struct{}
makeSink wrapSinkFn
jobID jobspb.JobID
mu struct {
syncutil.Mutex
terminalErr error
}
}
var _ cdctest.EnterpriseTestFeed = (*jobFeed)(nil)
func newJobFeed(db *gosql.DB, wrapper wrapSinkFn) *jobFeed {
return &jobFeed{
db: db,
shutdown: make(chan struct{}),
makeSink: wrapper,
}
}
type jobFailedMarker interface {
jobFailed(err error)
}
// jobFailed marks this job as failed.
func (f *jobFeed) jobFailed(err error) {
// protect against almost concurrent terminations of the same job.
// this could happen if the caller invokes `cancel job` just as we're
// trying to close this feed. Part of jobFailed handling involves
// closing shutdown channel -- and doing this multiple times panics.
f.mu.Lock()
defer f.mu.Unlock()
if f.mu.terminalErr != nil {
// Already failed/done.
return
}
f.mu.terminalErr = err
close(f.shutdown)
}
func (f *jobFeed) terminalJobError() error {
f.mu.Lock()
defer f.mu.Unlock()
return f.mu.terminalErr
}
// JobID implements EnterpriseTestFeed interface.
func (f *jobFeed) JobID() jobspb.JobID {
return f.jobID
}
func (f *jobFeed) status() (status string, err error) {
err = f.db.QueryRowContext(context.Background(),
`SELECT status FROM system.jobs WHERE id = $1`, f.jobID).Scan(&status)
return
}
func (f *jobFeed) WaitForStatus(statusPred func(status jobs.Status) bool) error {
if f.jobID == jobspb.InvalidJobID {
// Job may not have been started.
return nil
}
// Wait for the job status predicate to become true.
return testutils.SucceedsSoonError(func() error {
var status string
var err error
if status, err = f.status(); err != nil {
return err
}
if statusPred(jobs.Status(status)) {
return nil
}
return errors.Newf("still waiting for job status; current %s", status)
})
}
// Pause implements the TestFeed interface.
func (f *jobFeed) Pause() error {
_, err := f.db.Exec(`PAUSE JOB $1`, f.jobID)
if err != nil {
return err
}
return f.WaitForStatus(func(s jobs.Status) bool { return s == jobs.StatusPaused })
}
// Resume implements the TestFeed interface.
func (f *jobFeed) Resume() error {
_, err := f.db.Exec(`RESUME JOB $1`, f.jobID)
if err != nil {
return err
}
return f.WaitForStatus(func(s jobs.Status) bool { return s == jobs.StatusRunning })
}
// Details implements FeedJob interface.
func (f *jobFeed) Details() (*jobspb.ChangefeedDetails, error) {
stmt := fmt.Sprintf(`
SELECT payload FROM (%s)
`, jobutils.InternalSystemJobsBaseQuery)
var payloadBytes []byte
if err := f.db.QueryRow(stmt, f.jobID).Scan(&payloadBytes); err != nil {
return nil, errors.Wrapf(err, "Details for job %d", f.jobID)
}
var payload jobspb.Payload
if err := protoutil.Unmarshal(payloadBytes, &payload); err != nil {
return nil, err
}
return payload.GetChangefeed(), nil
}
// HighWaterMark implements FeedJob interface.
func (f *jobFeed) HighWaterMark() (hlc.Timestamp, error) {
stmt := fmt.Sprintf(`
SELECT progress FROM (%s)
`, jobutils.InternalSystemJobsBaseQuery)
var details []byte
if err := f.db.QueryRow(stmt, f.jobID).Scan(&details); err != nil {
return hlc.Timestamp{}, errors.Wrapf(err, "HighWaterMark for job %d", f.jobID)
}
var progress jobspb.Progress
if err := protoutil.Unmarshal(details, &progress); err != nil {
return hlc.Timestamp{}, err
}
h := progress.GetHighWater()
var hwm hlc.Timestamp
if h != nil {
hwm = *h
}
return hwm, nil
}
// TickHighWaterMark implements the TestFeed interface.
func (f *jobFeed) TickHighWaterMark(minHWM hlc.Timestamp) error {
return testutils.SucceedsWithinError(func() error {
current, err := f.HighWaterMark()
if err != nil {
return err
}
if minHWM.Less(current) {
return nil
}
return errors.Newf("waiting to tick: current=%s min=%s", current, minHWM)
}, 10*time.Second)
}
// FetchTerminalJobErr retrieves the error message from changefeed job.
func (f *jobFeed) FetchTerminalJobErr() error {
var errStr string
if err := testutils.SucceedsSoonError(func() error {
return f.db.QueryRow(
`SELECT error FROM [SHOW JOBS] WHERE job_id=$1`, f.jobID,
).Scan(&errStr)
}); err != nil {
return errors.Wrapf(err, "FetchTerminalJobErr for job %d", f.jobID)
}
if errStr != "" {
return errors.Newf("%s", errStr)
}
return nil
}
// FetchRunningStatus retrieves running status from changefeed job.
func (f *jobFeed) FetchRunningStatus() (runningStatusStr string, err error) {
if err = f.db.QueryRow(
`SELECT running_status FROM [SHOW JOBS] WHERE job_id=$1`, f.jobID,
).Scan(&runningStatusStr); err != nil {
return "", errors.Wrapf(err, "FetchRunningStatus for job %d", f.jobID)
}
return runningStatusStr, err
}
// Close closes job feed.
func (f *jobFeed) Close() error {
// Signal shutdown.
select {
case <-f.shutdown:
// Already failed/or failing.
default:
// TODO(yevgeniy): Cancel job w/out producing spurious error messages in the logs.
if f.jobID == jobspb.InvalidJobID {
// Some tests may create a jobFeed without creating a new job. Hence, if
// the jobID is invalid, skip trying to cancel the job.
return nil
}
status, err := f.status()
if err != nil {
return err
}
if status == string(jobs.StatusSucceeded) {
f.mu.Lock()
defer f.mu.Unlock()
f.mu.terminalErr = errors.New("changefeed completed")
close(f.shutdown)
return nil
}
if status == string(jobs.StatusFailed) {
f.mu.Lock()
defer f.mu.Unlock()
f.mu.terminalErr = errors.New("changefeed failed")
close(f.shutdown)
return nil
}
if _, err := f.db.Exec(`CANCEL JOB $1`, f.jobID); err != nil {
log.Infof(context.Background(), `could not cancel feed %d: %v`, f.jobID, err)
} else {
return f.WaitForStatus(func(s jobs.Status) bool { return s == jobs.StatusCanceled })
}
}
return nil
}
// sinkSychronizer allows testfeed's Next() method to synchronize itself
// with the sink operations.
type sinkSynchronizer struct {
syncutil.Mutex
waitor chan struct{}
flushed bool
}
// eventReady returns a channel that can be waited on until the next
// event.
func (s *sinkSynchronizer) eventReady() chan struct{} {
s.Lock()
defer s.Unlock()
ready := make(chan struct{})
if s.flushed {
close(ready)
s.flushed = false
} else {
s.waitor = ready
}
return ready
}
func (s *sinkSynchronizer) addFlush() {
s.Lock()
defer s.Unlock()
s.flushed = true
if s.waitor != nil {
close(s.waitor)
s.waitor = nil
s.flushed = false
}
}
// notifyFlushSink keeps track of the number of emitted rows and timestamps,
// and provides a way for the caller to block until some events have been emitted.
type notifyFlushSink struct {
Sink
sync *sinkSynchronizer
}
func (s *notifyFlushSink) Flush(ctx context.Context) error {
defer s.sync.addFlush()
return s.Sink.Flush(ctx)
}
func (s *notifyFlushSink) EncodeAndEmitRow(
ctx context.Context,
updatedRow cdcevent.Row,
prevRow cdcevent.Row,
topic TopicDescriptor,
updated, mvcc hlc.Timestamp,
alloc kvevent.Alloc,
) error {
if sinkWithEncoder, ok := s.Sink.(SinkWithEncoder); ok {
return sinkWithEncoder.EncodeAndEmitRow(ctx, updatedRow, prevRow, topic, updated, mvcc, alloc)
}
return errors.AssertionFailedf("Expected a sink with encoder for, found %T", s.Sink)
}
var _ Sink = (*notifyFlushSink)(nil)
// feedInjectable is the subset of the
// TestServerInterface/TestTenantInterface needed for depInjector to
// work correctly.
type feedInjectable interface {
JobRegistry() interface{}
DistSQLServer() interface{}
}
// depInjector facilitates dependency injection to provide orchestration
// between test feed and the changefeed itself.
// A single instance of depInjector should be used per feed factory.
// The reason we have have this dep injector (as opposed to configuring
// knobs directly) is that various knob settings are static (per sever).
// What we want is to have dependency injection per feed (since we can start
// multiple feeds inside a test).
type depInjector struct {
syncutil.Mutex
cond *sync.Cond
pendingJob *jobFeed
startedJobs map[jobspb.JobID]*jobFeed
}
// newDepInjector configures specified server with necessary hooks and knobs.
func newDepInjector(srvs ...feedInjectable) *depInjector {
di := &depInjector{
startedJobs: make(map[jobspb.JobID]*jobFeed),
}
di.cond = sync.NewCond(di)
for _, s := range srvs {
// Arrange for our wrapped sink to be instantiated.
s.DistSQLServer().(*distsql.ServerImpl).TestingKnobs.Changefeed.(*TestingKnobs).WrapSink =
func(s Sink, jobID jobspb.JobID) Sink {
f := di.getJobFeed(jobID)
return f.makeSink(s)
}
// Arrange for error reporting resumer to be used.
s.JobRegistry().(*jobs.Registry).TestingWrapResumerConstructor(
jobspb.TypeChangefeed,
func(raw jobs.Resumer) jobs.Resumer {
f := di.getJobFeed(raw.(*changefeedResumer).job.ID())
return &reportErrorResumer{
wrapped: raw,
jobFailed: func() {
f.jobFailed(f.FetchTerminalJobErr())
},
}
},
)
}
return di
}
// prepareJob must be called before starting the changefeed.
// it arranges for the pendingJob field to be initialized, which is needed
// when constructing "canary" sinks prior the changefeed resumer creation.
func (di *depInjector) prepareJob(jf *jobFeed) {
di.Lock()
defer di.Unlock()
// Wait for the previously set pendingJob to be nil (see startJob).
// Note: this is needed only if we create multiple feeds per feed factory rapidly.
for di.pendingJob != nil {
di.cond.Wait()
}
di.pendingJob = jf
}
// startJob must be called when changefeed job starts to register job feed
// with this dependency injector.
func (di *depInjector) startJob(jf *jobFeed) {
di.Lock()
defer di.Unlock()
if _, alreadyStarted := di.startedJobs[jf.jobID]; alreadyStarted {
panic("unexpected state: job already started")
}
if di.pendingJob != jf {
panic("expected pending job to be equal to started job")
}
di.startedJobs[jf.jobID] = jf
di.pendingJob = nil
di.cond.Broadcast()
}
// getJobFeed returns jobFeed associated with the specified jobID.
// This method blocks until the job actually starts (i.e. startJob has been called).
func (di *depInjector) getJobFeed(jobID jobspb.JobID) *jobFeed {
di.Lock()
defer di.Unlock()
for {
if f, started := di.startedJobs[jobID]; started {
return f
}
if di.pendingJob != nil {
return di.pendingJob
}
di.cond.Wait()
}
}
type enterpriseFeedFactory struct {
s serverutils.TestTenantInterface
di *depInjector
// db is used for creating changefeeds. This may be the same as rootDB.
db *gosql.DB
// rootDB is used for test internals.
rootDB *gosql.DB
}
func (e *enterpriseFeedFactory) configureUserDB(db *gosql.DB) {
e.db = db
}
func (e *enterpriseFeedFactory) jobsTableConn() *gosql.DB {
return e.rootDB
}
// AsUser uses the previous connection to ensure
// the user has the ability to authenticate, and saves it to poll
// job status, then implements TestFeedFactory.AsUser().
func (e *enterpriseFeedFactory) AsUser(user string, fn func(*sqlutils.SQLRunner)) error {
prevDB := e.db
defer func() { e.db = prevDB }()
password := `password`
_, err := e.rootDB.Exec(fmt.Sprintf(`ALTER USER %s WITH PASSWORD '%s'`, user, password))
if err != nil {
return err
}
pgURL := url.URL{
Scheme: "postgres",
User: url.UserPassword(user, password),
Host: e.s.SQLAddr(),
Path: `d`,
}
db2, err := gosql.Open("postgres", pgURL.String())
if err != nil {
return err
}
defer db2.Close()
userDB := sqlutils.MakeSQLRunner(db2)
e.db = db2
fn(userDB)
return nil
}
func (e enterpriseFeedFactory) startFeedJob(f *jobFeed, create string, args ...interface{}) error {
log.Infof(context.Background(), "Starting feed job: %q", create)
e.di.prepareJob(f)
if err := e.db.QueryRow(create, args...).Scan(&f.jobID); err != nil {
e.di.pendingJob = nil
return errors.Wrapf(err, "failed to start feed for job %d", f.jobID)
}
e.di.startJob(f)
return nil
}
type sinkForUser func(username string, password ...string) (uri url.URL, cleanup func())
type tableFeedFactory struct {
enterpriseFeedFactory
uri url.URL
}
func getInjectables(srvOrCluster interface{}) (serverutils.TestTenantInterface, []feedInjectable) {
switch t := srvOrCluster.(type) {
case serverutils.TestTenantInterface:
t.PGServer()
return t, []feedInjectable{t}
case serverutils.TestClusterInterface:
servers := make([]feedInjectable, t.NumServers())
for i := range servers {
servers[i] = t.Server(i)
}
return t.Server(0), servers
default:
panic(errors.AssertionFailedf("unexpected type %T", t))
}
}
// makeTableFeedFactory returns a TestFeedFactory implementation using the
// `experimental-sql` uri.
func makeTableFeedFactory(
srvOrCluster interface{}, rootDB *gosql.DB, sink url.URL,
) cdctest.TestFeedFactory {
s, injectables := getInjectables(srvOrCluster)
return &tableFeedFactory{
enterpriseFeedFactory: enterpriseFeedFactory{
s: s,
di: newDepInjector(injectables...),
db: rootDB,
rootDB: rootDB,
},
uri: sink,
}
}
// Feed implements the TestFeedFactory interface
func (f *tableFeedFactory) Feed(
create string, args ...interface{},
) (_ cdctest.TestFeed, err error) {
sinkURI := f.uri
sinkURI.Path = fmt.Sprintf(`table_%d`, timeutil.Now().UnixNano())
sinkDB, err := gosql.Open("postgres", sinkURI.String())
if err != nil {
return nil, err
}
defer func() {
if err != nil {
_ = sinkDB.Close()
}
}()
sinkURI.Scheme = `experimental-sql`
if _, err := sinkDB.Exec(`CREATE DATABASE ` + sinkURI.Path); err != nil {
return nil, err
}
ss := &sinkSynchronizer{}
wrapSink := func(s Sink) Sink {
return ¬ifyFlushSink{Sink: s, sync: ss}
}
c := &tableFeed{
jobFeed: newJobFeed(f.jobsTableConn(), wrapSink),
ss: ss,
seenTrackerMap: make(map[string]struct{}),
sinkDB: sinkDB,
}
parsed, err := parser.ParseOne(create)
if err != nil {
return nil, err
}
createStmt := parsed.AST.(*tree.CreateChangefeed)
if err := setURI(createStmt, sinkURI.String(), false, &args); err != nil {
return nil, err
}
if err := f.startFeedJob(c.jobFeed, createStmt.String(), args...); err != nil {
return nil, err
}
return c, nil
}
// Server implements the TestFeedFactory interface.
func (f *tableFeedFactory) Server() serverutils.TestTenantInterface {
return f.s
}
// tableFeed is a TestFeed implementation using the `experimental-sql` uri.
type tableFeed struct {
*jobFeed
seenTrackerMap
ss *sinkSynchronizer
sinkDB *gosql.DB // Changefeed emits messages into table in this DB.
toSend []*cdctest.TestFeedMessage
}
var _ cdctest.TestFeed = (*tableFeed)(nil)
// Partitions implements the TestFeed interface.
func (c *tableFeed) Partitions() []string {
// The sqlSink hardcodes these.
return []string{`0`, `1`, `2`}
}
func timeoutOp(op string, id jobspb.JobID) string {
return fmt.Sprintf("%s-%d", op, id)
}
// Next implements the TestFeed interface.
func (c *tableFeed) Next() (*cdctest.TestFeedMessage, error) {
// sinkSink writes all changes to a table with primary key of topic,
// partition, message_id. To simulate the semantics of kafka, message_ids
// are only comparable within a given (topic, partition). Internally the
// message ids are generated as a 64 bit int with a timestamp in bits 1-49
// and a hash of the partition in 50-64. This tableFeed.Next function works
// by repeatedly fetching and deleting all rows in the table. Then it pages
// through the results until they are empty and repeats.
for {
if len(c.toSend) > 0 {
toSend := c.toSend[0]
c.toSend = c.toSend[1:]
return toSend, nil
}
if err := contextutil.RunWithTimeout(
context.Background(), timeoutOp("tableFeed.Next", c.jobID), timeout(),
func(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-c.ss.eventReady():
return nil
case <-c.shutdown:
return c.terminalJobError()
}
},
); err != nil {
return nil, err
}
var toSend []*cdctest.TestFeedMessage
if err := crdb.ExecuteTx(context.Background(), c.sinkDB, nil, func(tx *gosql.Tx) error {
_, err := tx.Exec("SET TRANSACTION PRIORITY LOW")
if err != nil {
return err
}
toSend = nil // reset for this iteration
// TODO(dan): It's a bummer that this mutates the sqlsink table. I
// originally tried paging through message_id by repeatedly generating a
// new high-water with GenerateUniqueInt, but this was racy with rows
// being flushed out by the uri. An alternative is to steal the nanos
// part from `high_water_timestamp` in `crdb_internal.jobs` and run it
// through `builtins.GenerateUniqueID`, but that would mean we're only
// ever running tests on rows that have gotten a resolved timestamp,
// which seems limiting.
rows, err := tx.Query(
`SELECT * FROM [DELETE FROM sqlsink RETURNING *] ORDER BY topic, partition, message_id`)
if err != nil {
return err
}
for rows.Next() {
m := &cdctest.TestFeedMessage{}
var msgID int64
if err := rows.Scan(
&m.Topic, &m.Partition, &msgID, &m.Key, &m.Value, &m.Resolved,
); err != nil {
return err
}
// Scan turns NULL bytes columns into a 0-length, non-nil byte
// array, which is pretty unexpected. Nil them out before returning.
// Either key+value or payload will be set, but not both.
if len(m.Key) > 0 || len(m.Value) > 0 {
m.Resolved = nil
} else {
m.Key, m.Value = nil, nil
}
toSend = append(toSend, m)
}
return rows.Err()
}); err != nil {
return nil, err
}
for _, m := range toSend {
// NB: We should not filter seen keys in the query above -- doing so will
// result in flaky tests if txn gets restarted.
if len(m.Key) > 0 {
if isNew := c.markSeen(m); !isNew {
continue