-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
backfilling_operators.go
870 lines (788 loc) · 23.6 KB
/
backfilling_operators.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
// Copyright 2023 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ddl
import (
"context"
"encoding/hex"
"fmt"
"path"
"strconv"
"sync/atomic"
"time"
"github.com/docker/go-units"
"github.com/google/uuid"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/tidb/br/pkg/storage"
"github.com/pingcap/tidb/pkg/ddl/copr"
"github.com/pingcap/tidb/pkg/ddl/ingest"
"github.com/pingcap/tidb/pkg/ddl/internal/session"
"github.com/pingcap/tidb/pkg/disttask/framework/proto"
"github.com/pingcap/tidb/pkg/disttask/operator"
"github.com/pingcap/tidb/pkg/kv"
"github.com/pingcap/tidb/pkg/lightning/backend/external"
"github.com/pingcap/tidb/pkg/lightning/common"
"github.com/pingcap/tidb/pkg/metrics"
"github.com/pingcap/tidb/pkg/parser/model"
"github.com/pingcap/tidb/pkg/parser/terror"
"github.com/pingcap/tidb/pkg/resourcemanager/pool/workerpool"
"github.com/pingcap/tidb/pkg/resourcemanager/util"
"github.com/pingcap/tidb/pkg/sessionctx"
"github.com/pingcap/tidb/pkg/table"
"github.com/pingcap/tidb/pkg/table/tables"
"github.com/pingcap/tidb/pkg/tablecodec"
tidbutil "github.com/pingcap/tidb/pkg/util"
"github.com/pingcap/tidb/pkg/util/chunk"
"github.com/pingcap/tidb/pkg/util/logutil"
"github.com/pingcap/tidb/pkg/util/size"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
)
var (
_ operator.Operator = (*TableScanTaskSource)(nil)
_ operator.WithSink[TableScanTask] = (*TableScanTaskSource)(nil)
_ operator.WithSource[TableScanTask] = (*TableScanOperator)(nil)
_ operator.Operator = (*TableScanOperator)(nil)
_ operator.WithSink[IndexRecordChunk] = (*TableScanOperator)(nil)
_ operator.WithSource[IndexRecordChunk] = (*IndexIngestOperator)(nil)
_ operator.Operator = (*IndexIngestOperator)(nil)
_ operator.WithSink[IndexWriteResult] = (*IndexIngestOperator)(nil)
_ operator.WithSource[IndexWriteResult] = (*indexWriteResultSink)(nil)
_ operator.Operator = (*indexWriteResultSink)(nil)
)
type opSessPool interface {
Get() (sessionctx.Context, error)
Put(sessionctx.Context)
}
// OperatorCtx is the context for AddIndexIngestPipeline.
// This is used to cancel the pipeline and collect errors.
type OperatorCtx struct {
context.Context
cancel context.CancelFunc
err atomic.Pointer[error]
}
// NewOperatorCtx creates a new OperatorCtx.
func NewOperatorCtx(ctx context.Context, taskID, subtaskID int64) *OperatorCtx {
opCtx, cancel := context.WithCancel(ctx)
opCtx = logutil.WithFields(opCtx, zap.Int64("task-id", taskID), zap.Int64("subtask-id", subtaskID))
return &OperatorCtx{
Context: opCtx,
cancel: cancel,
}
}
func (ctx *OperatorCtx) onError(err error) {
tracedErr := errors.Trace(err)
ctx.cancel()
ctx.err.CompareAndSwap(nil, &tracedErr)
}
// Cancel cancels the pipeline.
func (ctx *OperatorCtx) Cancel() {
ctx.cancel()
}
// OperatorErr returns the error of the operator.
func (ctx *OperatorCtx) OperatorErr() error {
err := ctx.err.Load()
if err == nil {
return nil
}
return *err
}
// NewAddIndexIngestPipeline creates a pipeline for adding index in ingest mode.
func NewAddIndexIngestPipeline(
ctx *OperatorCtx,
store kv.Storage,
sessPool opSessPool,
backendCtx ingest.BackendCtx,
engines []ingest.Engine,
sessCtx sessionctx.Context,
jobID int64,
tbl table.PhysicalTable,
idxInfos []*model.IndexInfo,
startKey, endKey kv.Key,
totalRowCount *atomic.Int64,
metricCounter prometheus.Counter,
reorgMeta *model.DDLReorgMeta,
avgRowSize int,
concurrency int,
) (*operator.AsyncPipeline, error) {
indexes := make([]table.Index, 0, len(idxInfos))
for _, idxInfo := range idxInfos {
index := tables.NewIndex(tbl.GetPhysicalID(), tbl.Meta(), idxInfo)
indexes = append(indexes, index)
}
reqSrc := getDDLRequestSource(model.ActionAddIndex)
copCtx, err := copr.NewCopContext(tbl.Meta(), idxInfos, sessCtx, reqSrc)
if err != nil {
return nil, err
}
poolSize := copReadChunkPoolSize()
srcChkPool := make(chan *chunk.Chunk, poolSize)
for i := 0; i < poolSize; i++ {
srcChkPool <- chunk.NewChunkWithCapacity(copCtx.GetBase().FieldTypes, copReadBatchSize())
}
readerCnt, writerCnt := expectedIngestWorkerCnt(concurrency, avgRowSize)
srcOp := NewTableScanTaskSource(ctx, store, tbl, startKey, endKey)
scanOp := NewTableScanOperator(ctx, sessPool, copCtx, srcChkPool, readerCnt)
ingestOp := NewIndexIngestOperator(ctx, copCtx, backendCtx, sessPool, tbl, indexes, engines, srcChkPool, writerCnt, reorgMeta)
sinkOp := newIndexWriteResultSink(ctx, backendCtx, tbl, indexes, totalRowCount, metricCounter)
operator.Compose[TableScanTask](srcOp, scanOp)
operator.Compose[IndexRecordChunk](scanOp, ingestOp)
operator.Compose[IndexWriteResult](ingestOp, sinkOp)
logutil.Logger(ctx).Info("build add index local storage operators",
zap.Int64("jobID", jobID),
zap.Int("avgRowSize", avgRowSize),
zap.Int("reader", readerCnt),
zap.Int("writer", writerCnt))
return operator.NewAsyncPipeline(
srcOp, scanOp, ingestOp, sinkOp,
), nil
}
// NewWriteIndexToExternalStoragePipeline creates a pipeline for writing index to external storage.
func NewWriteIndexToExternalStoragePipeline(
ctx *OperatorCtx,
store kv.Storage,
extStoreURI string,
sessPool opSessPool,
sessCtx sessionctx.Context,
jobID, subtaskID int64,
tbl table.PhysicalTable,
idxInfos []*model.IndexInfo,
startKey, endKey kv.Key,
totalRowCount *atomic.Int64,
metricCounter prometheus.Counter,
onClose external.OnCloseFunc,
reorgMeta *model.DDLReorgMeta,
avgRowSize int,
concurrency int,
resource *proto.StepResource,
) (*operator.AsyncPipeline, error) {
indexes := make([]table.Index, 0, len(idxInfos))
for _, idxInfo := range idxInfos {
index := tables.NewIndex(tbl.GetPhysicalID(), tbl.Meta(), idxInfo)
indexes = append(indexes, index)
}
reqSrc := getDDLRequestSource(model.ActionAddIndex)
copCtx, err := copr.NewCopContext(tbl.Meta(), idxInfos, sessCtx, reqSrc)
if err != nil {
return nil, err
}
poolSize := copReadChunkPoolSize()
srcChkPool := make(chan *chunk.Chunk, poolSize)
for i := 0; i < poolSize; i++ {
srcChkPool <- chunk.NewChunkWithCapacity(copCtx.GetBase().FieldTypes, copReadBatchSize())
}
readerCnt, writerCnt := expectedIngestWorkerCnt(concurrency, avgRowSize)
backend, err := storage.ParseBackend(extStoreURI, nil)
if err != nil {
return nil, err
}
extStore, err := storage.NewWithDefaultOpt(ctx, backend)
if err != nil {
return nil, err
}
memCap := resource.Mem.Capacity()
memSizePerIndex := uint64(memCap / int64(writerCnt*2*len(idxInfos)))
failpoint.Inject("mockWriterMemSize", func() {
memSizePerIndex = 1 * size.GB
})
srcOp := NewTableScanTaskSource(ctx, store, tbl, startKey, endKey)
scanOp := NewTableScanOperator(ctx, sessPool, copCtx, srcChkPool, readerCnt)
writeOp := NewWriteExternalStoreOperator(
ctx, copCtx, sessPool, jobID, subtaskID, tbl, indexes, extStore, srcChkPool, writerCnt, onClose, memSizePerIndex, reorgMeta)
sinkOp := newIndexWriteResultSink(ctx, nil, tbl, indexes, totalRowCount, metricCounter)
operator.Compose[TableScanTask](srcOp, scanOp)
operator.Compose[IndexRecordChunk](scanOp, writeOp)
operator.Compose[IndexWriteResult](writeOp, sinkOp)
logutil.Logger(ctx).Info("build add index cloud storage operators",
zap.Int64("jobID", jobID),
zap.String("memCap", units.BytesSize(float64(memCap))),
zap.String("memSizePerIdx", units.BytesSize(float64(memSizePerIndex))),
zap.Int("avgRowSize", avgRowSize),
zap.Int("reader", readerCnt),
zap.Int("writer", writerCnt))
return operator.NewAsyncPipeline(
srcOp, scanOp, writeOp, sinkOp,
), nil
}
// TableScanTask contains the start key and the end key of a region.
type TableScanTask struct {
ID int
Start kv.Key
End kv.Key
}
// String implement fmt.Stringer interface.
func (t TableScanTask) String() string {
return fmt.Sprintf("TableScanTask: id=%d, startKey=%s, endKey=%s",
t.ID, hex.EncodeToString(t.Start), hex.EncodeToString(t.End))
}
// IndexRecordChunk contains one of the chunk read from corresponding TableScanTask.
type IndexRecordChunk struct {
ID int
Chunk *chunk.Chunk
Err error
Done bool
}
// TableScanTaskSource produces TableScanTask by splitting table records into ranges.
type TableScanTaskSource struct {
ctx context.Context
errGroup errgroup.Group
sink operator.DataChannel[TableScanTask]
tbl table.PhysicalTable
store kv.Storage
startKey kv.Key
endKey kv.Key
}
// NewTableScanTaskSource creates a new TableScanTaskSource.
func NewTableScanTaskSource(
ctx context.Context,
store kv.Storage,
physicalTable table.PhysicalTable,
startKey kv.Key,
endKey kv.Key,
) *TableScanTaskSource {
return &TableScanTaskSource{
ctx: ctx,
errGroup: errgroup.Group{},
tbl: physicalTable,
store: store,
startKey: startKey,
endKey: endKey,
}
}
// SetSink implements WithSink interface.
func (src *TableScanTaskSource) SetSink(sink operator.DataChannel[TableScanTask]) {
src.sink = sink
}
// Open implements Operator interface.
func (src *TableScanTaskSource) Open() error {
src.errGroup.Go(src.generateTasks)
return nil
}
func (src *TableScanTaskSource) generateTasks() error {
taskIDAlloc := newTaskIDAllocator()
defer src.sink.Finish()
startKey := src.startKey
endKey := src.endKey
for {
kvRanges, err := splitTableRanges(
src.ctx,
src.tbl,
src.store,
startKey,
endKey,
backfillTaskChanSize,
)
if err != nil {
return err
}
if len(kvRanges) == 0 {
break
}
batchTasks := src.getBatchTableScanTask(kvRanges, taskIDAlloc)
for _, task := range batchTasks {
select {
case <-src.ctx.Done():
return src.ctx.Err()
case src.sink.Channel() <- task:
}
}
startKey = kvRanges[len(kvRanges)-1].EndKey
if startKey.Cmp(endKey) >= 0 {
break
}
}
return nil
}
func (src *TableScanTaskSource) getBatchTableScanTask(
kvRanges []kv.KeyRange,
taskIDAlloc *taskIDAllocator,
) []TableScanTask {
batchTasks := make([]TableScanTask, 0, len(kvRanges))
prefix := src.tbl.RecordPrefix()
// Build reorg tasks.
for _, keyRange := range kvRanges {
taskID := taskIDAlloc.alloc()
startKey := keyRange.StartKey
if len(startKey) == 0 {
startKey = prefix
}
endKey := keyRange.EndKey
if len(endKey) == 0 {
endKey = prefix.PrefixNext()
}
task := TableScanTask{
ID: taskID,
Start: startKey,
End: endKey,
}
batchTasks = append(batchTasks, task)
}
return batchTasks
}
// Close implements Operator interface.
func (src *TableScanTaskSource) Close() error {
return src.errGroup.Wait()
}
// String implements fmt.Stringer interface.
func (*TableScanTaskSource) String() string {
return "TableScanTaskSource"
}
// TableScanOperator scans table records in given key ranges from kv store.
type TableScanOperator struct {
*operator.AsyncOperator[TableScanTask, IndexRecordChunk]
}
// NewTableScanOperator creates a new TableScanOperator.
func NewTableScanOperator(
ctx *OperatorCtx,
sessPool opSessPool,
copCtx copr.CopContext,
srcChkPool chan *chunk.Chunk,
concurrency int,
) *TableScanOperator {
pool := workerpool.NewWorkerPool(
"TableScanOperator",
util.DDL,
concurrency,
func() workerpool.Worker[TableScanTask, IndexRecordChunk] {
return &tableScanWorker{
ctx: ctx,
copCtx: copCtx,
sessPool: sessPool,
se: nil,
srcChkPool: srcChkPool,
}
})
return &TableScanOperator{
AsyncOperator: operator.NewAsyncOperator[TableScanTask, IndexRecordChunk](ctx, pool),
}
}
type tableScanWorker struct {
ctx *OperatorCtx
copCtx copr.CopContext
sessPool opSessPool
se *session.Session
srcChkPool chan *chunk.Chunk
}
func (w *tableScanWorker) HandleTask(task TableScanTask, sender func(IndexRecordChunk)) {
defer tidbutil.Recover(metrics.LblAddIndex, "handleTableScanTaskWithRecover", func() {
w.ctx.onError(errors.New("met panic in tableScanWorker"))
}, false)
failpoint.Inject("injectPanicForTableScan", func() {
panic("mock panic")
})
if w.se == nil {
sessCtx, err := w.sessPool.Get()
if err != nil {
logutil.Logger(w.ctx).Error("tableScanWorker get session from pool failed", zap.Error(err))
w.ctx.onError(err)
return
}
w.se = session.NewSession(sessCtx)
}
w.scanRecords(task, sender)
}
func (w *tableScanWorker) Close() {
if w.se != nil {
w.sessPool.Put(w.se.Context)
}
}
// OperatorCallBackForTest is used for test to mock scan record error.
var OperatorCallBackForTest func()
func (w *tableScanWorker) scanRecords(task TableScanTask, sender func(IndexRecordChunk)) {
logutil.Logger(w.ctx).Info("start a table scan task",
zap.Int("id", task.ID), zap.Stringer("task", task))
var idxResult IndexRecordChunk
err := wrapInBeginRollback(w.se, func(startTS uint64) error {
failpoint.Inject("mockScanRecordError", func(_ failpoint.Value) {
failpoint.Return(errors.New("mock scan record error"))
})
failpoint.Inject("scanRecordExec", func(_ failpoint.Value) {
OperatorCallBackForTest()
})
rs, err := buildTableScan(w.ctx, w.copCtx.GetBase(), startTS, task.Start, task.End)
if err != nil {
return err
}
var done bool
for !done {
srcChk := w.getChunk()
done, err = fetchTableScanResult(w.ctx, w.copCtx.GetBase(), rs, srcChk)
if err != nil || w.ctx.Err() != nil {
w.recycleChunk(srcChk)
terror.Call(rs.Close)
return err
}
idxResult = IndexRecordChunk{ID: task.ID, Chunk: srcChk, Done: done}
sender(idxResult)
}
return rs.Close()
})
if err != nil {
w.ctx.onError(err)
}
}
func (w *tableScanWorker) getChunk() *chunk.Chunk {
chk := <-w.srcChkPool
newCap := copReadBatchSize()
if chk.Capacity() != newCap {
chk = chunk.NewChunkWithCapacity(w.copCtx.GetBase().FieldTypes, newCap)
}
chk.Reset()
return chk
}
func (w *tableScanWorker) recycleChunk(chk *chunk.Chunk) {
w.srcChkPool <- chk
}
// WriteExternalStoreOperator writes index records to external storage.
type WriteExternalStoreOperator struct {
*operator.AsyncOperator[IndexRecordChunk, IndexWriteResult]
}
// NewWriteExternalStoreOperator creates a new WriteExternalStoreOperator.
func NewWriteExternalStoreOperator(
ctx *OperatorCtx,
copCtx copr.CopContext,
sessPool opSessPool,
jobID int64,
subtaskID int64,
tbl table.PhysicalTable,
indexes []table.Index,
store storage.ExternalStorage,
srcChunkPool chan *chunk.Chunk,
concurrency int,
onClose external.OnCloseFunc,
memoryQuota uint64,
reorgMeta *model.DDLReorgMeta,
) *WriteExternalStoreOperator {
pool := workerpool.NewWorkerPool(
"WriteExternalStoreOperator",
util.DDL,
concurrency,
func() workerpool.Worker[IndexRecordChunk, IndexWriteResult] {
writers := make([]ingest.Writer, 0, len(indexes))
for i, index := range indexes {
builder := external.NewWriterBuilder().
SetOnCloseFunc(onClose).
SetKeyDuplicationEncoding(index.Meta().Unique).
SetMemorySizeLimit(memoryQuota).
SetGroupOffset(i)
writerID := uuid.New().String()
prefix := path.Join(strconv.Itoa(int(jobID)), strconv.Itoa(int(subtaskID)))
writer := builder.Build(store, prefix, writerID)
writers = append(writers, writer)
}
return &indexIngestExternalWorker{
indexIngestBaseWorker: indexIngestBaseWorker{
ctx: ctx,
tbl: tbl,
indexes: indexes,
copCtx: copCtx,
se: nil,
sessPool: sessPool,
writers: writers,
srcChunkPool: srcChunkPool,
reorgMeta: reorgMeta,
},
}
})
return &WriteExternalStoreOperator{
AsyncOperator: operator.NewAsyncOperator[IndexRecordChunk, IndexWriteResult](ctx, pool),
}
}
// IndexWriteResult contains the result of writing index records to ingest engine.
type IndexWriteResult struct {
ID int
Added int
Total int
Next kv.Key
}
// IndexIngestOperator writes index records to ingest engine.
type IndexIngestOperator struct {
*operator.AsyncOperator[IndexRecordChunk, IndexWriteResult]
}
// NewIndexIngestOperator creates a new IndexIngestOperator.
func NewIndexIngestOperator(
ctx *OperatorCtx,
copCtx copr.CopContext,
backendCtx ingest.BackendCtx,
sessPool opSessPool,
tbl table.PhysicalTable,
indexes []table.Index,
engines []ingest.Engine,
srcChunkPool chan *chunk.Chunk,
concurrency int,
reorgMeta *model.DDLReorgMeta,
) *IndexIngestOperator {
var writerIDAlloc atomic.Int32
pool := workerpool.NewWorkerPool(
"indexIngestOperator",
util.DDL,
concurrency,
func() workerpool.Worker[IndexRecordChunk, IndexWriteResult] {
writers := make([]ingest.Writer, 0, len(indexes))
for i := range indexes {
writerID := int(writerIDAlloc.Add(1))
writer, err := engines[i].CreateWriter(writerID)
if err != nil {
logutil.Logger(ctx).Error("create index ingest worker failed", zap.Error(err))
return nil
}
writers = append(writers, writer)
}
indexIDs := make([]int64, len(indexes))
for i := 0; i < len(indexes); i++ {
indexIDs[i] = indexes[i].Meta().ID
}
return &indexIngestLocalWorker{
indexIngestBaseWorker: indexIngestBaseWorker{
ctx: ctx,
tbl: tbl,
indexes: indexes,
copCtx: copCtx,
se: nil,
sessPool: sessPool,
writers: writers,
srcChunkPool: srcChunkPool,
reorgMeta: reorgMeta,
},
indexIDs: indexIDs,
backendCtx: backendCtx,
}
})
return &IndexIngestOperator{
AsyncOperator: operator.NewAsyncOperator[IndexRecordChunk, IndexWriteResult](ctx, pool),
}
}
type indexIngestExternalWorker struct {
indexIngestBaseWorker
}
func (w *indexIngestExternalWorker) HandleTask(rs IndexRecordChunk, send func(IndexWriteResult)) {
defer tidbutil.Recover(metrics.LblAddIndex, "indexIngestExternalWorkerRecover", func() {
w.ctx.onError(errors.New("met panic in indexIngestExternalWorker"))
}, false)
defer func() {
if rs.Chunk != nil {
w.srcChunkPool <- rs.Chunk
}
}()
w.indexIngestBaseWorker.HandleTask(rs, send)
}
type indexIngestLocalWorker struct {
indexIngestBaseWorker
indexIDs []int64
backendCtx ingest.BackendCtx
}
func (w *indexIngestLocalWorker) HandleTask(rs IndexRecordChunk, send func(IndexWriteResult)) {
defer tidbutil.Recover(metrics.LblAddIndex, "indexIngestLocalWorkerRecover", func() {
w.ctx.onError(errors.New("met panic in indexIngestLocalWorker"))
}, false)
defer func() {
if rs.Chunk != nil {
w.srcChunkPool <- rs.Chunk
}
}()
w.indexIngestBaseWorker.HandleTask(rs, send)
// needs to flush and import to avoid too much use of disk.
_, _, _, err := w.backendCtx.Flush(ingest.FlushModeAuto)
if err != nil {
w.ctx.onError(err)
return
}
}
type indexIngestBaseWorker struct {
ctx *OperatorCtx
tbl table.PhysicalTable
indexes []table.Index
reorgMeta *model.DDLReorgMeta
copCtx copr.CopContext
sessPool opSessPool
se *session.Session
restore func(sessionctx.Context)
writers []ingest.Writer
srcChunkPool chan *chunk.Chunk
}
func (w *indexIngestBaseWorker) HandleTask(rs IndexRecordChunk, send func(IndexWriteResult)) {
failpoint.Inject("injectPanicForIndexIngest", func() {
panic("mock panic")
})
result := IndexWriteResult{
ID: rs.ID,
}
w.initSessCtx()
count, nextKey, err := w.WriteChunk(&rs)
if err != nil {
w.ctx.onError(err)
return
}
if count == 0 {
logutil.Logger(w.ctx).Info("finish a index ingest task", zap.Int("id", rs.ID))
send(result)
return
}
result.Added = count
result.Next = nextKey
if ResultCounterForTest != nil {
ResultCounterForTest.Add(1)
}
send(result)
}
func (w *indexIngestBaseWorker) initSessCtx() {
if w.se == nil {
sessCtx, err := w.sessPool.Get()
if err != nil {
w.ctx.onError(err)
return
}
w.restore = restoreSessCtx(sessCtx)
if err := initSessCtx(sessCtx,
w.reorgMeta.SQLMode,
w.reorgMeta.Location,
w.reorgMeta.ResourceGroupName); err != nil {
w.ctx.onError(err)
return
}
w.se = session.NewSession(sessCtx)
}
}
func (w *indexIngestBaseWorker) Close() {
// TODO(lance6716): unify the real write action for engineInfo and external
// writer.
for _, writer := range w.writers {
ew, ok := writer.(*external.Writer)
if !ok {
break
}
err := ew.Close(w.ctx)
if err != nil {
w.ctx.onError(err)
}
}
if w.se != nil {
w.restore(w.se.Context)
w.sessPool.Put(w.se.Context)
}
}
// WriteChunk will write index records to lightning engine.
func (w *indexIngestBaseWorker) WriteChunk(rs *IndexRecordChunk) (count int, nextKey kv.Key, err error) {
failpoint.Inject("mockWriteLocalError", func(_ failpoint.Value) {
failpoint.Return(0, nil, errors.New("mock write local error"))
})
failpoint.Inject("writeLocalExec", func(_ failpoint.Value) {
OperatorCallBackForTest()
})
oprStartTime := time.Now()
vars := w.se.GetSessionVars()
cnt, lastHandle, err := writeChunkToLocal(w.ctx, w.writers, w.indexes, w.copCtx, vars, rs.Chunk)
if err != nil || cnt == 0 {
return 0, nil, err
}
logSlowOperations(time.Since(oprStartTime), "writeChunkToLocal", 3000)
nextKey = tablecodec.EncodeRecordKey(w.tbl.RecordPrefix(), lastHandle)
return cnt, nextKey, nil
}
type indexWriteResultSink struct {
ctx *OperatorCtx
backendCtx ingest.BackendCtx
tbl table.PhysicalTable
indexes []table.Index
rowCount *atomic.Int64
metricCounter prometheus.Counter
errGroup errgroup.Group
source operator.DataChannel[IndexWriteResult]
}
func newIndexWriteResultSink(
ctx *OperatorCtx,
backendCtx ingest.BackendCtx,
tbl table.PhysicalTable,
indexes []table.Index,
rowCount *atomic.Int64,
metricCounter prometheus.Counter,
) *indexWriteResultSink {
return &indexWriteResultSink{
ctx: ctx,
backendCtx: backendCtx,
tbl: tbl,
indexes: indexes,
rowCount: rowCount,
metricCounter: metricCounter,
errGroup: errgroup.Group{},
}
}
func (s *indexWriteResultSink) SetSource(source operator.DataChannel[IndexWriteResult]) {
s.source = source
}
func (s *indexWriteResultSink) Open() error {
s.errGroup.Go(s.collectResult)
return nil
}
func (s *indexWriteResultSink) collectResult() error {
for {
select {
case <-s.ctx.Done():
return s.ctx.Err()
case result, ok := <-s.source.Channel():
if !ok {
err := s.flush()
if err != nil {
s.ctx.onError(err)
}
return err
}
s.rowCount.Add(int64(result.Added))
if s.metricCounter != nil {
s.metricCounter.Add(float64(result.Added))
}
}
}
}
func (s *indexWriteResultSink) flush() error {
if s.backendCtx == nil {
return nil
}
failpoint.Inject("mockFlushError", func(_ failpoint.Value) {
failpoint.Return(errors.New("mock flush error"))
})
_, _, errIdxID, err := s.backendCtx.Flush(ingest.FlushModeForceFlushAndImport)
if err != nil {
if common.ErrFoundDuplicateKeys.Equal(err) {
var idxInfo table.Index
for _, idx := range s.indexes {
if idx.Meta().ID == errIdxID {
idxInfo = idx
break
}
}
if idxInfo == nil {
logutil.Logger(s.ctx).Error("index not found", zap.Int64("indexID", errIdxID))
return kv.ErrKeyExists
}
return convertToKeyExistsErr(err, idxInfo.Meta(), s.tbl.Meta())
}
logutil.Logger(s.ctx).Error("flush error",
zap.String("category", "ddl"), zap.Error(err))
return err
}
return nil
}
func (s *indexWriteResultSink) Close() error {
err := s.errGroup.Wait()
// for local pipeline
if bc := s.backendCtx; bc != nil {
bc.UnregisterEngines()
}
return err
}
func (*indexWriteResultSink) String() string {
return "indexWriteResultSink"
}