-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathchangefeed_stmt.go
1691 lines (1528 loc) · 57.5 KB
/
changefeed_stmt.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"
"fmt"
"net/url"
"sort"
"time"
"github.com/cockroachdb/cockroach/pkg/ccl/backupccl/backupresolver"
"github.com/cockroachdb/cockroach/pkg/ccl/changefeedccl/cdceval"
"github.com/cockroachdb/cockroach/pkg/ccl/changefeedccl/changefeedbase"
"github.com/cockroachdb/cockroach/pkg/ccl/changefeedccl/changefeedvalidators"
"github.com/cockroachdb/cockroach/pkg/ccl/utilccl"
"github.com/cockroachdb/cockroach/pkg/cloud"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/docs"
"github.com/cockroachdb/cockroach/pkg/featureflag"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/protectedts"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/protectedts/ptpb"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/server/status"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"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"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/exprutil"
"github.com/cockroachdb/cockroach/pkg/sql/isql"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgnotice"
"github.com/cockroachdb/cockroach/pkg/sql/sem/asof"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondatapb"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"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/randutil"
"github.com/cockroachdb/cockroach/pkg/util/span"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/redact"
)
// featureChangefeedEnabled is used to enable and disable the CHANGEFEED feature.
var featureChangefeedEnabled = settings.RegisterBoolSetting(
settings.ApplicationLevel,
"feature.changefeed.enabled",
"set to true to enable changefeeds, false to disable; default is true",
featureflag.FeatureFlagEnabledDefault,
settings.WithPublic)
func init() {
sql.AddPlanHook("changefeed", changefeedPlanHook, changefeedTypeCheck)
jobs.RegisterConstructor(
jobspb.TypeChangefeed,
func(job *jobs.Job, _ *cluster.Settings) jobs.Resumer {
return &changefeedResumer{job: job}
},
jobs.UsesTenantCostControl,
)
}
type annotatedChangefeedStatement struct {
*tree.CreateChangefeed
originalSpecs map[tree.ChangefeedTarget]jobspb.ChangefeedTargetSpecification
alterChangefeedAsOf hlc.Timestamp
CreatedByInfo *jobs.CreatedByInfo
}
func getChangefeedStatement(stmt tree.Statement) *annotatedChangefeedStatement {
switch changefeed := stmt.(type) {
case *annotatedChangefeedStatement:
return changefeed
case *tree.CreateChangefeed:
return &annotatedChangefeedStatement{CreateChangefeed: changefeed}
default:
return nil
}
}
var (
sinklessHeader = colinfo.ResultColumns{
{Name: "table", Typ: types.String},
{Name: "key", Typ: types.Bytes},
{Name: "value", Typ: types.Bytes},
}
withSinkHeader = colinfo.ResultColumns{
{Name: "job_id", Typ: types.Int},
}
)
func changefeedTypeCheck(
ctx context.Context, stmt tree.Statement, p sql.PlanHookState,
) (matched bool, header colinfo.ResultColumns, _ error) {
changefeedStmt := getChangefeedStatement(stmt)
if changefeedStmt == nil {
return false, nil, nil
}
if err := exprutil.TypeCheck(ctx, `CREATE CHANGEFEED`, p.SemaCtx(),
exprutil.Strings{changefeedStmt.SinkURI},
&exprutil.KVOptions{
KVOptions: changefeedStmt.Options,
Validation: changefeedvalidators.CreateOptionValidations,
},
); err != nil {
return false, nil, err
}
unspecifiedSink := changefeedStmt.SinkURI == nil
if unspecifiedSink {
return true, sinklessHeader, nil
}
return true, withSinkHeader, nil
}
// changefeedPlanHook implements sql.PlanHookFn.
func changefeedPlanHook(
ctx context.Context, stmt tree.Statement, p sql.PlanHookState,
) (sql.PlanHookRowFn, colinfo.ResultColumns, []sql.PlanNode, bool, error) {
changefeedStmt := getChangefeedStatement(stmt)
if changefeedStmt == nil {
return nil, nil, nil, false, nil
}
exprEval := p.ExprEvaluator("CREATE CHANGEFEED")
var sinkURI string
unspecifiedSink := changefeedStmt.SinkURI == nil
avoidBuffering := unspecifiedSink
var header colinfo.ResultColumns
if unspecifiedSink {
// An unspecified sink triggers a fairly radical change in behavior.
// Instead of setting up a system.job to emit to a sink in the
// background and returning immediately with the job ID, the `CREATE
// CHANGEFEED` blocks forever and returns all changes as rows directly
// over pgwire. The types of these rows are `(topic STRING, key BYTES,
// value BYTES)` and they correspond exactly to what would be emitted to
// a sink.
avoidBuffering = true
header = sinklessHeader
} else {
var err error
sinkURI, err = exprEval.String(ctx, changefeedStmt.SinkURI)
if err != nil {
return nil, nil, nil, false, changefeedbase.MarkTaggedError(err, changefeedbase.UserInput)
}
header = withSinkHeader
}
rawOpts, err := exprEval.KVOptions(
ctx, changefeedStmt.Options, changefeedvalidators.CreateOptionValidations,
)
if err != nil {
return nil, nil, nil, false, err
}
// rowFn impements sql.PlanHookRowFn
rowFn := func(ctx context.Context, _ []sql.PlanNode, resultsCh chan<- tree.Datums) error {
ctx, span := tracing.ChildSpan(ctx, stmt.StatementTag())
defer span.Finish()
opts := changefeedbase.MakeStatementOptions(rawOpts)
st, err := opts.GetInitialScanType()
if err != nil {
return err
}
if err := validateSettings(ctx, st != changefeedbase.OnlyInitialScan, p.ExecCfg()); err != nil {
return err
}
if !unspecifiedSink && sinkURI == `` {
// Error if someone specifies an INTO with the empty string. We've
// already sent the wrong result column headers.
return errors.New(`omit the SINK clause for inline results`)
}
jr, err := createChangefeedJobRecord(
ctx,
p,
changefeedStmt,
sinkURI,
opts,
jobspb.InvalidJobID,
`changefeed.create`,
)
if err != nil {
return changefeedbase.MarkTaggedError(err, changefeedbase.UserInput)
}
details := jr.Details.(jobspb.ChangefeedDetails)
progress := jobspb.Progress{
Progress: &jobspb.Progress_HighWater{},
Details: &jobspb.Progress_Changefeed{
Changefeed: &jobspb.ChangefeedProgress{},
},
}
if details.SinkURI == `` {
// If this is a sinkless changefeed, then we should not hold on to the
// descriptor leases accessed to plan the changefeed. If changes happen
// to descriptors, they will be addressed during the execution.
// Failing to release the leases would result in preventing any schema
// changes on the relevant descriptors (including, potentially,
// system.role_membership, if the privileges to access the table were
// granted via an inherited role).
p.ExtendedEvalContext().Descs.ReleaseAll(ctx)
telemetry.Count(`changefeed.create.core`)
logChangefeedCreateTelemetry(ctx, jr, changefeedStmt.Select != nil)
err := coreChangefeed(ctx, p, details, progress, resultsCh)
// TODO(yevgeniy): This seems wrong -- core changefeeds always terminate
// with an error. Perhaps rename this telemetry to indicate number of
// completed feeds.
telemetry.Count(`changefeed.core.error`)
return err
}
// The below block creates the job and protects the data required for the
// changefeed to function from being garbage collected even if the
// changefeed lags behind the gcttl. We protect the data here rather than in
// Resume to shorten the window that data may be GC'd. The protected
// timestamps are updated to the highwater mark periodically during the
// execution of the changefeed by the changeFrontier. Protected timestamps
// are removed in OnFailOrCancel. See
// changeFrontier.manageProtectedTimestamps for more details on the handling
// of protected timestamps.
var sj *jobs.StartableJob
jobID := p.ExecCfg().JobRegistry.MakeJobID()
{
var ptr *ptpb.Record
codec := p.ExecCfg().Codec
ptr = createProtectedTimestampRecord(
ctx,
codec,
jobID,
AllTargets(details),
details.StatementTime,
)
progress.GetChangefeed().ProtectedTimestampRecord = ptr.ID.GetUUID()
jr.Progress = *progress.GetChangefeed()
if changefeedStmt.CreatedByInfo != nil {
// This changefeed statement invoked by the scheduler. As such, the scheduler
// must have specified transaction to use, and is responsible for committing
// transaction.
_, err := p.ExecCfg().JobRegistry.CreateAdoptableJobWithTxn(ctx, *jr, jobID, p.InternalSQLTxn())
if err != nil {
return err
}
if ptr != nil {
pts := p.ExecCfg().ProtectedTimestampProvider.WithTxn(p.InternalSQLTxn())
if err := pts.Protect(ctx, ptr); err != nil {
return err
}
}
select {
case <-ctx.Done():
return ctx.Err()
case resultsCh <- tree.Datums{
tree.NewDInt(tree.DInt(jobID)),
}:
return nil
}
}
if err := p.ExecCfg().InternalDB.Txn(ctx, func(ctx context.Context, txn isql.Txn) error {
if err := p.ExecCfg().JobRegistry.CreateStartableJobWithTxn(ctx, &sj, jobID, txn, *jr); err != nil {
return err
}
if ptr != nil {
return p.ExecCfg().ProtectedTimestampProvider.WithTxn(txn).Protect(ctx, ptr)
}
return nil
}); err != nil {
if sj != nil {
if err := sj.CleanupOnRollback(ctx); err != nil {
log.Warningf(ctx, "failed to cleanup aborted job: %v", err)
}
}
return err
}
}
// Start the job.
if err := sj.Start(ctx); err != nil {
return err
}
logChangefeedCreateTelemetry(ctx, jr, changefeedStmt.Select != nil)
select {
case <-ctx.Done():
return ctx.Err()
case resultsCh <- tree.Datums{
tree.NewDInt(tree.DInt(jobID)),
}:
return nil
}
}
rowFnLogErrors := func(ctx context.Context, pn []sql.PlanNode, resultsCh chan<- tree.Datums) error {
err := rowFn(ctx, pn, resultsCh)
if err != nil {
logChangefeedFailedTelemetry(ctx, nil, failureTypeForStartupError(err))
}
return err
}
return rowFnLogErrors, header, nil, avoidBuffering, nil
}
func coreChangefeed(
ctx context.Context,
p sql.PlanHookState,
details jobspb.ChangefeedDetails,
progress jobspb.Progress,
resultsCh chan<- tree.Datums,
) error {
localState := &cachedState{progress: progress}
p.ExtendedEvalContext().ChangefeedState = localState
knobs, _ := p.ExecCfg().DistSQLSrv.TestingKnobs.Changefeed.(*TestingKnobs)
for r := getRetry(ctx); r.Next(); {
if knobs != nil && knobs.BeforeDistChangefeed != nil {
knobs.BeforeDistChangefeed()
}
err := distChangefeedFlow(ctx, p, 0 /* jobID */, details, localState, resultsCh)
if err == nil {
return nil
}
if knobs != nil && knobs.HandleDistChangefeedError != nil {
err = knobs.HandleDistChangefeedError(err)
}
if err = changefeedbase.AsTerminalError(ctx, p.ExecCfg().LeaseManager, err); err != nil {
return err
}
// All other errors retry; but we'll use an up-to-date progress
// information which is saved in the localState.
}
return ctx.Err() // retry loop exits when context cancels.
}
func createChangefeedJobRecord(
ctx context.Context,
p sql.PlanHookState,
changefeedStmt *annotatedChangefeedStatement,
sinkURI string,
opts changefeedbase.StatementOptions,
jobID jobspb.JobID,
telemetryPath string,
) (*jobs.Record, error) {
unspecifiedSink := changefeedStmt.SinkURI == nil
for _, warning := range opts.DeprecationWarnings() {
p.BufferClientNotice(ctx, pgnotice.Newf("%s", warning))
}
jobDescription, err := changefeedJobDescription(ctx, changefeedStmt.CreateChangefeed, sinkURI, opts)
if err != nil {
return nil, err
}
statementTime := hlc.Timestamp{
WallTime: p.ExtendedEvalContext().GetStmtTimestamp().UnixNano(),
}
var initialHighWater hlc.Timestamp
evalTimestamp := func(s string) (hlc.Timestamp, error) {
if knobs, ok := p.ExecCfg().DistSQLSrv.TestingKnobs.Changefeed.(*TestingKnobs); ok {
if knobs != nil && knobs.OverrideCursor != nil {
s = knobs.OverrideCursor(&statementTime)
}
}
asOfClause := tree.AsOfClause{Expr: tree.NewStrVal(s)}
asOf, err := p.EvalAsOfTimestamp(ctx, asOfClause)
if err != nil {
return hlc.Timestamp{}, err
}
return asOf.Timestamp, nil
}
if opts.HasStartCursor() {
initialHighWater, err = evalTimestamp(opts.GetCursor())
if err != nil {
return nil, err
}
statementTime = initialHighWater
}
checkPrivs := true
if !changefeedStmt.alterChangefeedAsOf.IsEmpty() {
statementTime = changefeedStmt.alterChangefeedAsOf
// When altering a changefeed, we generate target descriptors below
// based on a timestamp in the past. For example, this may be the
// last highwater timestamp of a paused changefeed.
// This is a problem because any privilege checks done on these
// descriptors will be out of date.
// To solve this problem, we validate the descriptors
// in the alterChangefeedPlanHook at the statement time.
// Thus, we can skip the check here.
checkPrivs = false
}
endTime := hlc.Timestamp{}
if opts.HasEndTime() {
asOfClause := tree.AsOfClause{Expr: tree.NewStrVal(opts.GetEndTime())}
asOf, err := asof.Eval(ctx, asOfClause, p.SemaCtx(), &p.ExtendedEvalContext().Context)
if err != nil {
return nil, err
}
endTime = asOf.Timestamp
}
{
initialScanType, err := opts.GetInitialScanType()
if err != nil {
return nil, err
}
// TODO (zinger): Should we error or take the minimum
// if endTime is already set?
if initialScanType == changefeedbase.OnlyInitialScan {
endTime = statementTime
}
}
tableOnlyTargetList := tree.BackupTargetList{}
for _, t := range changefeedStmt.Targets {
tableOnlyTargetList.Tables.TablePatterns = append(tableOnlyTargetList.Tables.TablePatterns, t.TableName)
}
// This grabs table descriptors once to get their ids.
targetDescs, err := getTableDescriptors(ctx, p, &tableOnlyTargetList, statementTime, initialHighWater)
if err != nil {
return nil, err
}
targets, tables, err := getTargetsAndTables(ctx, p, targetDescs, changefeedStmt.Targets,
changefeedStmt.originalSpecs, opts.ShouldUseFullStatementTimeName(), sinkURI)
if err != nil {
return nil, err
}
tolerances := opts.GetCanHandle()
sd := p.SessionData().Clone()
// Add non-local session data state (localization, etc).
sessiondata.MarshalNonLocal(p.SessionData(), &sd.SessionData)
details := jobspb.ChangefeedDetails{
Tables: tables,
SinkURI: sinkURI,
StatementTime: statementTime,
EndTime: endTime,
TargetSpecifications: targets,
SessionData: &sd.SessionData,
}
specs := AllTargets(details)
hasSelectPrivOnAllTables := true
hasChangefeedPrivOnAllTables := true
for _, desc := range targetDescs {
if table, isTable := desc.(catalog.TableDescriptor); isTable {
if err := changefeedvalidators.ValidateTable(specs, table, tolerances); err != nil {
return nil, err
}
for _, warning := range changefeedvalidators.WarningsForTable(table, tolerances) {
p.BufferClientNotice(ctx, pgnotice.Newf("%s", warning))
}
hasSelect, hasChangefeed, err := checkPrivilegesForDescriptor(ctx, p, desc)
if err != nil {
return nil, err
}
hasSelectPrivOnAllTables = hasSelectPrivOnAllTables && hasSelect
hasChangefeedPrivOnAllTables = hasChangefeedPrivOnAllTables && hasChangefeed
}
}
if checkPrivs {
if err := authorizeUserToCreateChangefeed(ctx, p, sinkURI, hasSelectPrivOnAllTables, hasChangefeedPrivOnAllTables, opts.GetConfluentSchemaRegistry()); err != nil {
return nil, err
}
}
if changefeedStmt.Select != nil {
// Serialize changefeed expression.
normalized, withDiff, err := validateAndNormalizeChangefeedExpression(
ctx, p, opts, changefeedStmt.Select, targetDescs, targets, statementTime,
)
if err != nil {
return nil, err
}
if withDiff {
opts.ForceDiff()
} else if opts.IsSet(changefeedbase.OptDiff) {
// Expression didn't reference cdc_prev, but the diff option was specified.
// This only makes sense if we have wrapped envelope.
encopts, err := opts.GetEncodingOptions()
if err != nil {
return nil, err
}
if encopts.Envelope != changefeedbase.OptEnvelopeWrapped {
opts.ClearDiff()
p.BufferClientNotice(ctx, pgnotice.Newf(
"turning off unused %s option (expression <%s> does not use cdc_prev)",
changefeedbase.OptDiff, tree.AsString(normalized)))
}
}
// TODO: Set the default envelope to row here when using a sink and format
// that support it.
opts.SetDefaultEnvelope(changefeedbase.OptEnvelopeBare)
details.Select = cdceval.AsStringUnredacted(normalized)
}
// TODO(dan): In an attempt to present the most helpful error message to the
// user, the ordering requirements between all these usage validations have
// become extremely fragile and non-obvious.
//
// - `validateDetails` has to run first to fill in defaults for `envelope`
// and `format` if the user didn't specify them.
// - Then `getEncoder` is run to return any configuration errors.
// - Then the changefeed is opted in to `OptKeyInValue` for any cloud
// storage sink or webhook sink. Kafka etc have a key and value field in
// each message but cloud storage sinks and webhook sinks don't have
// anywhere to put the key. So if the key is not in the value, then for
// DELETEs there is no way to recover which key was deleted. We could make
// the user explicitly pass this option for every cloud storage sink/
// webhook sink and error if they don't, but that seems user-hostile for
// insufficient reason. We can't do this any earlier, because we might
// return errors about `key_in_value` being incompatible which is
// confusing when the user didn't type that option.
// This is the same for the topic and webhook sink, which uses
// `topic_in_value` to embed the topic in the value by default, since it
// has no other avenue to express the topic.
// - Finally, we create a "canary" sink to test sink configuration and
// connectivity. This has to go last because it is strange to return sink
// connectivity errors before we've finished validating all the other
// options. We should probably split sink configuration checking and sink
// connectivity checking into separate methods.
//
// The only upside in all this nonsense is the tests are decent. I've tuned
// this particular order simply by rearranging stuff until the changefeedccl
// tests all pass.
parsedSink, err := url.Parse(sinkURI)
if err != nil {
return nil, err
}
if newScheme, ok := changefeedbase.NoLongerExperimental[parsedSink.Scheme]; ok {
parsedSink.Scheme = newScheme // This gets munged anyway when building the sink
p.BufferClientNotice(ctx, pgnotice.Newf(`%[1]s is no longer experimental, use %[1]s://`,
newScheme),
)
}
if err = validateDetailsAndOptions(details, opts); err != nil {
return nil, err
}
// Validate the encoder. We can pass an empty slimetrics struct here since the encoder will not be used.
encodingOpts, err := opts.GetEncodingOptions()
if err != nil {
return nil, err
}
if _, err := getEncoder(ctx, encodingOpts, AllTargets(details), details.Select != "",
makeExternalConnectionProvider(ctx, p.ExecCfg().InternalDB), nil); err != nil {
return nil, err
}
if !unspecifiedSink && p.ExecCfg().ExternalIODirConfig.DisableOutbound {
return nil, errors.Errorf("Outbound IO is disabled by configuration, cannot create changefeed into %s", parsedSink.Scheme)
}
if telemetryPath != `` {
// Feature telemetry
telemetrySink := parsedSink.Scheme
if telemetrySink == `` {
telemetrySink = `sinkless`
}
telemetry.Count(telemetryPath + `.sink.` + telemetrySink)
telemetry.Count(telemetryPath + `.format.` + string(encodingOpts.Format))
telemetry.CountBucketed(telemetryPath+`.num_tables`, int64(len(tables)))
}
if scope, ok := opts.GetMetricScope(); ok {
if err := utilccl.CheckEnterpriseEnabled(
p.ExecCfg().Settings, "CHANGEFEED",
); err != nil {
return nil, errors.Wrapf(err,
"use of %q option requires an enterprise license.", changefeedbase.OptMetricsScope)
}
if scope == defaultSLIScope {
return nil, pgerror.Newf(pgcode.InvalidParameterValue,
"%[1]q=%[2]q is the default metrics scope which keeps track of statistics "+
"across all changefeeds without explicit label. "+
"If this is an intended behavior, please re-run the statement "+
"without specifying %[1]q parameter. "+
"Otherwise, please re-run with a different %[1]q value.",
changefeedbase.OptMetricsScope, defaultSLIScope)
}
if !status.ChildMetricsEnabled.Get(&p.ExecCfg().Settings.SV) {
p.BufferClientNotice(ctx, pgnotice.Newf(
"%s is set to false, metrics will only be published to the '%s' label when it is set to true",
status.ChildMetricsEnabled.Name(),
scope,
))
}
}
if details.SinkURI == `` {
if details.Select != `` {
if err := utilccl.CheckEnterpriseEnabled(
p.ExecCfg().Settings, "CHANGEFEED",
); err != nil {
return nil, errors.Wrap(err, "use of AS SELECT requires an enterprise license.")
}
}
details.Opts = opts.AsMap()
// Jobs should not be created for sinkless changefeeds. However, note that
// we create and return a job record for sinkless changefeeds below. This is
// because we need the details field to create our sinkless changefeed.
// After this job record is returned, we create our forever running sinkless
// changefeed, thus ensuring that no job is created for this changefeed as
// desired.
sinklessRecord := &jobs.Record{
Details: details,
}
return sinklessRecord, nil
}
if err := utilccl.CheckEnterpriseEnabled(
p.ExecCfg().Settings, "CHANGEFEED",
); err != nil {
return nil, err
}
if telemetryPath != `` {
telemetry.Count(telemetryPath + `.enterprise`)
}
// TODO (zinger): validateSink shouldn't need details, remove that so we only
// need to have this line once.
details.Opts = opts.AsMap()
// In the case where a user is executing a CREATE CHANGEFEED and is still
// waiting for the statement to return, we take the opportunity to ensure
// that the user has not made any obvious errors when specifying the sink in
// the CREATE CHANGEFEED statement. To do this, we create a "canary" sink,
// which will be immediately closed, only to check for errors.
// We also check here for any options that have passed previous validations
// but are inappropriate for the provided sink.
// TODO: Ideally those option validations would happen in validateDetails()
// earlier, like the others.
err = validateSink(ctx, p, jobID, details, opts)
if err != nil {
return nil, err
}
details.Opts = opts.AsMap()
if locFilter := details.Opts[changefeedbase.OptExecutionLocality]; locFilter != "" {
if !p.ExecCfg().Settings.Version.IsActive(ctx, clusterversion.TODODelete_V23_1) {
return nil, pgerror.Newf(
pgcode.FeatureNotSupported,
"cannot create new changefeed with %s until upgrade to version %s is complete",
changefeedbase.OptExecutionLocality, clusterversion.TODODelete_V23_1.String(),
)
}
if err := utilccl.CheckEnterpriseEnabled(
p.ExecCfg().Settings, changefeedbase.OptExecutionLocality,
); err != nil {
return nil, err
}
var executionLocality roachpb.Locality
if err := executionLocality.Set(locFilter); err != nil {
return nil, err
}
if _, err := p.DistSQLPlanner().GetAllInstancesByLocality(ctx, executionLocality); err != nil {
return nil, err
}
}
ptsExpiration, err := opts.GetPTSExpiration()
if err != nil {
return nil, err
}
useDefaultExpiration := ptsExpiration == 0
if useDefaultExpiration {
ptsExpiration = changefeedbase.MaxProtectedTimestampAge.Get(&p.ExecCfg().Settings.SV)
}
if ptsExpiration > 0 && ptsExpiration < time.Hour {
// This threshold is rather arbitrary. But we want to warn users about
// the potential impact of keeping this setting too low.
const explainer = `Having a low protected timestamp expiration value should not have adverse effect
as long as changefeed is running. However, should the changefeed be paused, it
will need to be resumed before expiration time. The value of this setting should
reflect how much time he changefeed may remain paused, before it is canceled.
Few hours to a few days range are appropriate values for this option.`
if useDefaultExpiration {
p.BufferClientNotice(ctx, pgnotice.Newf(
`the value of %s for changefeed.protect_timestamp.max_age setting might be too low. %s`,
ptsExpiration, changefeedbase.OptExpirePTSAfter, explainer))
} else {
p.BufferClientNotice(ctx, pgnotice.Newf(
`the value of %s for changefeed option %s might be too low. %s`,
ptsExpiration, changefeedbase.OptExpirePTSAfter, explainer))
}
}
jr := &jobs.Record{
Description: jobDescription,
Username: p.User(),
DescriptorIDs: func() (sqlDescIDs []descpb.ID) {
for _, desc := range targetDescs {
sqlDescIDs = append(sqlDescIDs, desc.GetID())
}
return sqlDescIDs
}(),
Details: details,
CreatedBy: changefeedStmt.CreatedByInfo,
MaximumPTSAge: ptsExpiration,
}
return jr, nil
}
func validateSettings(ctx context.Context, needsRangeFeed bool, execCfg *sql.ExecutorConfig) error {
if err := featureflag.CheckEnabled(
ctx,
execCfg,
featureChangefeedEnabled,
"CHANGEFEED",
); err != nil {
return err
}
// Changefeeds are based on the Rangefeed abstraction, which
// requires the `kv.rangefeed.enabled` setting to be true.
if needsRangeFeed && !kvserver.RangefeedEnabled.Get(&execCfg.Settings.SV) {
return errors.Errorf("rangefeeds require the kv.rangefeed.enabled setting. See %s",
docs.URL(`change-data-capture.html#enable-rangefeeds-to-reduce-latency`))
}
return nil
}
func getTableDescriptors(
ctx context.Context,
p sql.PlanHookState,
targets *tree.BackupTargetList,
statementTime hlc.Timestamp,
initialHighWater hlc.Timestamp,
) (map[tree.TablePattern]catalog.Descriptor, error) {
// For now, disallow targeting a database or wildcard table selection.
// Getting it right as tables enter and leave the set over time is
// tricky.
if len(targets.Databases) > 0 {
return nil, errors.Errorf(`CHANGEFEED cannot target %s`,
tree.AsString(targets))
}
for _, t := range targets.Tables.TablePatterns {
p, err := t.NormalizeTablePattern()
if err != nil {
return nil, err
}
if _, ok := p.(*tree.TableName); !ok {
return nil, errors.Errorf(`CHANGEFEED cannot target %s`, tree.AsString(t))
}
}
_, _, _, targetDescs, err := backupresolver.ResolveTargetsToDescriptors(ctx, p, statementTime, targets)
if err != nil {
var m *backupresolver.MissingTableErr
if errors.As(err, &m) {
tableName := m.GetTableName()
err = errors.Errorf("table %q does not exist", tableName)
}
err = errors.Wrap(err, "failed to resolve targets in the CHANGEFEED stmt")
if !initialHighWater.IsEmpty() {
// We specified cursor -- it is possible the targets do not exist at that time.
// Give a bit more context in the error message.
err = errors.WithHintf(err,
"do the targets exist at the specified cursor time %s?", initialHighWater)
}
}
return targetDescs, err
}
func getTargetsAndTables(
ctx context.Context,
p sql.PlanHookState,
targetDescs map[tree.TablePattern]catalog.Descriptor,
rawTargets tree.ChangefeedTargets,
originalSpecs map[tree.ChangefeedTarget]jobspb.ChangefeedTargetSpecification,
fullTableName bool,
sinkURI string,
) ([]jobspb.ChangefeedTargetSpecification, jobspb.ChangefeedTargets, error) {
tables := make(jobspb.ChangefeedTargets, len(targetDescs))
targets := make([]jobspb.ChangefeedTargetSpecification, len(rawTargets))
seen := make(map[jobspb.ChangefeedTargetSpecification]tree.ChangefeedTarget)
for i, ct := range rawTargets {
desc, ok := targetDescs[ct.TableName]
if !ok {
return nil, nil, errors.Newf("could not match %v to a fetched descriptor. Fetched were %v", ct.TableName, targetDescs)
}
td, ok := desc.(catalog.TableDescriptor)
if !ok {
return nil, nil, errors.Errorf(`CHANGEFEED cannot target %s`, tree.AsString(&ct))
}
if spec, ok := originalSpecs[ct]; ok {
targets[i] = spec
if table, ok := tables[td.GetID()]; ok {
if table.StatementTimeName != spec.StatementTimeName {
return nil, nil, errors.Errorf(
`table with id %d is referenced with multiple statement time names: %q and %q`, td.GetID(),
table.StatementTimeName, spec.StatementTimeName)
}
} else {
tables[td.GetID()] = jobspb.ChangefeedTargetTable{
StatementTimeName: spec.StatementTimeName,
}
}
} else {
name, err := getChangefeedTargetName(ctx, td, p.ExecCfg(), p.Txn(), fullTableName)
if err != nil {
return nil, nil, err
}
tables[td.GetID()] = jobspb.ChangefeedTargetTable{
StatementTimeName: name,
}
typ := jobspb.ChangefeedTargetSpecification_PRIMARY_FAMILY_ONLY
if ct.FamilyName != "" {
typ = jobspb.ChangefeedTargetSpecification_COLUMN_FAMILY
} else {
if td.NumFamilies() > 1 {
typ = jobspb.ChangefeedTargetSpecification_EACH_FAMILY
}
}
targets[i] = jobspb.ChangefeedTargetSpecification{
Type: typ,
TableID: td.GetID(),
FamilyName: string(ct.FamilyName),
StatementTimeName: tables[td.GetID()].StatementTimeName,
}
}
if dup, isDup := seen[targets[i]]; isDup {
return nil, nil, errors.Errorf(
"CHANGEFEED targets %s and %s are duplicates",
tree.AsString(&dup), tree.AsString(&ct),
)
}
seen[targets[i]] = ct
}
return targets, tables, nil
}
func validateSink(
ctx context.Context,
p sql.PlanHookState,
jobID jobspb.JobID,
details jobspb.ChangefeedDetails,
opts changefeedbase.StatementOptions,
) error {
metrics := p.ExecCfg().JobRegistry.MetricsStruct().Changefeed.(*Metrics)
scope, _ := opts.GetMetricScope()
sli, err := metrics.getSLIMetrics(scope)
if err != nil {
return err
}
u, err := url.Parse(details.SinkURI)
if err != nil {
return err
}
ambiguousSchemes := map[string][2]string{
changefeedbase.DeprecatedSinkSchemeHTTP: {changefeedbase.SinkSchemeCloudStorageHTTP, changefeedbase.SinkSchemeWebhookHTTP},
changefeedbase.DeprecatedSinkSchemeHTTPS: {changefeedbase.SinkSchemeCloudStorageHTTPS, changefeedbase.SinkSchemeWebhookHTTPS},
}
if disambiguations, isAmbiguous := ambiguousSchemes[u.Scheme]; isAmbiguous {
p.BufferClientNotice(ctx, pgnotice.Newf(
`Interpreting deprecated URI scheme %s as %s. For webhook semantics, use %s.`,
u.Scheme,
disambiguations[0],
disambiguations[1],
))
}
var nilOracle timestampLowerBoundOracle
canarySink, err := getAndDialSink(ctx, &p.ExecCfg().DistSQLSrv.ServerConfig, details,
nilOracle, p.User(), jobID, sli)
if err != nil {
return err
}
if err := canarySink.Close(); err != nil {
return err
}
// If there's no projection we may need to force some options to ensure messages
// have enough information.
if details.Select == `` {
if requiresKeyInValue(canarySink) {
if err = opts.ForceKeyInValue(); err != nil {
return err
}
}
if requiresTopicInValue(canarySink) {
if err = opts.ForceTopicInValue(); err != nil {
return err
}
}
}
if sink, ok := canarySink.(SinkWithTopics); ok {
if opts.IsSet(changefeedbase.OptResolvedTimestamps) &&
opts.IsSet(changefeedbase.OptSplitColumnFamilies) {
return errors.Newf("Resolved timestamps are not currently supported with %s for this sink"+
" as the set of topics to fan them out to may change. Instead, use TABLE tablename FAMILY familyname"+
" to specify individual families to watch.", changefeedbase.OptSplitColumnFamilies)
}
topics := sink.Topics()
for _, topic := range topics {
p.BufferClientNotice(ctx, pgnotice.Newf(`changefeed will emit to topic %s`, topic))
}
opts.SetTopics(topics)
}
return nil
}
func requiresKeyInValue(s Sink) bool {
switch s.getConcreteType() {
case sinkTypeCloudstorage, sinkTypeWebhook:
return true
default:
return false
}
}
func requiresTopicInValue(s Sink) bool {
return s.getConcreteType() == sinkTypeWebhook
}
func changefeedJobDescription(
ctx context.Context,
changefeed *tree.CreateChangefeed,
sinkURI string,
opts changefeedbase.StatementOptions,
) (string, error) {
// Redacts user sensitive information from job description.
cleanedSinkURI, err := cloud.SanitizeExternalStorageURI(sinkURI, []string{
changefeedbase.SinkParamSASLPassword,
changefeedbase.SinkParamCACert,
changefeedbase.SinkParamClientCert,
changefeedbase.SinkParamClientKey,
changefeedbase.SinkParamConfluentAPISecret,
changefeedbase.SinkParamAzureAccessKey,
})
if err != nil {
return "", err
}
cleanedSinkURI, err = changefeedbase.RedactUserFromURI(cleanedSinkURI)
if err != nil {
return "", err
}
logSanitizedChangefeedDestination(ctx, cleanedSinkURI)